Search code examples
javascriptarraysdestructuring

TypeError when swapping object properties with destructuring assignment


I am trying to swap two object values in JavaScript using the [] = [] method, but my below code fails with an error saying "message": "Uncaught TypeError: Cannot set property '9' of undefined",

let dataObj={"reg_price":2, "reg_price_alt":5, "ex":9}
console.log("before: ", dataObj)
[dataObj.reg_price, dataObj.ex] = [4, 5];
console.log("after: ", dataObj)

Is there some syntax I'm missing? I don't understand why this simple code does not work.


Solution

  • The syntax is fine. Add a semicolon to prevent the automatic semicolon insertion from thinking you want to do console.log(...)[...] instead of array destructuring:

    let dataObj = {"reg_price":2, "reg_price_alt":5, "ex":9}
    console.log("before: ", dataObj); // <-- semicolon
    [dataObj.reg_price, dataObj.ex] = [4, 5]
    console.log("after: ", dataObj)

    I'd take this a step further and add semicolons after every line. Caveat emptor otherwise. Example of swapping values:

    const o = {a: 0, b: 1};
    console.log(o);
    [o.a, o.b] = [o.b, o.a];
    console.log(o);