Quick tip for arrays in JavaScript

The reason

“An object needs a key and value”

let foo = [1, 2, 3]// Is internally for JS something of the likes oflet foo = {
  "0": 1,
  "1": 2,
  "2": 3,
}// And that is why you can access it withfoo[0]
foo[1]
foo[2]// If object properties/methods could be numbers you could access in this case like sofoo.0
foo.1
foo.2

What does it mean

By reference

let firstObject = {
  foo: 1,
}console.log(firstObject) // {foo: 1}let secondObject = firstObjectsecondObject.bar = 2console.log(firstObject) // {bar: 2, foo: 1}
console.log(secondObject) // {bar: 2, foo: 1}
let firstObject = {
  foo: 1
}
let secondObject = {}for (let key in firstObject) {
  secondObject[key] = firstObject[key]
}secondObject.bar = 2console.log(firstObject) // {foo: 1}
console.log(secondObject) // {bar: 2, foo: 1}
let secondObject = Object.assign({}, firstObject)

For…in

let foo = [1, 2, 3]foo.bar = 4for (let key in foo) {
  console.log('--->', key) // this will output "0", "1", "2", "bar"
}

Conclusion


Nearsoft Solutions

Business and tech related articles

Diogo Spínola

Written by

Learning enthusiast, web developer @nearsoftsolutio

Nearsoft Solutions

Business and tech related articles