Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 3)

Coercion

  • coercion - converting a value from one type to another
    • This happens quite often in JavaScript because it's dynamically typed.
    var a = 1 + 2;
    console.log(a); // 12
  • 1 is being coerced into '1' so the two strings can concatenate.

Comparison Operators

console.log(3 < 2 < 1);
console.log(false < 1); //coercion!! false to 0
console.log(0 < 1); //true
  • Avoid coercion by using strict equality ===.

Existence and Booleans

  • The Boolean of:
    • undefined is false
    • null is false
    • "" is false
var a; //initially set as undefined
            //goes to Internet and looks for a value
if (a) {
    console.log('something is there.');
}
  • a gets coerced, use a || a === 0 if a might be 0.
  • Since a is undefined (false), console.log will not happen.

Default Values

function greet(name) {
    console.log('Hello' + name);
}
greet();
  • JS doesn't care if there is no parameter, it uses undefined for name.
name = name || '<Your name here>'; //default value
  • || returns the value that can be coerced to true.
  • framework - a grouping of JS code that performs a task and is intended to be reusable

window.libraryName = window.libraryName || "Lib 2";

  • The above code checks to see if there is already a variable called libraryName; if not, it sets libraryName to "Lib 2".