# 2Controls: Booleans, Branch and Loops

## 2.1. Truth values and boolean operators

A control is a boolean context that is defined by the syntax of a conditional instruction:

• – branch: if(exp. in boolean context) {evaluated true} else {evaluated false};
• – loop: while (exp in boolean context) {repeat block of code}.

As is no surprise, there are two boolean values: `true` and `false`. What is more specific is that, in a boolean context, the values of type `string` or `number` are cast to a boolean, and values `undefined` and `null` are evaluated as `false`.

### 2.1.1. Boolean operators: “!” (not), “&&” (and), “ ||” (or)

Allowing to build logical expressions in classical boolean logics, we get:

````let p = true, q = false;`
` console.log( typeof p);      // -> boolean`
` console.log( p || q);              // -> disjonction -> true`
` console.log( !p || q);       // -> logical imply: p => q () -> false`
```

NOTE.– Evaluation from left to right, priority to inner parentheses, short-cut rules.

````let bool1 = true, bool2 = false;`
`let p = bool1 || bool2; // bool2 not evaluated: p already 'true'`
`let q = bool2 && bool1; // bool1 not evaluated; q already 'false'````

### 2.1.2. Relational operators: >, <, >=, <=

With numbers, the relation is the order relation in ℜ (real numbers); with strings, it is the Unicode order relation where figures [0-9] precede alphas.

````let x = 4; console.log(x>3); console.log(x>'3'); // 'true' 'true'`
`console.log('b' > 'a'); console.log('b' > '3'); // 'true' 'true'`
`// warning! figures are like characters, hence:`
`console.log( ...````

Get JavaScript and Open Data now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.