0

I wanna know when do we use logical operators with non-booleans in a real project also in experimental tests (exactly I mean something like var a = name || 'Adele'; at the example code, where one of the two operands of a logical operator is non-boolean)?

For example, in the program below, someone said " when we're not sure that name already has a value or not, as a callback, we add || 'Adele' to that ". But also I want to know more about such usage.

Thanks!

var name;
//
//
//
var a = name || 'Adele';
console.log(a); // ...
  • Seems like a duplicate question on "truthy"? In general, if `name` is explictly `false` or `undefined`, the expression will return true because "Adele" is defined. Also if name is numerical `0` then the `||` will take into consideration the literal string. – GetSet Apr 11 '20 at 12:26
  • Does this answer your question? [Why are logical operators in JavaScript left associative?](https://stackoverflow.com/questions/20591876/why-are-logical-operators-in-javascript-left-associative) – Utsav Patel Apr 11 '20 at 12:29
  • Thanks, but it wasn't what I want (and mean). – 01hossein10 Apr 11 '20 at 16:07
  • https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation https://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean https://stackoverflow.com/questions/3163407/javascript-and-operator-within-assignment https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – VLAZ Apr 11 '20 at 16:11

1 Answers1

0

I'm not sure about your question but in real projects, you use logical operators like that:

var person = input('Enter your name: ');
if (person == 'john' || person == null) {
 // gets executed even if input is empty
}

var age = 20;
if (person == 'john' && age == 20) {
print("you're john and you're 20");
}

Hope that answers your question!