Javascript if inside if you

JavaScript if

Summary: in this tutorial, you will learn how to use the JavaScript if statement to execute a block when a condition is true .

Introduction to the JavaScript if statement

The if statement executes block if a condition is true . The following shows the syntax of the if statement:

if( condition ) statement;Code language: JavaScript (javascript)

The condition can be a value or an expression. Typically, the condition evaluates to a Boolean value, which is true or false .

If the condition evaluates to true , the if statement executes the statement . Otherwise, the if statement passes the control to the next statement after it.

The following flowchart illustrates how the if statement works:

If the condition evaluates to a non-Boolean value, JavaScript implicitly converts its result to a Boolean value by calling the Boolean() function.

If you have more than one statement to execute, you need to use wrap them in a block using a pair of curly braces as follows:

if (condition) < // statements to execute >Code language: JavaScript (javascript)

However, it’s a good practice to always use curly braces with the if statement. By doing this, you make your code easier to maintain and avoid possible mistakes.

JavaScript if statement examples

The following example uses the if statement to check if the age is equal to or greater than 18 :

let age = 18; if (age >= 18) < console.log('You can sign up'); >Code language: JavaScript (javascript)
You can sign upCode language: JavaScript (javascript)

First, declare and initialize the variable age to 18 :

let age = 18;Code language: JavaScript (javascript)

Second, check if the age is greater or equal to 18 using the if statement. Because the expression age >= 18 is true , the code inside the if statement executes that outputs a message to the console:

if (age >= 18) < console.log('You can sign up'); >Code language: JavaScript (javascript)

The following example also uses the if statement. However, the age is 16 which causes the condition to evaluate to false . Therefore, you won’t see any message in the output:

let age = 16; if (age >= 18) < console.log('You can sign up'); >Code language: JavaScript (javascript)

Nested if statement

It’s possible to use an if statement inside another if statement. For example:

let age = 16; let state = 'CA'; if (state == 'CA') < if (age >= 16) < console.log('You can drive.'); > >Code language: JavaScript (javascript)
You can drive.Code language: JavaScript (javascript)

First, declare and initialize the age and state variables:

let age = 16; let state = 'CA';Code language: JavaScript (javascript)

Second, check if the state is ‘CA’ using an if statement. If yes, check if the age is greater than 16 using a nested if statement and output a message to the console:

if (state == 'CA') < if (age == 16) < console.log('You can drive.'); > >Code language: JavaScript (javascript)

In practice, you should avoid using nested if statements as much as possible. For example, you can use the && operator to combine the conditions and use an if statements as follows:

let age = 16; let state = 'CA'; if (state == 'CA' && age == 16) < console.log('You can drive.'); >Code language: JavaScript (javascript)

Summary

  • Use the JavaScript if statement to execute a statement if a condition is true .
  • Avoid using nested if statement as much as possible.
Читайте также:  Php mail smtp linux

Источник

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.

Источник

JavaScript If-Else and If-Then – JS Conditional Statements

JavaScript If-Else and If-Then – JS Conditional Statements

There will be times where you will want to write commands that handle different decisions in your code.

For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives.

In this article, I will explain what an if. else statement is and provide code examples. We will also look at the conditional (ternary) operator which you can use as a shorthand for the if. else statement.

What is an if. else statement in JavaScript?

The if. else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

Truthy and falsy values are converted to true or false in if statements.

if (condition is true) < // code is executed >else < // code is executed >

Any value that is not defined as falsy would be considered truthy in JavaScript.

Here is a list of falsy values:

  • false
  • 0 (zero)
  • -0 (negative zero)
  • 0n (BigInt zero)
  • «» , » , « (empty string)
  • null
  • undefined
  • NaN (not a number)

Examples of if. else statements in JavaScript

In this example, the condition for the if statement is true so the message printed to the console would be «Nick is an adult.»

const age = 18; if (age >= 18) < console.log("Nick is an adult."); >else

Screen-Shot-2021-08-09-at-3.18.12-AM

But if I change the age variable to be less than 18, then the condition would be false and the code would execute the else block instead.

const age = 12; if (age >= 18) < console.log("Nick is an adult."); >else

Screen-Shot-2021-08-09-at-3.17.07-AM

Examples of multiple conditions (if. else if. else statements) in JavaScript

