You get a bonus - 1 coin for daily activity. Now you have 1 coin

Conditional operators: if

Lecture




  1. if
  2. Conversion to boolean type
  3. Invalid condition, else
  4. Several conditions, else if
  5. Question mark operator '?'
  6. Multiple '?' Operators
  7. Unconventional use of '?'

Sometimes, depending on the condition, you need to perform various actions. To do this, use the if .

For example:

1 var year = prompt( 'В каком году появилась спецификация ECMA-262 5.1?' , '' );
2
3 if (year != 2011) alert( 'А вот и неправильно!' );

if

The if operator (if) gets a condition, in the example above this year != 2011 . It calculates it, and if the result is true , it executes the command.

If you need to execute more than one command, they are drawn up by a block of code in curly brackets:

1 if (year != 2011) {
2    alert( 'А вот..' );
3    alert( '..и неправильно!' );
4 }

It is recommended to use braces always, even when the command is one. This improves the readability of the code.

Conversion to boolean type

The if (...) operator evaluates and converts the expression in parentheses to a logical type.

In a logical context, the number 0 , the empty string "" , null and undefined , and also NaN are false , the other values ​​are true .

For example, this condition will never be fulfilled:

if (0) { // 0 преобразуется к false
   ...
}

... And this is always true:

if (1) { // 1 преобразуется к true
   ...
}

The calculation of the condition in the if (year != 2011) check if (year != 2011) can be made into a separate variable:

1 var cond = (year != 2011); // true/false
2
3 if (cond) {
4    ...
5 }

Importance: 5

Will alert appear?

if ( "0" ) {
   alert( 'Привет' );
}

Decision
[Open task in new window]

Invalid condition, else

The optional else block (“otherwise”) is executed if the condition is incorrect:

1 var year = prompt( 'Введите год ECMA-262 5.1' , '' );
2
3 if (year == 2011) {
4    alert( 'Да вы знаток!' );
5 } else {
6    alert( 'А вот и неправильно!' ); // любое значение, кроме 2011
7 }

Several conditions, else if

Sometimes you need to check several options conditions. To do this, use the else if ... block. For example:

1 var year = prompt( 'В каком году появилась спецификация ECMA-262 5.1?' , '' );
2
3 if (year < 2011) {
4    alert( 'Это слишком рано..' );
5 } else if (year > 2011) {
6    alert( 'Это поздновато..' );
7 } else {
8    alert( 'Да, точно в этом году!' );
9 }

In the example above, JavaScript first checks the first condition, if it is false, it goes to the second - and so on, until the last else .

Importance: 2

Write code that will ask: “What is the“ official ”name of JavaScript?”.

If the visitor enters "EcmaScript", then output "True!", If something else - output "Do not know? "EcmaScript"! ".

Flow Chart:

Conditional operators: if

Result in action: tutorial / intro / ifelse_task2.html

Decision

Solution: tutorial / intro / ifelse_task2.html.

[Open task in new window]

Importance: 2

Write the code that receives the value of the prompt , and then displays the alert :

  • 1 , if the value is greater than zero,
  • -1 if the value is less than zero,
  • 0 if the value is zero.

You can see in action: tutorial / intro / if_sign.html

Decision

tutorial / intro / if_sign.html

[Open task in new window]

Importance: 3

Write the code that will ask for the login ( prompt ).

If the visitor enters "Admin", then ask the password, if you clicked cancel (escape) - display "Login canceled", if it enters something else - "I do not know you."

Password check so. If the password “Black Lord” is entered, then output “Welcome!”, Otherwise - “Password is incorrect”, if canceled - “Login is canceled”.

Flow Chart:

Conditional operators: if

To solve use nested if blocks. Pay attention to the style and readability of the code.

Result in action: tutorial / intro / ifelse_task.html

Decision

Solution: tutorial / intro / ifelse_task.html.

Note the additional vertical indents inside the if . They are useful for better readability of the code.

[Open task in new window]

Question mark operator '?'

Sometimes you need to assign a variable depending on the condition. For example:

01 var access;
02 var age = prompt( 'Сколько вам лет?' , '' );
03
04 if (age > 14) {
05    access = true ;
06 } else {
07    access = false ;
08 }
09
10 alert(access);

Question mark operator '?' allows you to make it shorter and easier.

It consists of three parts:

условие ? значение1 : значение2

The condition is checked, then if it is true - the значение1 is returned, if it is incorrect, the значение2 , for example:

access = (age > 14) ? true : false ;

Operator '?' runs later than most others, in particular - later comparisons, so you can not put brackets:

access = age > 14 ? true : false ;

.. But when there are brackets, the code is better read. So it is recommended to write them.

In this case, one could do without the operator '?' because the comparison itself already returns true/false :

access = age > 14;

"Ternary Operator"

The question mark is the only operator that has as many as three arguments, while ordinary operators have one or two arguments.
Therefore, it is called the "ternary operator . "

Importance: 5

Rewrite if using the '?' Operator :

1 if (a + b < 4) {
2    result = 'Мало' ;
3 } else {
4    result = 'Много' ;
5 }

Decision

result = (a + b < 4) ? 'Мало' : 'Много' ;

[Open task in new window]

Multiple '?' Operators

Multiple if..else can be replaced by a sequence of '?' . For example:

1 var a = prompt( 'a?' , 1);
2
3 var res = (a == 1) ? 'значение1' :
4    (a == 2) ? 'значение2' :
5    (a > 2) ? 'значение3' :
6    'значение4' ;
7
8 alert(res);

At first it can be difficult to understand what is happening. However, after looking carefully, we notice that this is a normal if..else !

The question mark first checks a == 1 , if true - returns a значение1 , if not - goes to check a == 2 . If this is true, it returns the значение2 , otherwise the test is a > 2 and the значение3 . Finally, if nothing is true, then the значение4 .

Alternative with if..else :

01 var res;
02
03 if (a == 1) {
04    res = 'значение1' ;
05 } else if (a == 2) {
06    res = 'значение2' ;
07 } else if (a > 2) {
08    res = 'значение3' ;
09 } else {
10    res = 'значение4' ;
11 }

Importance: 5

Rewrite if..else using several '?' .

For readability - make out the code in several lines.

01 var message;
02
03 if (login == 'Вася' ) {
04    message = 'Привет' ;
05 } else if (login == 'Директор' ) {
06    message = 'Здравствуйте' ;
07 } else if (login == '' ) {
08    message = 'Нет логина' ;
09 } else {
10    message = '' ;
11 }

Decision

1 var message = (login == 'Вася' ) ? 'Привет' :
2    (login == 'Директор' ) ? 'Здравствуйте' :
3    (login == '' ) ? 'Нет логина' :
4    '' ;

[Open task in new window]

Unconventional use of '?'

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

1 var company = prompt( 'Какая компания создала JavaScript?' , '' );
2
3 (company == 'Netscape' ) ?
4     alert( 'Да, верно' ) : alert( 'Неправильно' );

It works like this: depending on the condition, either the first or the second part will be executed after the '?' .

The result of the execution is not assigned to a variable, so it disappears (however, alert does not return anything).

It is recommended not to use the question mark in this way.

Despite the fact that it looks shorter than if , it is much less readable.

Here, for comparison, the same with if :

1 var company = prompt( 'Какая компания создала JavaScript?' , '' );
2
3 if (company == 'Netscape' ) {
4    alert( 'Да, верно' );
5 } else {
6    alert( 'Неправильно' );
7 }

Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone