Conditional Statements and Jump Statements Flashcards
Conditional statements
2 broad ways
Can you use semicolons?
if
if else
else
ternary operator
1 == 1 ? ‘statement’ : ‘statement’
1 == 1 ? 'statement' : 2===2 ? 'statement' : 'statement' (unless an "if" conditional statement, you have to have the (else) : or it breaks) semicolons anywhere throw an error
What is the correct syntax of switch statement?
How to make a statement run no others do?
switch (variable) { case 5: console.log('a is 5'); break; case 6: console.log('a is 6'); break; default: console.log('a is neither 5, nor 6'); break; }
What does this do?
if (result = someFunction()) {
…
}
Why can this work?
let name; if (name = getNameFromUser()) { console.log(`Hi ${name}`); } else { console.log("you must enter your name!"); }
In the conditional, it gets a name from the user. Basically, if that name exists, it will be truey. But it looks like a mistake so don’t do it.
Instead do:
let result = somefunction(); if (result) { ... }
Is this correct?
if (x > 2) console.log(‘yes’);
Yes. You don’t necessarily need { } with single statements.
but always do
Is this correct? let x = 4; if (x > 2) console.log('yes'); else if (x == 2) console.log('maybe'); else console.log('no');
Yes. You don’t necessarily need { } with single statements.
but always do
what happens within the parentheses of:
if (…)
it is converted to Boolean
Is this correct? if (x>2) console.log('yes'); else if (x==2) console.log('maybe'); console.log('fsds'); else console.log('no');
No
the last else doesn’t know it’s a part of a conditional chain and will throw an error
what is the ? conditional operator used for
for conditional statements with this syntax: let accessAllowed = (age > 18) ? true : false;
Which works?
(age > 18) ? true : false;
age > 18 ? true : false;
Why?
Both work.
? has lower precedence than >
But use parenthesis for readability.