Javascript Conditional Operators: if, ‘?’

Javascript Conditional Operators: if, ‘?’

Javascript Conditional Operators: if, ‘?’



There are five conditional statements in JavaScript:

  • We use else if to identify a new condition to test if the first condition is false; else if to identify a block of code to be executed, if a specified condition is true; else to identify a block of code to be executed, if the same condition is false;
  • We use ‘?’ as shorthand for an if...else statement.
  • We use switch to identify a lot of alternative blocks of code to be executed.

The “if” Statement

The if(...) statement is the most fundamental of the conditional statements, as it evaluates whether a statement is true or false, and runs only if the statement returns true. In case of a false result the code block will be ignored and the program will skip to the next section.

Syntax:

if (condition) {
  //if the condition is true block of code  executed 
}
We use if in lowercase letters because uppercase letters (If or IF) will generate a JavaScript error.

The condition in this example is a simple equality check (answer == 'yes'), but it can be much more complicated.

let answer = prompt('Do you like Web?', '');

if (answer == 'yes') {

  console.log('Thanks!');

}

When we execute more than one statement, we must write our code block inside curly brackets.

Syntax:

if (condition) {
  statement1;
  statement2;
}

Example of the if(...) with code block inside curly brackets:

if (true) {
  let message = 'Welcome to Web!'
  console.log(message);
}

We recommend you to write your code between curly braces {} every time you use an if statement, no matter that there is only one statement to execute, as it improves readability.

Nested if statement means an if statement inside that statement. JavaScript allows us to nest if statements within if statements. For example, we can place an if statement inside another if statement.

Syntax:

if (condition1) {
  //When condition1 is true it's executes 
  if (condition2) {
    //When condition2 is true it's executes 
  }
}

Boolean Conversion

The if(...) statement evaluates the expression in the parentheses converting the result to a boolean.

Let’s remember the conversion rules from the chapter Data Types:

  • An empty string "", a number 0, null, undefined, and NaN become false. That’s the reason why they are called “falsy” values.
  • Other values become true and they are called “truthy”.

So this code would never execute:

if (0) { // 0 is falsy
  ...
}

This one will:

if (1) { // 1 is truthy
  ...
}
if (1) {
 console.log('Welcome to Web!');
}

The “else” Statement

The if(...) statement can contain an optional else block, which executes when the condition is false.

The else statement should be written after the if statement, and has no condition in parentheses. Here is the syntax for a simple if...else statement.

if (condition) {
  //this code  will execute if the condition is true
} else {
  // this code  will execute if the condition is false
}

Example of the “else” statement:

let i = 16;
if (i != 16 ) {
  console.log("it’s not i");
} else {
  console.log("it’s i");
}

The “else if” Statement

The else if statement let us to test several variants of a condition when we need more than two options. In other words, we use the else if statement to specify a new condition if the first one is false.

Syntax:

if (condition) {
  statement;
} else if (condition) {
  statement;
  .
  .
} else {
  statement;
}

Example of the else if statement:

let number = prompt('Guess the secret number?', '');
if (number > 16) {
  console.log("The number is smaller!");
} else if (number < 16) {
  console.log("The number is greater!");
} else {
  console.log("You guessed!")
}

In the example above, JavaScript first checks number > 16. If it is falsy, it goes to the next condition number < 16. If it is falsy as well, it will show the last alert. There can be more else if blocks, the last and final else is optional.

JavaScript will try to run all the statements in order, and will default to the else block if none of them are successful. In case of many else ifstatements, the switch statement can be preferred for readability.

Conditional operator ‘?’

The “conditional” or “question mark” operator lets us in a shorter and simpler way assign a variable. The operator is also called “ternary”, because it has three operands. It is actually the only JavaScript operator that has that many. Conditional (ternary) statements are an integral part of all programming languages, which used to perform different actions based on different conditions. For doing that you can use the if statement and the conditional operator ‘?’ (“question mark”) in your code.

Example of the conditional operator:

let booleanValue;
let number = prompt('Guess the secret number?', '');
if (number != 18 ) {
  booleanValue = false;
} else {
  booleanValue = true;
}
console.log(booleanValue);

Syntax:

let result = condition ? value1 : value2;

If the condition is true, the operator returns the value of value1; otherwise, it returns the value of value2.

Condition: An expression that evaluates to true or false.

Example of the condition:

let booleanValue = (number != 18) ? false : true;

The example executes the same thing as the previous one, but parentheses make the code more readable, so we recommend using them.

// the comparison operator "number != 18" executes first anyway
// (no need to wrap it into parentheses)
let booleanValue = number != 18  ? false : true;
You can avoid using the question mark operator in the example above, because the comparison itself returns true/false:
// the same
let booleanValue = number > 18;

Multiple ‘?’

An arrangement of question mark operators ? can return a value that depends on more than one condition.

let number = prompt('number?', '');

let message = (number < 16) ? "The number is smaller!":

(number > 16)  ? "The number is greater!" :"You guessed!"

console.log( message );

It can seem difficult for you to understand, but after a closer look, you can see that it’s just a standard sequence of tests:

  • The first? checks if number < 16.
  • In case it is true – it returns "The number is smaller!". If not, it continues to the expression after the colon ":", checking number > 16.
  • If that’s true – it returns"The number is greater!". If not, it continues to the expression after the next colon ":".
  • And returning 'You guessed!'.

Non-traditional use of ‘?’

Sometimes we use the question mark? as a replacement for if:

let number = prompt('Write the number', '');

(number == 16) ? console.log("it’s right number") : console.log("it’s wrong number");

Either the first or the second expression after the question mark gets executed showing an alert, what depends on the condition number == 16.

In this case, we don’t assign a result to a variable, but execute different code depending on the condition. Note, that it’s not recommended to use the question mark operator in this way.

The reason is the notation, which is shorter than the equivalent if statement, that appeals to some programmers.

Let’s look at the same code using if for comparison:

let number = prompt('Write the number', '');

if (number == 16) {

  console.log("it’s a right number")

} else {

  console.log("it’s a wrong number");

}

Here the code is located vertically. It’s easier to understand the code blocks which span several lines than a long, horizontal instruction set.

The main purpose of the question mark operator is to return one value or another, it depends on its condition. So use it for exactly that, when you need to execute different branches of code.




Reactions

Post a Comment

0 Comments

close