Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

370
Views
why array length in JavaScript does not change after adding property?

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. In the first line, you create a variable myArray and 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)

  1. In the second line, you add a baz property to myArray with "baz" value
  1. 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");

about 4 years ago · Juan Pablo Isaza Report

0

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" ]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!