8

In JavaScript, I have an array, which is

array = [true, false]

In some cases, I am trying to initialize this array

array.map(item => {
   item = false
})

After running the above code, the array is not changed, it is still [true, false], so is .map not reliable sometimes?

But after running my below code, the array is changed. Why does it work in this case?

let array = [{id:1, checked: false}, {id:2, checked:true}]
array.map(item => {
    item.checked = true
})

array becomes [{id:1, checked: true}, {id:2, checked:true}]

1
  • .map function doesn't change original array, it returns another array which you should use. Commented Feb 15, 2017 at 6:44

4 Answers 4

10

JavaScript Array map() Method

*)creates a new array with the results of calling a function for every array element and it calls the provided function once for each element in an array, in order.

Note: map() Method does not execute the function for array elements without values and it does not change the original array.

more details

Sign up to request clarification or add additional context in comments.

Comments

5

Array map function is working fine. The map() method creates a new array with the results of calling a provided function on every element in this array. map() does not mutate the array on which it is called.

var array = [true, false]



var new_array = array.map(function(item) {
  return false;
});

console.log(array)
console.log(new_array)

Comments

4

If your mapping is simple, you can do:

var array = [true, false];
array = array.map(_ => false);

console.log(array);
// [false, false]

1 Comment

Using an underscore as a variable name is sometimes used when you're not actually going to use the variable for anything. It's purely a style-thing.
0

.map() method is not mutable, check out its return value:

var arr2 = array.map(item => false)
console.log(arr2)

In functional programming, it's recommended that values do not change often, and JavaScript borrowed it. At least for .map() and .reduce() this is true. Make sure you know .map() well.

Comments

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.