why does myArray.length is 3 here? I have added a new property in it, to my guess, it should be 4.
var myArray = [ "foo", 42, "bar" ];
myArray.baz = "baz";
myArray.length; // 3
- In the first line, you create a variable
myArrayand you add a value to it. Every variable in Javascript is an object, that has keys and properties (see more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
Between [] you create an array type, that stores data and labels them with numbers. (see more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- In the second line, you add a
bazproperty tomyArraywith"baz"value
- In the third line, you get the length property of the array
If you want to add a(n)
"baz"element to the end of the array, you can use the.push()method. For example:myArray.push("baz");
You need to use Array.prototype.push() to add new elements to array. In your code myArray.baz = "baz" doesn't do anything.
var myArray = [ "foo", 42, "bar" ];
// your approch
myArray.baz = "baz";
console.log(myArray.length); // 3
console.log(myArray) // [ "foo", 42, "bar" ]
// correct
myArray.push("baz")
console.log(myArray.length); // 4
console.log(myArray) // [ "foo", 42, "bar", "baz" ]