Logical Operators in JavaScript

Logical operators in JavaScript can be a clean and simple way to return or set values without introducing extra if statements.

console.log(true || false);                //true
console.log(true && false);                //false
console.log(true && 0 && false);           //0
console.log(true && 'string' && 1);        //1
console.log(false || 'string' || false);   //string
console.log(false || 0 || 'string');       //string
console.log(false || 1 && 'string');       //string
console.log(false || 1 && 0 && 'string');  //0
console.log(false || 1 && 0 || 'string');  //string

This comes in hand when you want to make sure a variable has a value. This can be a concise way of preventing errors.

var persons = [
    {id: 1, name: 'joe', age: 22},
    {id: 2, name: 'harry', age: 59},
    {id: 3, name: 'will', age: 30}
];
var index = 19;
var person = persons[index];
console.log(person.name); //error

Well that’s no good. Let’s say index is derived from user input and you don’t want it to error if the index is out of bounds:

console.log(person && person.name); //undefined

Much better. You could also test index. If it’s not a valid value, then set it to a default.

index = index < persons.length || 0; //0
var person = persons[index];
console.log(person && person.name); //joe

This is a very contrived example, but hopefully you get the idea.

Arguably, adding logical operators on the same line doesn’t always make for the most readable code, but with practice I’ve found it to be quite readable and concise, as long as you don’t pack too many operations on one line.

That said, it’s not always easily tested. Each line of code performs multiple functions, so you can’t put break points right where you want them.

More JavaScript