Web Learning - JavaScript

Last updated on April 15, 2026 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.

Preface

This article mainly references:

The SAST technical documentation has many prerequisites and is suitable for people with a programming background.

Variables and Variable Types in JavaScript

Variable Declaration

There are three keywords for declaring variables in JavaScript:

  • var
  • let
  • const

The first two can both declare variables, while const is used to declare constants.

It is recommended to use let for all variable declarations to avoid confusion.

In addition, JavaScript is a weakly typed language, so the type can change when a variable is reassigned.

引用The Magic of JavaScript JavaScript is a language that was designed in ab...

The Magic of JavaScript

JavaScript is a language that was designed in about two weeks. Even though the language's designer was highly skilled, it is undeniable that such a tight deadline resulted in many counterintuitive design flaws in JavaScript. The editor will explain these flaws in the corresponding sections of this document.

The behavior of JavaScript's basic types and basic operators is similar to C/C++ in most cases, but due to JavaScript's language features or flaws, these basic operators exhibit quite otherworldly and counterintuitive behavior in certain operations beyond common sense. You can consider this a design flaw of JavaScript, or a syntactic feature of the language.

Among these, usages that have been widely adopted as syntactic features will be pointed out in the main text, while other usages will be introduced in detail at the end of this section. If you are a beginner in JavaScript, the editor does not recommend reading this part, as it may lead to bad coding habits and confusion in programming thinking. For beginners, reading the main text of this document is enough to write practical and powerful code. But if you want to gain a deeper understanding of this language, the editor believes it is necessary to understand the specific behavior of these operators.

Variable Types

Seven primitive types are supported: number, bigint, string, boolean, symbol, undefined, and null.

To get the type: use the typeof keyword:

let num = 0;
typeof num; // "number"

Boolean

Booleans are no different from C++.

JavaScript has two sets of equality operators:

  • ===
  • !==

and

  • ==
  • !=

It is recommended to use === and !== exclusively, because == may perform forced type conversion during comparison, leading to seemingly strange behavior, while === performs strict value comparison without type conversion.

1 == true; // true
1 === true; // false

Number

JavaScript's numbers do not distinguish between integers and floating-point numbers; they are uniformly represented as floating-point numbers.

Only integer arithmetic between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER is safe; otherwise, an approximation using double-precision floating-point numbers will be used.

Division does not round down

5 / 2; // 2.5

Constants and functions for mathematical operations are called through the built-in object Math.

Two reserved words:

NaN

NaN: the result of an invalid operation, and any arithmetic operation involving NaN only yields NaN.

Regarding NaN, pay attention to how it is used with comparison operators: since any arithmetic operation involving NaN only yields NaN, you cannot use ===, and should use the isNaN() function instead. This function first forcibly converts the argument to a number type, and returns true only when the converted result is NaN.

isNaN(Nan); // true
isNaN(1); // false
isNaN("No"); // true,字符串不能被强转为数字

You should use the isNaN() function appropriately for branch checks to prevent bugs.

Infinity

If the result of an operation exceeds the range JavaScript can handle, you get Infinity; if it involves indeterminate forms such as zero times infinity, infinity minus infinity, etc., you get NaN.

1 / 0; // Infinity
-1 / 0; // -Infinity
1e100000; // Infinity
0 / 0; // NaN
Infinity * 0; // NaN
Infinity - Infinity; // NaN

String

Both '' and "" can represent strings.

Strings in JavaScript are primitive values, meaning string is immutable, similar to Python and Java.

Some commonly used string methods:

"a" + "b"; // "ab"
"hello".charAt(0); // 'h'
"hello, abc".replace("abc", "def"); // "hello, def"
"hello, abc".indexOf("abc"); // 7
"hello".substring(2, 3); // "l" 左闭右开

Template Strings

Instead of wrapping with '' or "", use `` as the wrapper, and use ${} inside to wrap code blocks.

let i = 1;
`The val of i + 1 is ${i + 1}.`; // "The val of i + 1 is 2."

Converting Between Strings and Other Types

JavaScript allows any variable to be added to a string. Commonly, the string is on the left side of the plus sign and other variables are on the right side; this operation converts the other variable to a string and then concatenates.

"4" + 3; // "43"

A trick: adding "" to a variable is a convenient way to convert that variable to a string.

"" + 3; // "3"
"" + true // "true"

To convert a string to a number: parseInt and parseFloat.

For parseInt(): the first argument is the string to be converted, and the second argument is the radix for the conversion. If not provided, it defaults to determining the format from the string itself: strings starting with 0x are treated as hexadecimal, and the rest as decimal. It is generally recommended to pass the second argument.

parseInt() returns NaN when conversion fails, but the logic of this function is to read characters one by one and convert them in real time; when it encounters a character that cannot be converted, it returns the result converted so far rather than NaN:

parseInt("hello", 10); // NaN
parseInt("123abc", 10); // 123

The bigint Type

As the name suggests, the bigint type is used to store and compute large numbers beyond the limits of the number type.

The symbol Type

let sym = Symbol('SAST');

It is a very unique kind of value. A symbol value can only be constructed via Symbol(); the argument passed in is meaningless except for debugging, and the function returns a different symbol value each time.

Therefore, the sole purpose of the symbol type: serving as a unique identifier.

It is worth noting that symbol values are hashable, which makes symbol one of only three types that can be used as object keys (the other two are number and string, though in practice number is treated as string).

Objects and Arrays

Objects

