DEV Community

shinyo627
shinyo627

Posted on • Updated on

JS Truthy Falsy assignment /Short circuit evaluation.

let username = '';
let defaultName;

if (username) {
  defaultName = username;
} else {
  defaultName = 'Stranger';
}

console.log(defaultName); // Prints: Stranger
Enter fullscreen mode Exit fullscreen mode

Truthy Falsy evaluations open a world of short-hand possibilities.


let username = '';
let defaultName = username || 'Stranger';

console.log(defaultName); // Prints: Stranger
Enter fullscreen mode Exit fullscreen mode

If you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment:

Top comments (0)