0

Can someone please help me understand why the following array length increments without having a counter.

var inputName = "";
var namesArray = new Array();

while ( (inputName = prompt("Enter a name", "")) != "") {
    namesArray[namesArray.length] = inputName;
}

namesArray.sort();

var namesList = namesArray.join("\n");

console.log(namesList);

So from this I am assuming, a while loop increments any value you include inside the while loop. I had a look at MDN While Loop and I can see that both the x in this example is also incrementing.

I just want to be sure that I got this correct but mainly understand why it does this.

Thanks

2
  • the length is not a counter... once you put data in the array, the size increases Commented Dec 15, 2014 at 11:48
  • 1
    Doing assigment directly in the while loop, is generally not very good practice. Commented Dec 15, 2014 at 11:48

4 Answers 4

1

Adding an item into an array can be done in several ways in Javascript

your code essentially does a push, so you could replace

namesArray[namesArray.length] = inputName

with

namesArray.push(inputName)
Sign up to request clarification or add additional context in comments.

Comments

0

For an empty array, length property will be 0. Let's put it like this

1st iteration

while ( (inputName = prompt("Enter a name", "")) != "") {
    namesArray[namesArray.length] = inputName;
    // namesArray[0] = inputName;
}

2nd iteration

while ( (inputName = prompt("Enter a name", "")) != "") {
    namesArray[namesArray.length] = inputName;
    // namesArray[1] = inputName; // since now length is 1
}

And so on.. So what you're doing is assigning in following fashion

names[0] = inputName
names[1] = inputName 
...

So, the length increases from 0 to n as you're adding elements to the Array.

2 Comments

Thanks Amit. I like answers like this where examples are provided.
@KamMiah ah! glad to have helped :)
0

The length property of a Javascript array is the highest subscript plus one. So, if there are eight elements in an array, they have indices 0 - 7 and length is 8. The assignment statement, namesArray[namesArray.length] = inputName; adds an element to the array, and so increases the length.

Comments

0
   while (condition) {// Condition either return true or false so loop will execute untill condition return false
     namesArray[namesArray.length] = inputName //you just push data into array
    }

1 Comment

Please edit your answer in order to add a context to the code (the comments are ok but it's not sufficient).

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.