Info
Demo 3.4Conditional logic using
Conditional logic using if...then statements
Files in this demo
├─ index.html └─ script.js
An if statement runs code only when something is true.
if (hour < 12) {
console.log("Good morning!");
}
The condition goes in round brackets. The code goes in curly braces.
Branching
if (a) {
// when a is true
} else if (b) {
// when a is false and b is true
} else {
// when neither is
}
JavaScript checks the branches top to bottom and stops at the first true one, so the order you write them in changes the result.
Truthy and falsy
Anything can be used as a condition. These six count as false:
false, 0, "" (empty string), null, undefined, NaN
Everything else counts as true ~ including "0", "false" and an empty array, all of which have confused people at three in the morning.
This is why you often see:
if (name) {
// runs when name has any content at all
}
The ternary
const label = hour < 12 ? "AM" : "PM";
Condition, ?, value-if-true, :, value-if-false. Perfect for choosing between two values. Please don’t nest them ~ I’ve read that code and I didn’t enjoy it.
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z
Undo / redo
Tab / ⇧ TabTab / ⇧ Tab
Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [
Indent / unindent lines
⌘ ACtrl A
Select all
⌘ DCtrl D
Select next occurrence of selection
⌘ /Ctrl /
Comment / uncomment lines
Ctrl SpaceCtrl Space
Autocomplete
Ctrl EnterCtrl Enter
Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ]
Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation,
shortcuts and the info panel still work in the meantime.
Settings
View
Font size
14
Code
Preview
Delay
Zoom
Share
Reset
Preview
Currently previewing:
Dimensions0 × 0
Delay
Preview paused
Click to resume
Click to resume
The preview is disabled for this demo.
Use the console below.
Use the console below.
Console
›