There will be times where you want to test multiple conditions. That is where the else if block comes in.

if (condition 1 is true) < // code is executed >else if (condition 2 is true) < // code is executed >else < // code is executed >

When the if statement is false , the computer will move onto the else if statement. If that is also false , then it will move onto the else block.

In this example, the else if block would be executed because Alice is between the ages of 18 and 21.

const age = 18; if (age < 18) < console.log("Alice is under 18 years old."); >else if (age >= 18 && age else

Screen-Shot-2021-08-09-at-3.33.33-AM

When to use switch statements over if. else statements?

There are times in JavaScript where you might consider using a switch statement instead of an if else statement.

switch statements can have a cleaner syntax over complicated if else statements.

Take a look at the example below – instead of using this long if else statement, you might choose to go with an easier to read switch statement.

const pet = "dog"; if (pet === "lizard") < console.log("I own a lizard"); >else if (pet === "dog") < console.log("I own a dog"); >else if (pet === "cat") < console.log("I own a cat"); >else if (pet === "snake") < console.log("I own a snake"); >else if (pet === "parrot") < console.log("I own a parrot"); >else
const pet = "dog"; switch (pet)

switch statements will not be appropriate to use in all situations. But if you feel like the if else statements are long and complicated, then a switch statement could be an alternative option.

The logical AND (&&) operator and if. else statements in JavaScript

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

In this example, since age is greater than 16 and the ownsCar variable is true , the if block will run. The message printed to the console will be «Jerry is old enough to drive and has his own car.»

const age = 17; const ownsCar = true; if (age >= 16 && ownsCar) < console.log("Jerry is old enough to drive and has his own car."); >else

Screen-Shot-2021-08-09-at-4.22.49-AM

If I change the age variable to be less than 16, then both conditions are no longer true and the else block would be executed instead.

const age = 13; const ownsCar = true; if (age >= 16 && ownsCar) < console.log("Jerry is old enough to drive and has his own car."); >else

Screen-Shot-2021-08-09-at-4.20.19-AM

The logical OR (||) operator and if. else statements in JavaScript

In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.

In this example, even though the isSale variable is set to false , the code inside the if block will still execute because the boyfriendIsPaying variable is set to true .

const boyfriendIsPaying = true; const isSale = false; if (boyfriendIsPaying || isSale) < console.log("Jesse will go shopping."); >else

Screen-Shot-2021-08-09-at-4.40.36-AM

If I were to change the value of the boyfriendIsPaying variable to false , then the else block would execute because both conditions are false .

const boyfriendIsPaying = false; const isSale = false; if (boyfriendIsPaying || isSale) < console.log("Jesse will go shopping."); >else

Screen-Shot-2021-08-09-at-4.42.12-AM

The logical NOT (!) operator and if. else statements in JavaScript

The logical NOT ( ! ) operator will take something that is true and make it false . It will also take something that is false and make it true .

We can modify the example from earlier to use the ! operator to make the boyfriendIsPaying variable false . Since both conditions are false , the else block would be executed.

const boyfriendIsPaying = true; const isSale = false; if (!boyfriendIsPaying || isSale) < console.log("Jesse will go shopping."); >else

Screen-Shot-2021-08-09-at-5.02.04-AM

Conditional (ternary) operator in JavaScript

If you have a short if else statement, then you might choose to go with the ternary operator. The word ternary means something composed of three parts.

This is the basic syntax for a ternary operator:

condition ? if condition is true : if condition is false 

The condition goes before the ? mark and if it is true , then the code between the ? mark and : would execute. If the condition is false , then the code after the : would execute.

In this example, since age is greater than 18, then the message to the console would be «Can vote».

const age = 32; const citizen = age >= 18 ? "Can vote" : "Cannot vote"; console.log(citizen); 

Screen-Shot-2021-08-09-at-5.25.14-AM

This is what the code would look like using an if else statement:

const age = 32; let citizen; if (age >= 18) < citizen = "Can vote"; >else < citizen = "Cannot vote"; >console.log(citizen);

Conclusion

if else statements will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

There will be times where you want to test multiple conditions and you can use an if. else if. else statement.

If you feel like the if else statement is long and complicated, then a switch statement could be an alternative option.

Using logical operators to test multiple conditions can replace nested if else statements.

The ternary operator can be used to write shorter code for a simple if else statement.

Источник

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