Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading