173. ES2020 part3

변지영·2022년 3월 8일
0

Nullish Coalescing Operator ??

?? can be used instead of OR operator,||.
Let's add a new property, power.
pikachu have the 'lightning'.

let andrei_pokemon = {
	pikachu: {
		species: 'Mouse Pokemon',
		height: 0.8,
		weight: 30
		power: 'lightning'
	}
}

let power = andrei_pokemon?.pikachu?.power|| 'no power'

console.log(power)

we weren't sure that we had this property(power)
power?.
we can't use an optional chaining operator.

let power = andrei_pokemon?.pikachu?.power || 'no power'
so let's use OR operator.

let's imagine that we have an empty string or not even the property.

let andrei_pokemon = {
	pikachu: {
		species: 'Mouse Pokemon',
		height: 0.8,
		weight: 30
	}
}

let power = andrei_pokemon?.pikachu?.power|| 'no power'

console.log(power)

with empty string

let andrei_pokemon = {
	pikachu: {
		species: 'Mouse Pokemon',
		height: 0.8,
		weight: 30,
        power: ''
	}
}

let power = andrei_pokemon?.pikachu?.power|| 'no power'

console.log(power)

OR operator works by checking if this is Truthy.

What if the power is false?

let andrei_pokemon = {
	pikachu: {
		species: 'Mouse Pokemon',
		height: 0.8,
		weight: 30,
        power: false
	}
}

let power = andrei_pokemon?.pikachu?.power|| 'no power'

console.log(power)

If pikachu is evolving and doesn't have any power,
I don't necessarily want to say no power.
we can do the nullish coalescing.

?? (Nullish coalescing)

This doens't check if a value is Falsy.
Instead, it checks if it's null or undefined.

let andrei_pokemon = {
	pikachu: {
		species: 'Mouse Pokemon',
		height: 0.8,
		weight: 30,
		power: 0
	}
}

let power = andrei_pokemon?.pikachu?.power ?? 'no power'

console.log(power)

0개의 댓글