1

I recently came across the following piece of sample code:

function range(upto) {
  var result = [];
  for (var i = 0; i <= upto; i++) {
    result[i] = i;
  }
  return result;
}

and I'm confused as to why:

result[i] = i;

as opposed to:

i = result[i];

Isn't 'i' the variable and 'result[i]' the value?

1
  • No, result[i] is the variable and i is the value it is being set to. The purpose of that line of code is to set the variable result[i] to the value i. Commented Sep 7, 2013 at 20:11

3 Answers 3

2

This fills the array :

result[0] = 0 // sets the first cell of the array to the value 0
result[1] = 1
etc.

This function returns

[0, 1, 2, ... upto]

More about arrays in JavaScript

Sign up to request clarification or add additional context in comments.

Comments

1

The

result[i] = i;

assigns the value of i to the i-th element of result.

Thus, result[0] becomes 0, result[1] becomes 1 and so on.

Comments

0
  • result[i] = i; means you are assigning the value of i to the index i of the array result.

  • i = result[i]; means you are assigning the value of the i-th index of the array result,to the variable i.

That's it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.