Using if in java script

Conditional branching: if, ‘?’

Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the if statement and the conditional operator ? , that’s also called a “question mark” operator.

The “if” statement

The if(. ) statement evaluates a condition in parentheses and, if the result is true , executes a block of code.

let year = prompt('In which year was ECMAScript-2015 specification published?', ''); if (year == 2015) alert( 'You are right!' );

In the example above, the condition is a simple equality check ( year == 2015 ), but it can be much more complex.

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

We recommend wrapping your code block with curly braces <> every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.

Boolean conversion

The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean.

Читайте также:  Java how to initialize map

Let’s recall the conversion rules from the chapter Type Conversions:

  • A number 0 , an empty string «» , null , undefined , and NaN all become false . Because of that they are called “falsy” values.
  • Other values become true , so they are called “truthy”.

So, the code under this condition would never execute:

…and inside this condition – it always will:

We can also pass a pre-evaluated boolean value to if , like this:

let cond = (year == 2015); // equality evaluates to true or false if (cond)

The “else” clause

The if statement may contain an optional else block. It executes when the condition is falsy.

let year = prompt('In which year was the ECMAScript-2015 specification published?', ''); if (year == 2015) < alert( 'You guessed it right!' ); >else < alert( 'How can you be so wrong?' ); // any value except 2015 >

Several conditions: “else if”

Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.

let year = prompt('In which year was the ECMAScript-2015 specification published?', ''); if (year < 2015) < alert( 'Too early. ' ); >else if (year > 2015) < alert( 'Too late' ); >else

In the code above, JavaScript first checks year < 2015 . If that is falsy, it goes to the next condition year >2015 . If that is also falsy, it shows the last alert .

There can be more else if blocks. The final else is optional.

Conditional operator ‘?’

Sometimes, we need to assign a variable depending on a condition.

let accessAllowed; let age = prompt('How old are you?', ''); if (age > 18) < accessAllowed = true; >else < accessAllowed = false; >alert(accessAllowed);

The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.

The operator is represented by a question mark ? . Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

let result = condition ? value1 : value2;

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2 .

let accessAllowed = (age > 18) ? true : false;

Technically, we can omit the parentheses around age > 18 . The question mark operator has a low precedence, so it executes after the comparison > .

This example will do the same thing as the previous one:

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

But parentheses make the code more readable, so we recommend using them.

In the example above, you can avoid using the question mark operator because the comparison itself returns true/false :

// the same let accessAllowed = age > 18;

Multiple ‘?’

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

let age = prompt('age?', 18); let message = (age < 3) ? 'Hi, baby!' : (age < 18) ? 'Hello!' : (age < 100) ? 'Greetings!' : 'What an unusual age!'; alert( message );

It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an ordinary sequence of tests:

Here’s how this looks using if..else :

if (age < 3) < message = 'Hi, baby!'; >else if (age < 18) < message = 'Hello!'; >else if (age < 100) < message = 'Greetings!'; >else

Non-traditional use of ‘?’

Sometimes the question mark ? is used as a replacement for if :

let company = prompt('Which company created JavaScript?', ''); (company == 'Netscape') ? alert('Right!') : alert('Wrong.');

Depending on the condition company == 'Netscape' , either the first or the second expression after the ? gets executed and shows an alert.

We don’t assign a result to a variable here. Instead, we execute different code depending on the condition.

It’s not recommended to use the question mark operator in this way.

The notation is shorter than the equivalent if statement, which appeals to some programmers. But it is less readable.

Here is the same code using if for comparison:

let company = prompt('Which company created JavaScript?', ''); if (company == 'Netscape') < alert('Right!'); >else

Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.

The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that. Use if when you need to execute different branches of code.

Tasks

if (a string with zero)

Yes, it will.

Any string except an empty one (and "0" is not empty) becomes true in the logical context.

The name of JavaScript

Using the if..else construct, write the code which asks: ‘What is the “official” name of JavaScript?’

If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “You don’t know? ECMAScript!”

Источник

JavaScript if, else, and else if

Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The switch statement is described in the next chapter.

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

Example

Make a "Good day" greeting if the hour is less than 18:00:

The result of greeting will be:

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

if (condition) // block of code to be executed if the condition is true
> else <
// block of code to be executed if the condition is false
>

Example

If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":

The result of greeting will be:

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) // block of code to be executed if condition1 is true
> else if (condition2) // block of code to be executed if the condition1 is false and condition2 is true
> else // block of code to be executed if the condition1 is false and condition2 is false
>

Example

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":

if (time < 10) <
greeting = "Good morning";
> else if (time < 20) <
greeting = "Good day";
> else <
greeting = "Good evening";
>

The result of greeting will be:

More Examples

Random link
This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.

Источник

if. else

The if. else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

Try it

Syntax

if (condition) statement1 // With an else clause if (condition) statement1 else statement2 

An expression that is considered to be either truthy or falsy.

Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ( < /* . */ >) to group those statements. To execute no statements, use an empty statement.

Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements.

Description

Multiple if. else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.

if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … else statementN 

To see how this works, this is how it would look if the nesting were properly indented:

if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … 

To execute multiple statements within a clause, use a block statement ( < /* . */ >) to group those statements.

if (condition)  statements1 > else  statements2 > 

Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:

function checkValue(a, b)  if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); > 

This code looks innocent — however, executing checkValue(1, 3) will log "a is not 1". This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like:

function checkValue(a, b)  if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); > 

In general, it is a good practice to always use block statements, especially in code involving nested if statements.

function checkValue(a, b)  if (a === 1)  if (b === 2)  console.log("a is 1 and b is 2"); > > else  console.log("a is not 1"); > > 

Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false , undefined , null , 0 , -0 , NaN , or the empty string ( "" ), and any object, including a Boolean object whose value is false , is considered truthy when used as the condition. For example:

const b = new Boolean(false); if (b)  console.log("b is truthy"); // "b is truthy" > 

Examples

Using if. else

if (cipherChar === fromChar)  result += toChar; x++; > else  result += clearChar; > 

Using else if

Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if :

if (x > 50)  /* do something */ > else if (x > 5)  /* do something */ > else  /* do something */ > 

Using an assignment as a condition

You should almost never have an if. else with an assignment like x = y as a condition:

However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with an example showing a general best-practice syntax you should know about and follow.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 5, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью