Search code examples
javascriptnode.jsobjectecmascript-6javascript-objects

conditionally deconstruct object (javascript)


I want to check an argument, if it was undefined (or false), I will assign a value to it by deconstructing an object

function test(x){
  let obj={x:1,y:2}
  if(!x){x}=obj;
}

note: I don't want to use a temporary variable

if(!x){
  let {temp}=obj;
  x=temp
}

Solution

  • You can not reassign a value to a variable which is passed as an argument to a function. If it is an object, you can, however, add/modify the properties of that object. But reassigning it will make it lose the reference it was holding from the argument. In your case, if something is undefined, you can not update that reference to hold a value.

    For example, in your code -

    function test(x){
      let obj={x:1,y:2}
      x = x || obj.x
    }
    let x = undefined
    test(x)
    console.log(x)  // x is still undefined

    What you can do is keep an object and update its properties using a function

    function test(a){
      let obj={x:1,y:2}
      a.x = a.x || obj.x
    }
    let a = {}
    test(a)
    console.log(a.x)  // a.x equals to 1 now