Define default values in JavaScript
In JavaScript, it's possible to use the ||
operator to define default values. That is, if the expression evaluates to 0
, ''
, null
, false
, or undefined
, the defined default value will be used instead.
Let's look at the following code example:
function printFruit(fruit) {
console.log(fruit);
}
printFruit('apple'); // 'apple'
printFruit('mango'); // 'mango'
printFruit(); // undefined
printFruit(0); // 0
printFruit(''); // ''
printFruit(null); // null
printFruit(undefined); // undefined
In the example above, we have a simple function that logs the 'fruit' it receives to the console. However, if it receives a falsy
value such as 0
, ''
, null
, false
, or undefined
, those are what get printed.
This can be prevented by using the ||
operator:
function printFruit(fruit) {
// fruit = fruit || 'pear'
// console.log(fruit)
console.log(fruit || 'pear');
}
printFruit('apple'); // 'apple'
printFruit('mango'); // 'mango'
printFruit(); // 'pear'
printFruit(0); // 'pear'
printFruit(''); // 'pear'
printFruit(null); // 'pear'
printFruit(undefined); // 'pear'
It's good to be cautious when using the ||
operator because if at some point a value like 0
or ''
is desired and a default value is defined, the default will be used instead.
Another way to define default values is through function parameters, which I wrote an article about called Default parameters in JavaScript.