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

129
Views
What am I missing in this Javascript Array behavior?

I tried this in the chrome dev tools console:

let a = [[null,null],[null,null]]

function na(){ return Array(2).fill(Array(2)) }
let b = na();

console.log(JSON.stringify(a))
// [[null,null],[null,null]]

console.log(JSON.stringify(b))
// [[null,null],[null,null]]

So far, so good. I was expecting both a and b with the same values and strucuture. Then I wanted to test a small function that should append an extra value in each line:

function add(x) { x.map( line => line.push(null) )}

add(a)
console.log(JSON.stringify(a))
// [[null,null,null],[null,null,null]]

add(b)
console.log(JSON.stringify(b))
// [[null,null,null,null],[null,null,null,null]]
// ?! I was not expecting this extra value here...

Well, that was unexpected. Why is that extra null appearing in add(b) ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

function na(){
    return Array(2).fill(Array(2))
}

na() fills the empty Array(2) with shallow copies of the second Array(2) object.

As a result changing values in any of the clones changes the Array's value everywhere.

a = Array(5).fill(Array(3))

a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

console.log(JSON.stringify(a))

So because b has 2 elements and you are using .push() to add an element to b for each of the (same) arrays, 2 new elements are added to the array.

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!