Skip to main content

Conditional Branching in JavaScript

JavaScript Fundamentals: Conditional Branching

Can you execute more than one statement in an if statement?

View Answer:
Interview Response: Yes, but they must be encased in curly brackets . Even if just one sentence has to run, this improves readability and is encouraged.

Code Example:

if (year == 2015) {
alert("That's correct!");
alert("You're so smart!");
}

What type of conversion does the JavaScript “if” statement use?

View Answer:
Interview Response: The if (_) statement evaluates the expression in its parentheses and converts it to a true or false Boolean value.

Can you pre-evaluate a condition for use in an if statement?

View Answer:
Interview Response: Yes, we can pass a pre-evaluated condition in a value to an if statement.

Code Example:

let cond = year == 2015; // equality evaluates to true or false
if (cond) {
alert('Hello, World'); // returns Hello, World
}

Is there a way to handle falsie conditions in an if statement?

View Answer:
Interview Response: We can use an if-else statement to handle false conditions.

Technical Response: Yes, the “if” statement may contain an optional “else” block. It executes when the condition is false.

Code Example:

let year = prompt('In which year was the ECMAScript-2015 published?', '');

if (year == 2015) {
alert('You guessed it right!');
} else {
alert('How can you be so wrong?'); // any value except 2015
}

If you want to test a variety of circumstances. What kind of conditional statement can you use with an if statement?

View Answer:
Interview Response: To test several conditions in an if statement, you must add an “else if” statement. There can be more than one else if block and the final else is optional.

Code Example:

let year = prompt('In which year was the ECMAScript-2015  published?', '');

if (year < 2015) {
alert('Too early...');
} else if (year > 2015) {
alert('Too late');
} else {
alert('Exactly!');
}

Can you assign a variable depending on a condition in an if statement?

View Answer:
Interview Response: Yes, you can assign a variable depending on a condition in an if statement.

Code Example:

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {
accessAllowed = true;
} else {
accessAllowed = false;
}

alert(accessAllowed);

Is there a shorthand version of the if statement that you can use in JavaScript?

View Answer:
Interview Response: We can use the ternary operator shorthand syntax.

Technical Response: Yes, the condition/ternary (?) operator can be used to shorten the implementation of a conditional statement.

Code Example:

// the comparison operator "age > 18" executes first anyway
// (no need to wrap it into parentheses)
let accessAllowed = age > 18 ? true : false;

Note: Because the comparison itself gives true/false, you may eliminate using the question mark operator in the above example:

// the same
let accessAllowed = age > 18;