Imperative Code

Gaurav Dubey
1 min readJan 27, 2021

According to wiki imperative means “expressing the commands” .

But we talk about imperative in JavaScript is means very different ,

Lets talk about that what is imperative code in JavaScript basically imperative coding is telling java Script what to do and how to do.

const people = ['Ama', 'Frann', 'Greoff', 'Kiren', 'Rechard', 'Tylor']
const excitedPeople = []

for (let i = 0; i < people.length; i++) {
excitedPeople[i] = people[i] + '!'
}

If you’ve worked with JavaScript any length of time, then this should be pretty straightforward. We’re looping through each item in the people array, adding an exclamation mark to their name, and storing the new string in the excitedPeople array. Pretty simple, right?

This is imperative code, though. We’re commanding JavaScript what to do at every single step. We have to give it commands to:

  • set an initial value for the iterator — (let i = 0)
  • tell the for loop when it needs to stop - (i < people.length)
  • get the person at the current position and add an exclamation mark — (people[i] + '!')
  • store the data in the ith position in the other array - (excitedPeople[i])
  • increment the i variable by one - (i++).

--

--