It is like a fallback. If numero
is a falsy
value (false
, ''
, undefined
, null
, NaN
, 0
) it will set the value to 1
.
As we can see here in these two tests, if a values is not passed it will use the fallback otherwise it will use the value passed as a parameter.
function test(value) {
console.log(value || 'Not Set')
}
test()
test('Awesome')
There are also more advanced ways which work differently but also produce the similar effect. Here we can do the complete opposite by using &&
instead which will only run the next item if the previous command is truthy
.
let items = []
function addItem(a) {
let contains = items.includes(a)
!contains && items.push(a)
}
addItem('cat')
addItem('dog')
addItem('pig')
addItem('cat')
addItem('cat')
console.log(items)
In the above we use &&
instead which will do the exact opposite of ||
, so if contains
is true, we run the next command, otherwise end the current statement.
Lastly, we can combine the two and get a whole new result:
let items = []
function addItem(a) {
let contains = items.includes(a)
!contains && a % 2 == 0 && items.push(a) || console.log('Item', a, 'is not valid')
}
addItem(1)
addItem(2)
addItem(10)
addItem(15)
addItem(10)
addItem(100)
addItem(102)
addItem(103)
console.log(items)
And with this example we only insert items into the array if they are not already in the array and are an even number. otherwise we will output that the value isn't a valid insert either because it was already in the array, or it wasn't event.