Javascript
/
Fundamentals
- 1 Fundamentals 11
-
Hello World
-
Code structure
-
Use strict
-
Variables
-
Data types
-
Type conversions
-
Maths
-
Comparitions
-
Conditional
-
Loops
-
Functions
- 2 Testing 2
-
Mocha
-
Nested describe
- 3 Objects 4
-
Basics
-
Reference
-
Methods
-
Constructor
- 4 Types 5
-
Primitives
-
Numbers
-
Strings
-
Arrays
-
Json
- 5 Classes 3
-
Constructor
-
Binding
-
Inheritance
/
Conditional
➟
➟
Last update: 17-01-2022
If
The if (...) statement evaluates the expression in its parantheses.
/**
* The if (…) statement evaluates the expression in its parentheses ...
* and converts the result to a boolean.
*
* If the result is true executes the block of code.
*
*/
let age = 20;
if (age > 18) {
console.log("Allowed");
}
Ternary
! With conditional operator we can assign a result in a simpler way.
/**
* The ternary operator has three operands.
* It's the only operator witch has more than two operands.
*/
let age = 20
let allowed = age > 18 ? 'Yes' : 'No';
console.log(allowed); // Yes
Or
In Javascript this operator has some powerful uses.
/**
* In classical programming, the logical OR is for manipulating ...
* booleans only.
*
* In Javascript the operator is a bit trickier and more powerful.
* If an operand is not boolean, it's converted to a boolean.
*
* If all operands have been evaluated false, returns the last operand.
*/
console.log(true || false); // true
console.log(false || false); // false
console.log(1 || 0); // 1, like (true || false)
console.log(null || false || '0'); // 0
let firstName = '';
let lastName = '';
let nickName = null;
console.log(firstName || lastName || nickName || 'Anonymous');
// Anonymous
/**
* AND
* Just as with OR, any value is allowed as an operand.
* The differents is that AND returns first falsy value
* (or the last if none found)
*
* The OR return the first truly one.
*/
console.log( 1 && 0); // 0
console.log( 0 && 'no matter what'); // 0
Nullish
This is a recent addition to the language.
/**
* The two question marks operator ?? ...
* returns the first argument if it's not null/undefined.
*/
let a;
let b = 2;
// classical
let c = (a !== null && a !== undefined) ? a : b; // 2
console.assert( c === b); // pass
// nullish coalescing
let d = a ?? b; // 2
console.assert( d === b); // pass
➥ Questions github Fundamentals