-1

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
}
4
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 12, 2018 at 13:59
  • It's not clear from your example what you're trying to achieve. You're creating an object only to deconstruct it again. What's the point? Why not create an object with those variables and you wouldn't have to deconstruct it. What are you returning from the function? The object, x? You should really provide your quesiton with more details. Commented Dec 12, 2018 at 14:18
  • the function is just simplified, and it is very clear that it accebts an object, but if no argument passed it will use a default one Commented Dec 12, 2018 at 15:11
  • 1
    Please, provide your real code instead of abstractions. Why should obj be defined in function scope? As it was said, it's unclear what you're trying to achieve. Commented Dec 12, 2018 at 15:20

3 Answers 3

0

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

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

1 Comment

thank you, I used if(!x) x=obj.x
-1

Do you mean to assign a default value if undefined or false?

x = x || {};

1 Comment

No, I mean that I want to deconstruct the default object if no argument passed
-1

Override x value with in the function and return it like this Code below

function test(x){
   let obj={x:1,y:2}
   if(!x)x=obj;
   if(x.hasOwnProperty('x')){
   return x.x;
   }
   else{
    return "object does not have property x";
}
}
console.log(test(undefined));    //  {x:1,y:2}
console.log(test(false));    //  {x:1,y:2}
console.log(test(true));    //  true

2 Comments

I want to deconstruct the object, so I get the value of x whitch is inside it
Here it assign object to the x from the function if x undefined or false ,else it will return initial value of x is that what you want ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.