Confused by the abbreviated syntax: x> 0? eleven;

What does the following Javascript syntax mean? Describe the whole syntax:

var x = 0; x > 0 ? 1 : -1; // confused about this line alert(x); 
+4
source share
4 answers

This in itself does not mean anything. You will warn about the value of x , which is 0, and that it is. The second statement is meaningless if you do not assign it. If you did this:

 var x=0; var y = x > 0 ? 1 : -1; alert(y); 

You would get -1.

The conditional statement is an abbreviation for IF statements, it basically says:

Statement if x > 0 . If so, assign 1. If not, assign -1. A.

Or in a more general form:

 CONDITION ? VALUE_IF_TRUE : VALUE_IF_FALSE; 

Where:

  • CONDITION - can be anything that evaluates to logical (even after juggling).
  • VALUE_IF_TRUE - the value that should be returned if CONDITION was indicated on TRUE .
  • VALUE_IF_FALSE - the value that should be returned if CONDITION was specified on FALSE .
+19
source

This is a conditional statement . This is a ternary operator because it has three operands. It is often called the ternary operator, but this terminology is quite free, since any operator with three operands is a triple operator. It so happens that this is the only commonly used ternary operator.

What does it mean? Expression

 a?b:c 

evaluates to b if a evaluates to true, otherwise the expression evaluates to c .

+2
source

is it a ternary operator (?)

Think of it as an IF expression.

statement before '?' is a condition of your if statement. Immediately, what follows before ":" will be executed / assigned if the statement is true. After the ':' is what will be executed / assigned if the statement is false.

However, your code will just warn 0 because you are not assigning anything from your ternary operator.

basically your code can also say.
x = 0; alert(x); // this would alert 0

you need to review this:
x = 0; var y = x > 0 ? 1 : -1; alert(y);

+1
source

It will be -1. This is called a ternary operator .

It basically expands to this (assuming you wanted to put x= at the beginning of the second line).

 if(x>0){ x = 1 } else { x = -1 } 
0
source

Source: https://habr.com/ru/post/1412183/


All Articles