Conditions in Javascript

2

I recently discovered that it is possible that you can save the result of a condition (such as a if ) to a variable:

var x = (1 > 2); // false
var y = (2 > 1); // true

See the JSFiddle: link

  • What is this feature called?
  • What is / is it useful for?
  • Is it also available in other languages?
asked by anonymous 04.07.2014 / 18:51

3 answers

7

Expressions

We usually call + , - % of mathematical operators , * , < , > of conditional operators , or

A set of values, permeated by operators, is what we call "expression", and an expression returns a value.


The "Conditional Expression"

The condition is nothing special, because as it says, == is just an operator. And and simply uses its result to define what it will do.

When you say:

if (x > y) { ...

You are first calculating the value of or . Let's suppose that by chance && actually is greater than || , the result of this "calculation" will be > , so it would have the same effect as if it were written if in that particular case.

Likewise, x > y is equivalent to:

var meu_teste = x > y; // teste recebe o valor true se x > y

if ( meu_teste ) { ... 

Only after "calculated" will the value of x that y will use the returned result. In fact, true "does not even know, does not care" about what happened inside the parentheses.


The "Boolean Expression" 1

Likewise, if (true) and if (x > y) could also be saved in var ";)

var condicoes = true or false; // true || false, etc.
if ( condicoes ) { ...
  

At a glance: you're just saving a value from an operation like any other. As x > y , operations if , if and or return a value at the end.

1. I am not sure what I want to do, but I do not know how to do it.     

04.07.2014 / 19:57
4

This is available in other languages too ...

The big difference is that in JavaScript you do not need to specify the type of your variable, ie you do not need to tell if it is a Boolean, String, Interger or something.

Your (1 > 2) operation returns a Boolean value ( false in this case) so you can assign this value to your x variable.

In Java for example you will need to say that your variable will receive a Boolean to perform this operation.

public static void main(String[] args) {
    Boolean x = (1 > 2);
    System.out.println(x);
}
    
04.07.2014 / 18:59
1

In php you have something similar too, but look.

$x = (3 > 1);
$y = (1 > 2);

var_dump($x); //boolean true
var_dump($y); //boolean false

echo $x; //1
echo $y; //(imprime nada)

But this is no special feature, when using a comparison operator, the result will always be a Boolean.

    
04.07.2014 / 19:02