Relearn Frontend - JavaScript

Some useful notes about JavaScript.

Type

  1. Undefined
  2. Null
  3. Boolean
  4. String
  5. Number
  6. Symbol
  7. Object

Why use void 0 not undefined?

In JavaScript, undefined is a variable, not a keyword, so we better use void 0 in order to avoid being changed unintentional.

In modern browsers , undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

Null means defefined but the value is null and it is a keyword in JavaScript, so we can use it derectly.

Why 0.1 + 0.2 != 0.3?

Accuracy problem of floating point arithmetic, there is a tiny difference.

We can use

1
console.log( Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON);

Symbol

Symbol is a new type in ES6, every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type’s only purpose.

Promise setTimeout async/await

Tasks/MicroTasks

Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. (setTimeout)

Microtasks are usually scheduled for things that should happen straight after the currently executing script, such as reacting to a batch of actions, or to make something async without taking the penalty of a whole new task. (Promise)

async/await

async before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.

await makes JavaScript wait until that promise settles and returns its result.

traffic light

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function sleep(duration){
return new Promise(function(resolve){
setTimeout(resolve, duration);
})
}
async function changeColor(duration,color){
document.getElementById("traffic-light").style.background = color;
await sleep(duration);

}
async function main(){
while(true){
await changeColor(3000,"green");
await changeColor(1000, "yellow");
await changeColor(2000, "red");
}
}
main()

Execution Context

ES3

  • scope
  • variable object
  • this value

ES5

  • lexical environment
  • variable environment
  • this value

ES2018

  • lexical environment
  • variable environment
  • code evaluation state
  • Function
  • ScriptOrMoudule
  • Realm
  • Generator

IIFE

Immediately Invoked Function Expression

console 20 div index

1
2
3
4
5
6
7
8
9
10
11

for(var i = 0; i < 20; i ++) {
void function(i){
var div = document.createElement("div");
div.innerHTML = i;
div.onclick = function(){
console.log(i);
}
document.body.appendChild(div);
}(i);
}