Quick Memory Joggers
Brief
Here are a few simple JS memory points — just remember them and you're fine.
Quick notes
The difference between var and let
- The scope differs. var is function-scoped, let is block-scoped. For example, define a var variable inside a for loop and, as long as it lives under the same function as that for loop, you can reach the var-defined variable from outside the for; define a let variable inside a for loop and it cannot be reached from outside.
- let has to be declared before it is used; var can be used before it is declared, but until the declaration happens its value is undefined.
- let cannot be redefined, i.e. you can't use that keyword to define the same variable name twice; var can be redefined.
How to turn on strict mode
// turn on strict mode for the whole JS file
'use strict'
function foo() {
// turn on strict mode inside the function
'use strict'
}Immediately-invoked function
(function () {
...
})();The eval() function
This function compiles and runs the JS statements passed to it; if the argument is an expression, eval() runs the expression. If the argument is a Javascript statement, eval() runs the Javascript statement. You can think of it as a kind of execution function.
The downsides of eval
- Can't be optimised, performance problems
- Security problems
- Lowers the code compression rate
The difference between Object and Map
- How they're created differs.
let obj = {...}can be created as a literal|constructor /let ergoMap = new Map()can only be created with the constructor - An Object's keys can only store strings or Symbols; a Map's keys can be objects, arrays and other types
- Object key-value pairs are stored unordered; Map key-value pairs are stored in order
Primitive data types
The first six are: undefined, null, Boolean, String, Number, Object.
Plus Symbol, newly added in ES6.
Primitive data types are not created with the new keyword
As the title says.
Keys in an object
Even if an object's keys aren't wrapped in single or double quotes, they are still read as strings. So if you need to pass in a variable, you have to wrap it in square brackets.
let user1 = 'Zhang San'
let user2 = 'Li Si'
let grade = {
user1: 100,
[user2]: 200
}
console.log(grade) // {user1: 100, Li Si: 200}Bitwise operators can replace multiplying and dividing by powers of two
As the title says. Example below:
let num1 = 7
let multipliedBy2 = num1 * 2; // the old way, the answer is 14
let efficientmultipliedBy2 = num1 << 1; // the new way, the answer is 14
let divide2 = num1 / 2;
divide2 = Math.floor(divide2) // the old way, the answer is 3
let efficientDivide2 = num1 >> 1; // the new way (divides by two and rounds down), the answer is 3Important
This article was translated by Hermes Agent; the original text can be found at here. The translation is for reference only. Translation time: 2026-11-05