The object type is the most commonly used composite type in JavaScript, consisting of several key-value pairs. In each key-value pair, the value can be a variable of any type, and nesting of objects is also allowed.

Object literals are represented with curly braces; key-value pairs inside the braces are separated by commas, and the key and value of each key-value pair are separated by a colon:

let obj = {
    foo: 0,
    bar: "bar",
    foobar: {
        a: 1,
        b: "value",
    }, // 注意最后一个键值对也要有逗号
};

The key in each key-value pair is called a property of the object. Ways to access it:

  • obj.foo; // 0
  • obj['foo']; // 0

An object's property names can be any valid JavaScript string or symbol value, but if the property name is not a valid JavaScript identifier (for example, containing spaces or other special characters, or being a symbol), you can only use [] to access it:

const sym = Symbol();
const obj = {
    [sym]: 1,
    valid: 2,
    'invalid identifier': 3,
};

console.log(obj[sym]);
console.log(obj.valid);
console.log(obj['invalid identifier']);

Although JavaScript accepts numbers as property names, in essence numbers are converted to strings for use.

Declaring an object constant with const means that the variable name always points to that object, not that the object's properties are immutable. If you need to add properties that cannot be modified or deleted, use the Object.defineProperty method.

Arrays

The format of arrays in JavaScript:

  • Elements in the array are not required to have the same type (because it's a weakly typed language, after all)
let arr = [1, false, 'test', {foo: 1,}];
arr[1]; // false
arr.length; // 4,内置类型

Some commonly used built-in methods:

let arr = [1, 2, 3];
arr.indexOf(1); // 0
arr.indexOf(4); // -1
arr.slice(1, 2); // [2]
arr.join("."); // "1.2.3"
arr.push(4);
arr.pop();

When using built-in array methods, pay attention to whether the method affects the original array. The slice obtained by slice is a new array, while the pop method does affect the original array.

Other Built-in Objects

JavaScript has many other built-in objects; here are just a few examples:

Regular Expressions

let reg = /sast/;

Date

let date = new Date();
console.log(date.toLocaleString()); // 现在时间

Set

let docs = new Set();
docs.add('JavaScript');

Namespace Objects

Not all built-in objects are used to construct objects; some built-in objects only serve to store a category of methods or values, and are called namespace objects, such as Math and console.

Spread Syntax

Achieved by adding ... in front:

// 对象
let obj1 = {foo: 'bar', x: 1};
let obj2 = {foo: 'barrr', y: 2};
let clonedObj = {...obj1}; // 与obj1完全一致
let mergedObj = {...obj1, ...obj2}; // 包含两者的内容,相同的键后出现的会覆盖先出现的
let helfClonedObj = {...obj1, x: 2, y: 3}; // 也可以另外覆盖或添加部分内容
// 数组
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(...arr2); // 1 2 3 4 5

Destructuring Assignment

A bit like Python's tuple unpacking, except here we destructure arrays and objects:

let a, b, rest;
[a, b] = [1, 2];
[a, b] = [b, a];
[a, b, ...rest] = [1, 2, 3, 4, 5]; // => a = 1, b = 2, rest = [3, 4, 5]

// 最外层的括号是为了消去歧义,防止大括号被认为是代码块
({a, b} = {a: 1, b: 2}); // => a = 1, b = 2
({ a, b, ...rest } = { a: 10, b: 20, c: 30 }); // => a = 10, b = 20, rest = { c: 30 }

You can ignore some values, and you can also provide default values:

let a;
[, a] = [1, 2]; // a = 1
({a}) = {a:1, b:2}; // a = 1
[, a=2] = [1]; // a = 2
({a=1} = {b:2}); // a = 1

Renaming when destructuring objects:

let {b: a} = {b: 10}; // 声明变量 a = 10,没有声明变量 b

Object Literal Shorthand

Starting from ES 6, the following shorthand is supported:

let a = 1; let b = { a };  // 等价于 let b = { a: a }

My personal understanding is that the property is the variable name, and the value is the variable's value.

Null Types

  • undefined
  • null

The difference can be understood as "different degrees of emptiness". null is empty, but it exists, whereas undefined does not exist—it is not defined.

Situations where you encounter undefined:

  • Accessing a variable that has not been assigned
  • Array out-of-bounds access
  • Accessing a property that does not exist on an object
  • Getting the return value of a function with no return value

Since in many cases you don't want the program to crash with an error from accessing a non-existent property, you can use the ?. or ?.[] operators, whose effect is: when the property access fails, abort the access and return undefined.

For example:

response.data?.propList[3].name;

When you are unsure whether response has a data property, i.e., unsure whether response.data is undefined, use ?. instead of . in subsequent accesses.

A more extreme example:

undefined?.anyProp;

The statement returns undefined without throwing an error.

The ?.[] operator is used similarly:

arr?.[10]; // 可能arr没有10这么长

The ?. operator can also be used to handle properties related to null, and the return value is still undefined.

Control Statements in JavaScript

The usage of if, else, switch, case, while, do, for is almost exactly the same as in C/C++, so it won't be repeated here.

let i = 0;
if (i > 0) {
    console.log("i is greater than 0");
} else {
    console.log("i is not greater than 0");
}

let arr = [1, 2, 3, 4, 5];
for (let j = 0; j < arr.length; ++j) {
    console.log(`arr[${j}] = ${arr[j]}\n`);
}

In branching control statements, forced type conversion occurs during condition evaluation, following this logic:

  • undefined, null, 0, NaN, "", false convert to false
  • Everything else converts to true (whether objects or primitive types)

{} forcibly converts to true, because it is an object.

The for...in Loop

The for...in statement iterates over all enumerable properties of an object (properties are essentially keys), except for symbol, in arbitrary order. (Regarding enumerability, more on that later.)

For example:

const obj = {
    a: 1,
    b: 2,
};
for (const key in obj) {
    console.log(`${key}: ${obj[key]}`);
}

The for...of Loop

The for...of loop creates an iteration loop over iterable objects (such as Array, Map, Set, String), for example:

let frontend_courses = ['Java/Android', 'JavaScript/TS/React'];
for (const course of frontend_courses) {
    console.log(course);
}

Exception Handling

Similar to C++ (although I don't really understand C++'s exception handling either):

try {
    someDangerousFunction();
} catch (err) {
    console.log('error occurred');
}

Semicolons

The semicolon at the end of a JavaScript statement is optional, but we always add it.

Functions in JavaScript

Function Declaration and Invocation

Similar to Python, we can consider JavaScript functions as a kind of variable, because in JavaScript, functions behave largely like variables.

Syntax for declaring a function in JavaScript:

function sum(x, y) {
	return x + y;
}

Or like this; the essence of this approach is treating the function as a kind of variable:

const sum = function(x, y) {
    return x + y;
}

Here sum, as a variable, is an object, and this object's constructor is Function.

JavaScript does not check whether a function call matches the parameter list, which is reflected in:

  • It does not check variable types (obviously)
  • It does not check the number of arguments passed in

For example, the sum function defined above works normally whether you pass 1 or 3 arguments:

sum(1); // NaN
sum(1, 2, 3); // 3

Handling logic:

  • Parameters that are declared but not passed in are undefined
  • Extra arguments need to be captured manually

Ways to capture them:

  1. Add a variadic parameter ...rest to the parameter list; it will be assigned an array, and when there are no extra arguments, it is an empty array rather than undefined

    function sum(x, y, ...rest) {
        let s = 0;
        for (let i = 0; i < rest.length; ++i) s += rest[i];
        return x + y + s;
    }
  2. Use the arguments variable inside the function; this variable stores all of the function's arguments wrapped into an array, and in theory you don't need to declare a parameter list

    function sum() {
        let s = 0;
        for (let i = 0; i < arguments.length; ++i) {
            s += arguments[i];
        }
        return s;
    }

The Vanishing Return Value

JavaScript does not require statements to end with a semicolon, and its engine automatically adds a semicolon after every statement that does not end with one, but this can lead to unexpected results.

For example, in C++ it is common to write the return value on a new line:

function foo() {
    return
    	({name: "foo",});
}

But this actually returns undefined, because the code above effectively adds a ; after return.

The correct way to write it is:

function foo() {
    return {
        name: "foo",
    };
}

Variable Hoisting and Function Hoisting

Variable hoisting is one of JavaScript's language flaws, related to JavaScript's variable scoping issues.

We know that C++ uses {...} to mark a variable's scope (called block scope). But the earliest JavaScript did not have block scope, only function scope; that is, control statement blocks like for, if, etc., do not form scopes—what truly limits a variable's scope is the function:

// i is *not* visible here 
// j is *not* visible here 
function test() {
    // i *is* visible here 
    // j *is* visible here

    var i;
    for (var j = 0; j < 10; ++j) {
        // i *is* visible here 
        // j *is* visible here
    }

    // i *is* visible here 
    // j *is* visible here
}
// i is *not* visible here 
// j is *not* visible here 

The essence of this is that JavaScript hoists every variable's declaration to the very top of its containing function, and the original declaration statement becomes an assignment statement left in place; variables declared outside all functions have global scope.

For example:

代码JAVASCRIPT · 22 行
var name = "Mike";
function foo() {
    console.log(`Hello, ${name}!`);
    if (true) {
        var name = "Helen";
    }
}
// 输出是 "Hello, undefined!"
foo();
/*
实际上的运行方式:
var name;
name = "Mike";
function foo() {
	var name;
	if (true) {
        name = "Helen";
    }
}
foo();
这样就不难理解上面那段代码的结果了。
*/

Functions are also hoisted, but the difference from variable hoisting is that variable hoisting splits the declaration and the assignment apart, whereas functions are hoisted together with their function body.

greet(); // "Hello!"
function greet() {
    console.log("Hello!");
}
// 解析之后,在这个例子里面就是函数的声明和调用调换位置

If you declare a function in a way similar to declaring a variable, its function body will not be hoisted along with it; instead, it behaves like variable hoisting.

If variable hoisting and function hoisting happen at the same time, the following rules apply (below we distinguish between function declarations and functions declared in variable form):

  1. When variables and functions are hoisted together, variable declarations come first, and function declarations follow as a whole:

    console.log(a); // 输出 [Function: a]
    function a() {}
    var a = 10;
    console.log(a); // 输出 10
    
    /** * 逻辑拆解(提升后的等价顺序):
     * 1. var a; (变量声明最优先)
     * 2. function a() {} (函数声明紧跟其后,覆盖了前面的同名变量声明)
     * 3. console.log(a); (此时 a 是函数)
     * 4. a = 10; (赋值操作留在原地,此时 a 变成数字)
     * 5. console.log(a); (此时 a 是 10)
     */
  2. When the same-named identifier appears in multiple variable declarations, the declaration is recorded only once, and all assignment statements are retained:

    var a = 1;
    var a = 2;
    console.log(a); // 2
    
    /** * 逻辑拆解:
     * 1. var a; // 只保留一次
     * 2. a = 1; 
     * 3. a = 2; 
     */
  3. When the same-named identifier appears in multiple function declarations: the later one overrides the earlier one.

    foo(); // 输出 "second"
    function foo() {
        console.log("first");
    }
    function foo() {
        console.log("second");
    }

The Implicit Global Variable Problem

If you write a variable assignment statement without any keyword, and the variable to be assigned is undefined, that variable will be declared as a global variable:

function f() {
    foo = 1;
}
f();
console.log(foo); // 1

Reason: if the JavaScript engine cannot find the variable's declaration inside the function, it continues searching in the outer scope; if it cannot find it even in the global scope, it implicitly creates the variable in the global scope.

Writing the string "use strict" at the beginning of the code disables the implicit global variable problem.

Why Not Use var

The old standard actually only had var, but because the variable hoisting rules are very counterintuitive and the scope granularity is too coarse, making it inconvenient to use, the new standard introduced the let, const keywords. Variables declared with these two keywords follow block scope and are not hoisted.

console.log(a); // Uncaught ReferenceError: a is not defined
let a = 1;

console.log(b); // undefined
var b = 1;

Arrow Functions

A more concise notation for function expressions:

const sum = (x, y) => x + y;
const sum = (x, y) => {
    return x + y;
}
function sum(x, y) {
    return x + y;
}

const plusOne = x => x + 1;

That is:

  • When there is only a single return statement, the outer braces and return can be omitted
  • When there is only a single parameter, the () can be omitted

Since JavaScript has a large number of anonymous functions, this notation saves you from writing the function keyword many times.

However, when returning an object literal, the {} used as a block scope and the {} used as an object identifier may conflict, so you need to wrap it in () to disambiguate.

const fun = (value) => ({key: value});

The Callback Pattern

The callback pattern can be considered one of the great "souls" of JavaScript; many of this language's features are based on this design pattern.

The callback pattern: passing a function as an argument into another function.

Actually, the CS61A course explains this quite thoroughly (Higher-Order Functions).

function calculate(x, y, op) {
    return op(x, y);
}

calculate(1, 2, function (x, y) { return x + y; }); // 3
calculate(1, 2, function (x, y) { return x - y; }); // -1
calculate(1, 2, function (x, y) { return x; }); // 1

Almost all array operations in JavaScript use callback functions:

  • The array's map method: takes a callback function, passes each item of the array into this callback function as an argument, and returns a new array:

    const newArr = [1, 2, 3, 4].map(function(val) {
        return val * 2;
    }); // [2, 4, 6, 8]

Such callback chains are very convenient when processing arrays:

response.data
    .map(function (val, ind) {
        return {
            ...val,
            index: ind,
        };
    })
    .filter(function (val) {
        return val.name !== undefined;
    })
    .sort(function (a, b) {
        return a.subscriberNum - b.subscriberNum;
    });

Here we used the ... operator. Explaining its operational details would be redundant, so here we explain its common usage in practical engineering:

let obj = { a: 1, b: 2, c: 3 };
let another = { ...obj, c: 2, d: 4 }; // { a: 1, b: 2, c: 2, d: 4 } 

Here ...obj means spreading the obj object into key-value pairs; that is, the another object here gets the three key-value pairs a: 1, b: 2, c: 3. If subsequent key-value pairs overlap with those in obj (for example, another here redefines the c property), the later one overrides the earlier one. So the newly defined c: 2 here overrides the c: 3 in obj.

An important use of this syntax is: if I need to construct a new object another based on an existing object obj, where the new object differs from the existing object in only one key-value pair, I can use this syntax:

const getNewObjectWithOnePropChanged = (obj, value) => {
    return {
        ...obj;
        keyToBeChanged: value,
    };
};

Deferred Execution

Every JavaScript runtime includes the following two functions:

setTimeout(() => {
  // do something
}, 1000);

setInterval(() => {
  // do something
}, 1000);

The first argument passed to both functions is the task to execute, and the second is the waiting time (in milliseconds). The difference is that setTimeout's callback executes only once, while setInterval's callback repeatedly executes at the given interval.

Note that due to JavaScript's event loop model, the delay times above are not precise; for example, when other complex tasks are blocking execution, tasks are added to the queue at the specified time, but their execution will be delayed.

Closures

Using a function to return another function:

function getIncreaser(increment) {
    return function (x) {
        return x + increment;
    }
}
getIncreaser(5)(10); // 15

getIncreaser wraps the increment variable inside the anonymous function it returns, forming a closure.

A closure is: a function bundled together with references to its surrounding state (lexical environment).

The so-called lexical environment: the function scope at the time the closure is created.

Closures can cause certain problems. Let's look at a somewhat hard-to-understand problem:

Actually, thinking back, CS61A covered similar material 😭, but I didn't study it too seriously at the time; I plan to write a blog post later specifically reviewing this topic.

function getCounters() {
    var arr = [];
    for (var i = 0; i < 3; ++i) {
        arr.push(function () { console.log(i * i); });
    }
    return arr;
}

var counters = getCounters();
counters[0](); // 9
counters[1](); // 9
counters[2](); // 9

The expected result should be 0, 1, 4. Why?

Let me try to explain briefly: what a closure records is a reference to a scope object. When a closure captures variables, it copies variables of local scope and references variables of function scope. And variables declared with var all have function scope.

You can understand it this way: I used var counters to record this function's closure. All the temporary variables inside would normally be destroyed after the function ends, but this closure (environment) still holds pointers to these temporary variables, so within this function frame, the frames of the three created subfunctions all have their parent frames pointing to the frame of getCounters(), and the parent frame contains the variable i.

Therefore, when the three subfunctions are called outside the parent frame, they find this i, and since i is already 3 after the function call finishes, the result is all 9s.

The following Python code produces the same (well, similar) result:

def get_counters():
    arr = []
    for i in range(3):
        # 定义一个匿名函数(lambda)
        arr.append(lambda: print(i * i))
    return arr

counters = get_counters()
counters[0]()  # 输出 4
counters[1]()  # 输出 4
counters[2]()  # 输出 4

I feel this is still not explained clearly enough; I'll see if I can explain it better later.

The best solution to this problem is to use let, which changes it to block scope rather than function scope:

function getCounters() {
    let arr = [];
    for (let i = 0; i < 3; ++i) {
        arr.push(function () { console.log(i * i); });
    }
    return arr;
}

One more thing to note here: the essence is the change of scope, not that let brings some other special effect. If we write it like this:

function getCounters() {
    let arr = [];
    let i = 0;  // 注意在这里声明的 i 是函数作用域
    for (i = 0; i < 3; ++i) {
        arr.push(function () { console.log(i * i); });
    }
    return arr;
}

let counters = getCounters();
counters[0](); // 9
counters[1](); // 9
counters[2](); // 9

The result is still wrong.

The essence remains: when a closure captures variables, it copies primitive variables of local scope and references variables of function scope.

I feel the sentence above is the clearest explanation.

Pass by Value / Pass by Reference

JavaScript never copies objects for you under any circumstances. If a closure captures an object's value, regardless of scope, a problem similar to the one above will occur.

Manual deep copy:

let sharedData = {score: 0};
for (let i = 0; i < 3; i++) {
    let tmp = {...sharedData, score: i};
    arr.push(tmp);
}

Object-Oriented Programming in JavaScript

JavaScript's OOP is not implemented with class encapsulation logic, but with prototype chain logic. The earliest JavaScript did not support class syntax, but because the prototype chain was too dramatically hilarious, later JavaScript standards added class syntax to the language standard as syntactic sugar; however, the underlying implementation of JavaScript's OOP is still based on the prototype chain. For beginners, it is recommended to use only class syntax, and not to spend time digging into the prototype chain unless you encounter an unsolvable bug.

JavaScript using class syntax is largely similar to Java. Here is an example:

代码JAVASCRIPT · 18 行
// 复数类
class Complex {
    real = 0;
    imaginary = 0; // 默认值
    constructor(_real, _imaginary) {
        this.real = _real;
        this.imaginary = _imaginary;
    }
    print() {
        console.log(`${this.real} ${this.imaginary >= 0 ? "+" : "-"} ${Math.abs(this.imaginary)} i`);
    }
    static printInfo() {
        console.log("This is a complex class.");
    }
}
let com = new Complex(1, 2);
com.print(); // "1 + 2 i"
Complex.printInfo(); // "This is a complex class."
  • When using class members inside class methods, you must use this to call them
  • When using class syntax, the constructor's constructor is a keyword and must be used
  • Inheritance uses the extends keyword
  • All class methods and class members are public; JavaScript has no access modifiers

The this Pointing Problem

The this pointing problem is arguably the most far-reaching flaw in JavaScript's language design—so far-reaching that even though it takes a long time to fully understand, you have no choice but to invest that effort, otherwise you may encounter many this-related problems in your future coding practice.

The rule for this pointing: this always points to the nearest caller.

For example:

function foo() {
    console.log(this);
}
foo(); // window
let obj = {foo: foo,};
obj.foo(); // {foo: f}
// 为什么写成obj.foo()?因为obj.foo相当于是调用名为foo的成员,而这个成员是一个函数,然后再使用()调用之

Both calls invoke the same foo function, but:

  • The former is a global call / direct call
  • The latter attaches foo as a property of the object obj and then calls it through obj

And: the pointing of this is determined at the time the function is called:

  • If foo is called globally, then this points to the global object
  • If it is called through obj, then this points to obj

What is the global object

JavaScript's global variables are all properties of the global object at runtime, and every JavaScript runtime environment has a global object. For example, the global object in the browser is window, and in Node.js it is global. Every declared global variable is bound as a property of the global object.

var a = 1;
windows.a; // 1
foo();
windows.foo(); // 没区别

Here is a more complex example:

let obj = {
    foo: 1,
    inner: {
        foo: 2,
        fn: function () {
            console.log(this.foo);
        },
    },
};

obj.inner.fn(); // 2

obj.fn = obj.inner.fn;
obj.fn(); // 1

let fn = obj.inner.fn;
fn(); // undefined

There are three calls, and the objects from top to bottom are obj.inner, obj, and window, so this points to these three objects respectively.

The flaw of this lies in its dynamic pointing. In practice, it is often hard to figure out who the caller of a function is—for example, event listener functions and class methods. These cannot be solved in this section either; you need to learn prototype chain logic.

There are some patches that allow developers to explicitly specify what this points to:

  • The call() and apply() methods: when calling a function, the first argument specifies which object this is, and the following arguments:

    • For call(), the arguments are passed in one by one, loosely
    • For apply(), the arguments are packed into an array and passed in
    function speak(greeting, punctuation) {
        console.log(`${greeting},我是 ${this.name}${punctuation}`);
    }
    var name = "小王";
    const student = {
        name: "小明"
    };
    
    speak.call(window, "你好", "!");
    // 输出:你好,我是 小王!
    
    const params = ["哈喽", "~~~"];
    speak.apply(student, params);
    // 输出:哈喽,我是 小明~~~
  • The bind() method: permanently binds this to a specific object, and this binding is maintained no matter how it is called afterwards.

Nowadays, arrow functions are also commonly used to solve this:

Arrow Functions

Arrow functions were mentioned earlier, but at that time it was only because the syntax was convenient. In fact, arrow functions were designed largely to solve the this problem.

  • For a function, when this is used inside it, it points to the context at the time the function is called;
  • An arrow function is actually a closure, so an arrow function preserves the this from the time it was defined, solving the problem of ambiguous this pointing.

For example:

const foo = () => console.log(this);

foo(); // window

// Changing caller will not change 'this'
let obj = { foo: foo, };
obj.foo(); // window

// 'call' & 'bind' may fail
foo.call(obj); // window
foo = foo.bind(obj);
foo(); // window

As you can see, for an arrow function defined in the global environment, this always points to the global object.

Here is another example (this one is a bit convoluted; understand it carefully):

let obj = {
    bar: function () {
        const foo = () => console.log(this);
        return foo;
    },
};

const foo = obj.bar();
foo(); // obj

const bar = obj.bar;
bar()(); // window
  • For const foo = obj.bar(), the bar() is called inside obj and returns the foo function, so the arrow function's this points to obj
  • For const bar = obj.bar, the const bar here is a global object, and calling bar() with the global object means the this of the resulting foo function points to the global object.

Asynchronous JavaScript

Why write asynchronous code?

  • So-called synchronous code: the code executes from top to bottom, and the code below only executes after the code above has finished;
  • But in frontend code:
    • We often request data from the backend / network, and this step is necessarily much slower than other code operations. If synchronous code is used, the page will freeze at this step
    • Some operations can be completed while the frontend requests the page, such as rendering the page template first, and then filling the data into the page after the data is fully retrieved
  • In short, the frontend needs to allow multiple pieces of code to execute simultaneously, i.e., asynchronous code (Asynchronous)

Event Loop and Message Queue Mechanism

This is how JavaScript implements asynchrony, because JavaScript is a single-threaded language and does not support multi-threaded concurrent asynchrony.

Why are multiple threads disabled?

JavaScript was originally designed as a browser scripting language whose purpose is to modify the DOM tree. If multiple threads were allowed, concurrent write conflicts could occur.

  • Callback functions: here it is mainly about re-understanding them. When the main thread dispatches an asynchronous process (such as triggering a network request), a callback function for this asynchronous process needs to be set, describing what needs to be done after the asynchronous process finishes.
    • Reason: the main thread has no way of knowing when this asynchronous process will end or whether it will succeed. Under such circumstances, the main thread cannot know at all when to do the follow-up work of this asynchronous process (for example, after fetching data from the network, the main thread should load that data onto the page). Therefore, a callback function is defined, and its invocation timing is determined by the execution status of the asynchronous process.

The main thread of JavaScript has an infinite loop, called the event loop:

  • When idle (the function stack is empty), it continuously checks whether there are messages in the message queue
  • If there are, it executes them; if not, it waits.

Code that needs to be executed asynchronously carries a callback function:

  • When the asynchronous process finishes, the callback function is placed at the end of the message queue;
  • When the main thread is idle and detects a callback function in the message queue, the main thread executes the callback function, completing the follow-up work of the asynchronous process.

Macro message queue and micro message queue

In fact, JavaScript has two kinds of message queues: the macro message queue and the micro message queue. Callbacks triggered by things like setTimeout, setInterval are placed in the macro message queue, while the then of a Promise is placed in the micro message queue.

When JavaScript's event loop checks the message queues, it first checks the micro message queue, and if there are callbacks, it executes every callback until the micro message queue is empty. Then it checks the macro message queue and executes only the first callback in the queue.

Here is an example of asynchronous code:

The setTimeout here is only used to simulate a time-consuming asynchronous process.

// 这个函数接收两个参数:回调函数,和多长时间之后执行回调函数
setTimeout(() => {
    console.log("1s has passed.")
}, 1000);

The waiting process of this function runs asynchronously to the main thread, and the callback function passed in as the first argument will be placed into the message queue after the waiting is finished.

We use this function to write a time-consuming operation to simulate a network request:

const fetchData = () => {
    setTimeout(() => {
        console.log("got data"); // 可以认为这个是“善后”
    }, 1000);
}
// 主线程:
fetchData(); // 派遣异步任务
// 这里可以做别的任务

It can be considered that: the task of this function is to dispatch an asynchronous process; it is not responsible for waiting for the asynchronous task to finish or for the follow-up work—the follow-up work is written in the callback function.

While waiting for the asynchronous process, the main thread can do other work.

The Flaws of Callback Functions

Why are there so many callback functions in JavaScript?

Often it is because: we need to perform some custom operations inside the called function.

Why do it this way? One common reason is:

  • Originally our approach could be: the called function provides a return value, and the caller uses that return value to handle things;
  • But in reality: this data may not be immediately available;
  • Therefore, in order not to block the entire program:
    • The caller can only encapsulate the subsequent operations as a closure and hand it to the called function;
    • Once the data is ready, the subsequent operations are completed by calling the closure.

For example, reading a file:

// readFile 是 Node.js 内置的读取文件的方法
import { readFile } from 'fs';

const handler = (err, data) => {
    // 下面的代码只是一个例子,告诉readFile这个异步过程完成之后该做什么
    console.log(data.toString());
}
readFile('~/someFile', handler);

The so-called "problem with callback functions":

  • Although it achieves "convenient use in asynchrony without introducing much other syntax"
  • The readability is poor
  • Excessive nesting makes the code hard to maintain—the so-called "callback hell".

The Promise Object

Introduced in newer versions of JavaScript to solve the unintuitiveness of callback functions, it completely changed the paradigm of writing asynchronous code in JavaScript.

Use the constructor to create a Promise object:

  • Its constructor accepts a callback function
    • The parameters of this callback function are two other callback functions
    • resolve represents the callback for asynchronous success, and reject represents the callback for asynchronous failure
    • Note: the parameter names of this asynchronous function are required to be resolve and reject
    • The entire function body of the callback function received by the constructor is the time-consuming operation to be executed
    • To specify concrete function bodies for resolve and reject, you need to use the then and catch methods. Both methods accept callback functions, and return a Promise object.
代码JAVASCRIPT · 18 行
new Promise((resolve, reject) => {
    let asyncSucceeded = Math.random() > 0.2;
    setTimeout(() => {
        if (asyncSucceeded) {
            resolve("Async succeeded!");
        } else {
            reject("Async failed!");
        }
    }, 1000);
})
    .then((res) => {
        console.log("Then");
        console.log(res);
    })
    .catch((err) => {
        console.log("Catch");
        console.log(err);
    });

In this way, we specify the concrete task of the asynchronous process in the function body of the callback function received by the Promise constructor, and assign the callback functions of the asynchronous process in the then and catch methods, so that the main thread fully completes the dispatch of the asynchronous process.

The paragraph above feels a bit convoluted; read it a few more times.

Why is Promise superior to directly writing the callback pattern? Consider a business scenario of fetching data from multiple data sources. Because:

  • The return value of the then method is still a Promise object, so we can chain then calls after then;
  • The return value of the previous then's callback function is passed into the first parameter of the next then's callback function;
  • Only after the previous Promise reaches the resolve state will the next Promise be triggered
  • The res received by each then is the result processed by the previous step
new Promise((resolve, reject) => {
    resolve("用户登录");
})
	.then((res) => {
   		return requestData("获取用户信息", res);
	})
	.then((res) => {
        return requestData("获取订单列表", res);
    })
	.then((res) => {
   		return "final"; 
	})
	.catch(console.log);

In addition, for the multiple-dependency problem (where the next asynchronous operation can only be dispatched after multiple asynchronous operations have all finished), Promise provides the all method:

Promise.all(
    [1, 2, 3].map((val) => {
        return new Promise((resolve, reject) => {
            resolve(`Promise #${val}`);
        });
    })
)
    .then((res) => {
        console.log(res); // ["Promise #1", "Promise #2", "Promise #3"]
    })
    .catch((err) => {});

Here, the callback function in then receives an array assembled from the parameters accepted by the resolve callbacks of all the Promise objects; the same applies to catch.

  • Once a Promise is created, the internal asynchronous process starts executing, and once started it cannot be canceled (atomic)
  • After creating a Promise, the asynchronous operation has only been dispatched; it does not mean the asynchronous execution has finished.

For example:

let i = 1;

new Promise((resolve, reject) => {
    resolve(2);
})
    .then((res) => {
        i = 2;
    })
    .catch(console.log);

console.log(i); // 1

Since the asynchronous process has not finished executing at this point, we can only get 1.

async and await

Two keywords introduced in the new standard, with the goal of making asynchronous code as natural as synchronous code.

When using Promise directly with chained calls, the code becomes ugly in order to preserve intermediate variables. Therefore, we more often use the async and await keywords.

The role of the async keyword:

  • Declares a function as an asynchronous function, which returns and dispatches an asynchronous operation when called
  • Wraps the function's return value as a Promise object, so that then chaining can be used

Example:

const foo = async() => {
    return "1";
};
foo()
	.then((res) => {
   		 console.log(res);
    	return "2";
	}).
	then(console.log)
	.catch(console.log);

The role of the await keyword: it is followed by a variable

  • If it is not a Promise object, nothing happens;
  • If it is a Promise object, the await keyword blocks code execution until the asynchronous operation represented by this Promise object finishes:
    • If the asynchronous operation succeeds, the return value of the await statement is the parameter accepted by the Promise's resolve callback;
    • If the asynchronous operation fails:
      • If this Promise has a reject callback specified via the catch method, the return value of the callback function in catch is returned;
      • Otherwise, an Uncaught Failure error is thrown.

For example:

let a = await 1;
a; // 1
let b = await new Promise((resolve, reject) => {
    let succeeded = Math.random() > 0.2;
    if (succeeded) resolve("success");
    else reject("failure");
})
	.catch((err) => {
        return "Error" + err;
    });
b; // "success" or "Error Failure"

Using the async and await keywords to simplify the previously mentioned fetching of data from multiple data sources:

const fetchData = async () => {
    let data_1 = await fetchData_1(initData);
    let data_2 = await fetchData_2(data_1);
    let data_3 = await fetchData_3(data_2);
    return [data_1, data_2, data_3];
}

It is now almost indistinguishable from synchronous code.

It also solves the problem of then chains of indeterminate length; combining with a for loop solves the problem.

async, await have also generated considerable controversy; the biggest danger is async infection.

One requirement for using the await keyword: if it is used inside a function, then that function must be asynchronous.

Reason:

  • await blocks code execution
  • If it blocks on the main thread, it will cause the page to lag, which contradicts the original purpose of asynchrony.

Consequently, further:

  • When a function uses await internally, that function must be defined as an async asynchronous function
  • To prevent the "variable sensitivity problem" (i.e., the Promise problem—after creating a Promise, the asynchronous operation has only been dispatched; it does not mean the asynchronous execution has finished), the caller has to add the await keyword as well to forcibly wait for the result
  • This logic keeps spreading upward, causing the entire code to become asynchronous—this is async infection.

In addition, the synchronous style of async/await masks the asynchronous nature, easily leading people to write inefficient code:

const fetchData = async () => {
    let data_1 = await fetchData_1();
    let data_2 = await fetchData_2();
}

If data_1, data_2 could have been fetched concurrently, this way of writing actually reduces efficiency, because the actual meaning of this code is to fetch data serially. In fact, async, await only makes code that fetches information sequentially concise; for information fetching that could already be concurrent, they may instead lead us to write unnecessary serial code. The correct way to write it should be:

const fetchData = async () => {
    let data_1_promise = fetchData_1();
    let data_2_promise = fetchData_2();
    let data_1 = await data_1_promise;
    let data_2 = await data_2_promise;
}

Only by first obtaining the two asynchronous Promise objects—dispatching both asynchronous operations first and then awaiting them separately—can concurrency be achieved.

But the purpose of async, await is precisely to hide the existence of Promise and write asynchronous code in a synchronous format; doing this is actually no better than writing out the Promise directly.

Furthermore, for the multiple-dependency problem, the async, await keywords do not provide a solution, because await can only wait for one asynchronous operation at a time. In this case, it is still inevitable to use Promise objects.

JavaScript in the Browser

  • The browser can be understood as a runtime environment

Browser Built-in Objects

The browser has a series of built-in global objects, related to information such as the window, screen, and browsing history.

For example, the window object: it is

  • One of the most commonly used built-in global variables
  • One major role is to act as the global scope, i.e., all global variables and functions are bound as its properties
  • It has properties such as innerHeight, innerWidth, outerHeight, and outerWidth

There are also:

  • The screen object: information about the screen
  • The navigator object: information about the browser
  • The location object: URL-related information
  • The document object: the root node of the entire DOM tree of the current page

Common Methods for DOM Tree Nodes

Finding DOM Nodes

Use the following built-in methods:

  • document.getElementById: finds by HTML node ID and returns the specific DOM node. In the console, it is displayed as an HTML tag, and hovering the mouse over the tag highlights the corresponding element on the page.

    dom.getElementById in Edge
    <h1 id="test-1">
      Hello World
    </h1>
  • getElementsByClassName: can be applied to any DOM node; it searches the subtree rooted at the node for all nodes whose class attribute equals the given value, and returns a list of DOM nodes. It can be used in combination with document.getElementById.

  • getElementsByTagName: similar to the above; the only difference is that it searches for all nodes whose tag name equals the given value, and the return value is still a list.

  • querySelector and querySelectorAll: the former returns the first DOM node in the subtree rooted at that DOM node that satisfies the selector requirements; the latter returns a list of all nodes in the subtree that satisfy the requirements

    const nodes = node.querySelectorAll("div > p.active");

Updating DOM Tree Nodes

DOM node objects have a very important property: innerHTML, which is a string—namely, the text between a pair of closing HTML tags.

For example, for such a DOM node

<p> The color is <span style="color:red"> RED </span> ! </p>

then node.innerHTML == ' The color is <span style="color:red"> RED </span> ! '

This property can be freely read and written; by directly modifying this property, the DOM node can be adjusted.

Another commonly used property: innerText. The only difference from innerHTML is that it performs character escaping, e.g., < becomes &lt;.

You can also modify a node's style by modifying its style property:

node.style.color = "red";
node.style.fontSize = "20px"; // "font-size" in CSS

CSS allows property names to contain hyphens -, but JavaScript does not, so when encountering such property names, rewrite them using camelCase.

Adjusting the DOM Tree Structure

appendChild, insertBefore, document.createElement, removeChild

These are all just APIs—ask an LLM when using them. This is just CRUD on the DOM tree.

jQuery

A third-party library, very popular.

$ is jQuery's global wrapper object.

The rest are CRUD APIs, which will not be elaborated here.

Events

Consider how users interact with web pages → how users trigger the JavaScript that describes the interaction behavior → introducing the concept of events.

  • User actions such as clicking, typing, and document tree loading can all be events
  • The information of an event is wrapped as an object and passed into JavaScript's event handling loop
  • After receiving an event, the JavaScript engine calls the corresponding callback function, and the interaction behavior is defined in these callback functions.

Here is an example using jQuery:

$("#test-button").on("click", () => {
    alert("Hello!");
});

Afterword

I've kind of become a human-shaped documentation copier; I'll add things to this as I read other documentation later.

TODO:

  • Advanced OOP in SAST (the principles of the prototype chain)
  • Reading through parts of MDN

Web Learning - JavaScript
https://blog.wendain.ing/en/posts/web-learn-js/
Author
wendaining
Posted on
April 13, 2026
Updated on
April 15, 2026
Licensed under