Conditional Statements and Jump Statements Flashcards

1
Q

Conditional statements
2 broad ways

Can you use semicolons?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the correct syntax of switch statement?

How to make a statement run no others do?

A
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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does this do?

if (result = someFunction()) {

}

Why can this work?

A
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) {
...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is this correct?

if (x > 2) console.log(‘yes’);

A

Yes. You don’t necessarily need { } with single statements.

but always do

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
Is this correct?
let x = 4;
if (x > 2) console.log('yes');
else if (x == 2) console.log('maybe');
else console.log('no');
A

Yes. You don’t necessarily need { } with single statements.

but always do

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what happens within the parentheses of:

if (…)

A

it is converted to Boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
Is this correct?
if (x>2) console.log('yes');
else if (x==2) console.log('maybe');
console.log('fsds');
else console.log('no');
A

No

the last else doesn’t know it’s a part of a conditional chain and will throw an error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is the ? conditional operator used for

A
for conditional statements with this syntax:
let accessAllowed = (age > 18) ? true : false;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which works?
(age > 18) ? true : false;
age > 18 ? true : false;
Why?

A

Both work.
? has lower precedence than >
But use parenthesis for readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly