Javascript - Types

| Comments

Differences between undefined and null

  • undefined means a variable has not been declared, or has been declared but has not yet been assigned a value
  • null is an assignment value that means “no value”
  • Javascript sets unassigned variables with a default value of undefined
  • Javascript never sets a value to null. It is used by programmers to indicate that a var has no value.
  • undefined is not valid in JSON while null is
  • undefined typeof is undefined
  • null typeof is an object. Why?
  • Both are primitives
  • Both are falsy (Boolean(undefined) // false, Boolean(null) // false)

You can know if a variable is undefined

1
typeof variable === "undefined"

You can check if a variable is null

1
variable === null

The equality operator considers them equal, but the identity doesn’t

1
2
3
4
// equality
null == undefined // true
// identity
null === undefined // false

Using Array Concat to Create Effective Methods

| Comments

Rather than writing separate methods to handle an array and a single element parameter, write effective functions with help of concat so they can handle both. This is similar to how some of jQuery’s functions work (css will modify everything matched by the selector).

You just have to concat everything into an array first. Array.concat will accept an array or a single element.

1
2
3
4
5
6
function printUpperCase(words) {
  var elements = [].concat(words);
  for (var i = 0; i < elements.length; i++) {
    console.log(elements[i].toUpperCase());
  }
}

printUpperCase is now ready to accept a single node or an array of nodes as its parameter.

1
2
3
4
5
6
printUpperCase("Piano");
// => PIANO
printUpperCase(["guitar", "drums", "keyboard"]);
// => GUITAR
//  DRUMS
//  KEYBOARD