How do you explain this behavior of the map function?

  • 0
    little experience in js. And the question is most likely stupid, but still did not find information about this.
    let cord = [{x: 0, y: 0, type: 5, active: true}]
    console.log(cord)
    //x=5
    cord.map(elem => elem.x = 5)
    
    console.log(cord)
    //x=5

    as far as I know, map produces a new array, the variable of which needs to be equated
    JavaScript Molly Rowe, Feb 12, 2020

  • 3 Answers
  • 0
    In this case, the anonymous function in map changes the property x directly in the object - an array element that is passed to it by reference.

    The map function also has a result, it is [5].
    Anonymous

  • 0
    const cord = [{x: 0, y: 0, type: 5, active: true}]
    console.log(cord) // x = 0
    const newCoord = cord.map(elem => ({
    ...elem,
    x: 5
    }))
    console.log(cord) // x = 0
    console.log(newCoord) // x = 5
    Milo Riggs

  • 0
    In your case, something like this happens:

    function incrementX(obj) {
    obj.x += 1
    return obj
    }

    var a = {x: 0}
    var b = incrementX(a)

    console.log(b) // {x: 1}
    console.log(a) // {x: 1} -- Магия




    Objects in JS are passed by reference. That is, passing an object as an argument to a function, the latter can modify it, which can lead to undesirable effects.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!