Home > Enterprise >  what is the different between (myVar && { myVar }) and { myVar }
what is the different between (myVar && { myVar }) and { myVar }

Time:09-05

I have seen few JavaScript repositories online where an object is created in the following syntax

const myVar

const myObj = (myVar && {myVar})

I'm wondering why do we need to use this syntax, when the same output can be acheived by simply declaring the object like this:

const myObj = {myVar}

Is there any difference between those two?

CodePudding user response:

The version with && only creates the object if the value of myVar isn't falsey. If it's falsey, it will get the value of myVar as it is, not wrapped in an object.

Compare these examples:

let myVar1 = 10;
let myObj1_and = (myVar1 && {myVar1});
let myObj1_noand = {myVar1};
console.log(myObj1_and);
console.log(myObj1_noand);

let myVar2 = 0;
let myObj2_and = (myVar2 && {myVar2});
let myObj2_noand = {myVar2};
console.log(myObj2_and);
console.log(myObj2_noand);

Without the &&, it creates the object regardless of the value of the variable.

  • Related