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?
>Solution :
The version with && only creates the object if the value of myVar isn’t falsey.
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 = null;
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.