Javascript if with true

if, if…else, else if

if — это условный оператор позволяющий выполнять действия исходя из заданных условий. Инструкция if может дополняться блоком else if , который дает возможность задать дополнительное условие и прописать еще одну инструкцию. Если ни одно условие не истина, инструкцию можно описать в блоке else .

Синтаксис if

if — выражение условия, которое принимает значение true или false

Инструкция — выполняется если условие принимает значение true

Пример №1

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90)

Если введенное число scores больше 90 (условие принимает значение true ), выполнится инструкция — модальное окно с текстом Ваша оценка 5

Пример №2

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90) alert('Ваша оценка 5'); 

Когда инструкция описана в одну строку, запись может иметь такой вид

Пример №3

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90)

В том случае, если в инструкции более одной строки, код заключается в фигурные скобки.

Хорошей практикой считается использование блочного оператора <. >всегда — это улучшает читаемость кода.

Логическое преобразование в if (. )

  • 0, пустая строка, null, undefined и NaN — false
  • если 0 приведено к строке — true
  • все остальные значения — true

Пример №4

При таком условии инструкция не выполнится никогда.

Пример №5

Условие true — инструкция выполнится.

Блок else

else («иначе») — это необязательный блок, в котором можно описать еще одну инструкцию, которая выполнится когда условие в if принимает значение false .

Синтаксис if…else

Пример №6

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90) < alert('Ваша оценка 5'); alert('Поздравляем! Вы поступите на бюджет.'); >else

Использование блока else if

Инструкция if может содержать, как одно, так и более условий. Во втором случае используется блок else if .

В JavaScript нет ключевого слова elseif (в одно слово).

Пример №7

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90) < alert('Ваша оценка 5'); alert('Поздравляем! Вы поступите на бюджет.'); >else if (scores 60) < alert('Вы не получили 5'); alert('Вы можете претендовать только на платное обучение.'); >else

В данном случае, если scores больше 90 выполнится первая инструкция, если scores меньше или равно 90, а также более 60, тогда вторая. Если значение scores не попадает под эти два условия выполнится инструкция в else . В такой конструкции блок else также не является обязательным и может быть пропущен.

Пример №8

 let scores = prompt('Сколько баллов вы набрали на экзамене') if (scores > 90) < alert('Ваша оценка 5'); alert('Поздравляем! Вы поступите на бюджет.'); >else if (scores 60) < alert('Вы получили 4'); alert('Вы можете претендовать только на платное обучение.'); >else if (scores 30) < alert('Вы получили 3'); alert('Ваши шансы на поступление низки'); >else

Блок else if может быть добавлен 1, 2 и более раз.

Итого

if — это удобный и гибкий условный оператор, который позволяет исполнять код исходя из одного или более условий. Для добавления условия используется блок else if , который можно добавить неограниченное количество раз. Если ни одно условие не истина инструкцию можно описать в коде else . И else и else if не являются обязательными.

Skypro — научим с нуля

Источник

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.

Источник

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.

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!”

Источник

Читайте также:  Python конструкция if elif else
Оцените статью