let sale = true if(sale){ console.log('Time to buy!') }
let sale = true sale = false if(sale) { console.log('Time to buy!') } else{ console.log('Time to wait for a sale.') }
let hungerLevel = 7 if(hungerLevel>7){ console.log('Time to eat!') } else{ console.log('We can eat later!') }
and
operator (&&
)or
operator (||
)not
operator, otherwise known as the_bang_operator (!
)let mood = 'sleepy'; let tirednessLevel = 6; if((mood === 'sleepy') &&(tirednessLevel >8)){ console.log('time to sleep') } else{ console.log('not bed time yet') }
考慮non-boolean data types
code
表示錯誤
的有字符串
0
""
or''
空字符串null
which represent when there is no value at allundefined
which represent when a declared variable lacks a value 未定義變量NaN
, or Not a Number||
or statements check the left-hand condition firstget
因此這兩個是等價的string
let defaultName if (username) { defaultName = username } else { defaultName = 'Stranger' }let defaultName = username || 'Stranger';
let tool = 'marker'; let writingUtensil = tool ||'pen' console.log(`The ${writingUtensil} is mightier than the sword.`);The pen is mightier than the sword.
let tool = ''; let writingUtensil = tool ||'pen' console.log(`The ${writingUtensil} is mightier than the sword.`);The marker is mightier than the sword.
三元運算符it
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
?
前面?
後面有兩個待執行語句,用:
隔開:
前面的),爲假執行第二個(:
後面的)let stopLight = 'yellow' if (stopLight === 'red'){ console.log('Stop!') } else if (stopLight === 'yellow'){ console.log('Slow down.') } else if (stopLight === 'green'){ console.log('Go!'); } else{ console.log('Caution, unknown!') }
let athleteFinalPosition = 'first place'; switch(athleteFinalPosition){ case (athleteFinalPosition === 'first place'): console.log('You get the gold medal!') break case (athleteFinalPosition === 'second place'): console.log('You get the silver medal!') break case (athleteFinalPosition === 'third place'): console.log('You get the bronze medal!') break default: console.log('No medal awarded.') break }