JS Tip from Github

Convert a Node list to an Array

const nodelist = document.querySelectorAll('div');  
const nodelistToArray = Array.apply(null,nodelist);  

The apply method is used to pass an array of arguments to a function with a given this value. MDN states that apply will take an array like object, which is exactly what querySelectorAll returns. Since we don't need to specify a value for this in the context of the function, we pass in null or 0. The result is an actual array of DOM elements which contains all of the available array methods.

Template Strings


var firstName = 'Jake';  
var lastName = 'Lee';  
console.log('My name is ' + firstName + '' + lastName);  


var firstName = 'Jake';  
var lastName = 'Lee';  
console.log(`My name is ${firstName} ${lastName});  

"use strict" and get lazy

// Whole-script strict mode syntax
"use strict";
var v = "Hi!  I'm a strict mode script!";  
//function-level strict mode syntax
function f()  
  // Function-level strict mode syntax
  'use strict';
  function nested() { return "And so am I!"; }
  return "Hi!  I'm a strict mode function!  " + nested();
function f2() { return "I'm not strict."; }  

Those followings are changes when strict mode enabled :

  • Variables can only be introduced when they are preceded with "var"
  • Attempting to write to readonly properties generates a noisy error
  • You have to call constructors with the "new" keyword
  • "this" is not implicitly bound to the global object
  • Very limited use of eval() allowed
  • Protects you from using reserved words or future reserved words as variable names

Differences between undefined and null

  • undefined means a variable has not been declared of has been declared but has been declared but not yet has 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's used by programmers to indicate that a var has no value.
  • undefined is invaild in JSON but null is vaild
  • undefined typeof undefined
  • null typeof object
  • Both are primitives
  • Both are falsy

    check if a variable is undefined typeof variable === "undefined" check if a variable is null

typeof variable === null  

the equality operator considers them equal,but identity doesn't

null == undefined //true

null === undefined // false