Backwards & Forwards

JS is backward-compatible. Developers can write code which won’t stop running when browsers are updated.

Transpiler

Developers can write JS with new syntax then use a transpiler (Babel is a popular choice) to convert the source code to older JS version.

Example: let is coverted to var.

Polyfill

Developers can work with recently added API methods, then use polyfill to provide the missing methods for older browsers.

Number

Number type is double precision 64-bit, which consists of numbers between -(2^53-1) and +(2^53-1) inclusive (± 9,007,199,254,740,991). So any integer is implicitly a float.

Integers are treated as 32-bit int until they are used to perform an instruction that is valid on a Number but not on 32-bit int.

// check if a number is an integer
Number.isSafeInteger(12)          // true
Number.isSafeInteger(12.0)        // true
Number.isSafeInteger(12.1)        // false
Number.isSafeInteger(NaN)         // false
Number.isSafeInteger(Infinity)    // false
Number.isSafeInteger('12')        // false

Custom Object

function Person(first, last) {
  this.fist = fist
  this.last = last
}
 
// fullname shared by all Person instances
Person.prototype.fullname = function() {
  return this.first + this.last
}

Comparisons

=== is described as ‘checking both the value and the type’, which is correct most of the time.

// true
3 === 3.0
'abc' === 'abc'
null === null
true === true
 
// false
3 === '3'
'a' === 'A'
0 === null

2 special cases:

NaN === NaN     // false
0 === -0        // true

For NaN, use Number.isNaN(…). For -0, use Object.is(…).

As for non-primitives, === compares references.

const x = [1, 2, 3]
const y = x
 
x === y           // true
y === [1, 2, 3]   // false
x === [1, 2, 3]   // false

this

this value is dynamic and depends on the execution context.

const say = function() {
  console.log(`Hi ${this.word}`)
}

this points to global object window.

// Hi undefined
say()

this refers to the object that execute the function.

const test = {
  word: 'Testing',
  say: say,
}
 
// Hi Testing
test.say()

Can also use apply to bind this to an object.

const test2 = {
  word: 'Another test',
}
 
// Hi Another test
say.apply(test2)

In the context of prototypes, this will still resolve to the executed object.

Call vs Apply

A for array and C for comma.

const hi = (firstName, lastName) => console.log(`Hi ${firstName} ${lastName}`);
 
hi.apply(this, ['viet', 'le']);
hi.call(this, 'viet', 'le');

Prototypes

A mechanism by which JS objects inherit features from another.

Object.prototype is the most basic prototype which all objects have by default.

const person = {
  age: '111',
}
 
//[object Object]
person.toString()