Existence and Booleans

Lack of existence converts to false: 
Boolean(undefined) = false
Boolean(null) = false
Boolean("") = false
Boolean(0) = false

Example:

var a; 

//Tries to converts a is into a boolean 
if (a) {
    console.log('Somethign is there')
}

Can be tricky when var a = 0 because Boolean (0) results to false so :

if (a || a === 0) {
    //So first it will run the strict equality because === has a higher precedence over ||
    //What happens is a === 0 becomes true and then:
    //a || true 
    //a will be coerced to 0 so false and we will have false || true 
    //fa

Default Value

function greet(name) {
    console.log('Hello' + name); 
}

greet('Tony');
greet(); - Wont throw an error, name becomes undefined 

Note: undefined || 'hello' returns "Hello", the || returns the value that can be coerced to true
Note: 0 || 1 returns 1 , "hi" || "hello" returns "hi" - 
The OR operator special behaviour is when you pass two value that can be coerced to true and false, 
it will returns the first one that returns to true 
So: undefined || "hello" returns "hello"
    null || "hello" returns "hello"
    "" || "hello" returns "hello"

function greet(name) {
    //OR Operator is run before assigned operator is called 
    name = name || 'Ian'
    console.log('Hello' + name); 
}

results matching ""

    No results matching ""