I complete reading JavaScript Enlightenment recently. The book is more about basics in JavaScript and suitable for beginners. Here are a list of my benefits and extensions from the book.javascript
JavaScript developers often capitalize the constructor name to distinguish the constructors from normal functions. Therefore, some developers may mistake Math as function since the name is capitalized while Math is really just an object.java
console.log(typeof Math); // object console.log(typeof Array); // function
There are two ways to construct a function:git
function sum(x, y) { return x + y; } console.log(sum(3,4)); //7
let multiply = new Function("x", "y", "return x * y;"); console.log(multiply(3,4)); //12
In development, we often need to use call or apply to switch the function context. E.g.github
function print(){ console.log(this.a); } print.call({a: 'hello'}); //hello
Some interview questions will ask why print doesn't define call as its property but print.call() won't throw error. It's because print is an instance from Function constructor so it inherits all the methods defined in Function.prototype through prototype chain.express
print.call === Function.prototype.call
typeof can be used to determine the types for primitive datatypes. But it won't be able to distinguish between arrays and objects.api
console.log(typeof [1,2]); //object console.log(typeof {}); //object
There are several wasy to do Array check:app
console.log(Array.isArray([1,2])); //true
console.log(Object.prototype.toString.call([1,2]) .toLowerCase() === '[object array]'); //true
Note here we have to use Object.prototype.toString with call to switch the calling context, as Array.prototype.toString is overriden.ide
console.log(Object.prototype.toString.call([1,2])); //[object Array] console.log([1,2].toString()); //1,2
[1,2] instanceof Array === true;
Object.prototype.toString won't work for custom datatypes. In this case we can use instanceof to determine the type.ui
class Person {} let mike = new Person(); console.log(Object.prototype.toString.call(mike)); // [object Object] console.log(mike instanceof Person); // true
There are two cases where a variable is undefined.this
let s; console.log(s); //undefined
let obj1 = {}; console.log(obj1.a); //undefined
let obj2 = {a: null}; console.log(obj2.a); //null
If we aim to filter out undefined and null, we can use weak comparison with double equality sign(i.e. ==).
console.log(null == undefined); //true let arr = [null, undefined, 1]; let fil = arr.filter(it => { return it != null; }); console.log(fil); //[1]