Console Learner — An interactive JavaScript course.


5.5 Idioms

>>>
var obj = { text: 'ok'};


  
>>>
obj.missing || 'default'
"default"
As previously mentioned, boolean logic is commonly used to provide default values. The ?? nullish coalescing operator (introduced with ES11 in 2020) is a recent alternative in many cases.
>>>
obj && obj.text
"ok"
It is also common to use boolean logic to avoid issues with possible null references. The ?. optional chaining operator (introduced with ES11 in 2020) simplifies this further.
>>>
obj && print(obj);

  
A third way of using boolean conditions is the cond && operation idiom. This code style avoids an if statement for short operations.
>>>
[0, 1, true, false, '', ' ', null, undefined].filter(Boolean)
[1, true, " "]
The built-in Boolean function coerces any value into a boolean. This is useful when filtering out null or empty values from an array. But note that 0 and false are also removed.
>>>
new Array(4).fill(0).map(Math.random).map(v => v * 10).map(Math.floor).join('-')
"0-1-2-3"
Some objects, such as Array, have methods that either return a new instance or a reference to itself. This makes it possible to use method chaining to avoid intermediate result variables.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.