Javascript
Lộ trình phát triển toàn diện Javascript theo tiêu chuẩn quốc tế nilbuild/developer-roadmap
Hướng dẫn từng bước từ nền tảng đến chuyên sâu giúp bạn làm chủ Javascript. Tích hợp tài liệu lý thuyết, bài viết thực chiến, video tham khảo và bài tập lập trình trực tiếp trên IDE.
Nền Tảng & Khái Niệm Cốt Lõi
Giai đoạn 1 tập trung hoàn thiện 26 chủ đề then chốt.
===
The `===` operator compares two values for equality without type coercion. Both the value and the type must match for the comparison to return `true`. It is the recommended equality operator for most cases because it produces predictable results.
==
The `==` operator compares two values for equality after performing type coercion if the types differ. For example, `"5" == 5` returns `true` because the string is converted to a number before comparison. This can produce surprising results and is generally avoided in favor of `===`.
All about Variables
Variables are named containers for storing data values in a program. In JavaScript, variables are declared using `var`, `let`, or `const`, each with different scoping and reassignment rules. Choosing the right declaration keyword affects how the variable behaves throughout the code.
apply
The apply() method of Function instances calls this function with a given this value, and arguments provided as an array (or an array-like object).
Arguments object
The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function, available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0. But, in modern code, rest parameters should be preferred.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers. They include `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (remainder), and `**` (exponentiation). The `+` operator is also used for string concatenation, which can cause issues when operands are mixed types.
Arrays
Arrays are ordered, indexed collections that can hold values of any type. JavaScript arrays are dynamic, meaning they can grow and shrink, and provide a rich set of built-in methods like `map()`, `filter()`, `reduce()`, `push()`, and `pop()`. They are one of the most used data structures in JavaScript.
Arrow Functions
Arrow functions are a concise syntax for writing function expressions introduced in ES6. They use `=>` instead of the `function` keyword and do not have their own `this`, `arguments`, or `super` bindings. They are commonly used for callbacks and short expressions, but are not suitable as object methods or constructors.
Assignment Operators
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (`=`), which assigns the value of its right operand to its left operand. That is, `x = f()` is an assignment expression that assigns the value of `f()` to `x`.
Async/Await
`async/await` is a special syntax to work with promises in a more comfortable fashion. We use `async` keyword to declare a async function that return a Promise, and the `await` keyword makes a function wait for a Promise.
Asynchronous JavaScript
Asynchronous JavaScript allows code to start long-running operations, like network requests or timers, and continue executing other code while waiting for them to complete. JavaScript is single-threaded, so asynchronous patterns prevent the main thread from blocking. The main mechanisms are callbacks, Promises, and async/await.
BigInt Operators
Most operators that can be used with the `Number` data type will also work with `BigInt` values (e.g. arithmetic, comparison, etc.). However, the unsigned right shift `>>>` operator is an exception and is not supported. Similarly, some operators may have slight differences in behaviour (for example, division with `BigInt` will round towards zero).
bigint
`BigInt` is a primitive type for representing integers of arbitrary size, beyond the safe integer limit of the `number` type. A BigInt is created by appending `n` to an integer literal or using the `BigInt()` function. It is used when precise integer arithmetic is needed for very large numbers, such as in cryptography or financial calculations.
bind()
The `bind()` method in JavaScript allows you to create a new function with a specific context and optionally preset arguments. Unlike `call()` or `apply()`, `bind()` does not immediately invoke the function. Instead, it returns a new function that can be called later, either as a regular function or with additional arguments. This is particularly useful when you want to ensure that a function retains a specific context, regardless of how or when it's invoked.
Bitwise Operators
Bitwise operators treat their operands as 32-bit integers and perform operations at the bit level. They include `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), `<<` (left shift), `>>` (right shift), and `>>>` (unsigned right shift). They are used in low-level programming, flag manipulation, and performance-critical code.
Block
Block scope limits a variable's visibility to the block of code enclosed in curly braces `{}` where it is declared. Variables declared with `let` and `const` are block-scoped. A variable inside an `if` statement or `for` loop with block scope is not accessible outside that block.
boolean
A boolean is a primitive type with only two possible values: `true` or `false`. Booleans are used in conditions, comparisons, and logical operations. JavaScript also has truthy and falsy values, where non-boolean values are implicitly converted to `true` or `false` in a boolean context.
break / continue
`break` exits a loop or switch statement immediately, skipping any remaining iterations. `continue` skips the rest of the current iteration and moves to the next one. Both can be used with labels to control nested loops.
Built in functions
JavaScript offers a variety of built-in functions that simplify common tasks, available globally or within specific objects without requiring explicit definition. Functions like parseInt(), setTimeout(), and Math.random() can be used directly, while objects like Array, String, and Date include built-in methods for efficient data manipulation. Understanding these functions enhances development by leveraging JavaScript’s core features without reinventing the wheel.
Built-in Objects
JavaScript provides a set of built-in objects that are available without any imports. These include `Math`, `Date`, `JSON`, `Array`, `RegExp`, `Promise`, and others. They provide standard functionality for common tasks like math operations, date manipulation, and data serialization.
call()
The `call()` method allows you to invoke a function with a given `this` value, and arguments provided individually.
Callback Hell
The callback hell is when we try to write asynchronous JavaScript in a way where execution happens visually from top to bottom, creating a code that has a pyramid shape with many **})** at the end.
Callbacks
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Classes
Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but have some syntax and semantics that are not shared with ES5 class-like semantics.
Closures
Function closures are one of the most powerful, yet most misunderstood, concepts of JavaScript that are actually really simple to understand. A closure refers to a function along with its lexical environment. It is essentially what allows us to return a function `A`, from another function `B`, that remembers the local variables defined in `B`, even after `B` exits. The idea of closures is employed in nearly every other JavaScript program, hence, it's paramount for a JavaScript developer to know it really well.
Comma operators
The comma operator (`,`) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a `for` loop.
Kỹ Năng Trọng Tâm & Thực Hành
Giai đoạn 2 tập trung hoàn thiện 26 chủ đề then chốt.
CommonJS
CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ESModules standard used by browsers and other JavaScript run-times, but CJS is still widely used in backend Node.js applications. Sometimes these modules will be written with a .cjs extension.
Comparison Operators
Comparison operators are the operators that compare values and return true or false. The operators include: `>`, `<`, `>=`, `<=`, `==`, `===`, `!=` and `!==`
Conditional Operators
The conditional (ternary) operator is the only JavaScript operator that takes three operands: `condition ? valueIfTrue : valueIfFalse`. It is a concise alternative to `if...else` for simple conditional assignments or expressions. Nesting ternary operators deeply is discouraged because it reduces readability.
Conditional statements
When you write code, you often want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript, we have three conditional statements: `if`, `if...else`, and `switch`.
[const] keyword
Constants are block-scoped, much like variables declared using the `let` keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be re-declared (i.e. through a variable declaration). However, if a constant is an object or array its properties or items can be updated or removed.
Control Flow
Control flow refers to the order in which statements are executed in a program. JavaScript provides conditional statements (`if...else`, `switch`) to branch logic, and exception handling (`try/catch/finally`, `throw`) to manage errors. Writing clear control flow makes code easier to follow and debug.
Data Structures
A Data structure is a format to organize, manage and store data in a way that allows efficient access and modification. JavaScript has primitive (built-in) and non-primitive (not built-in) data structures. Primitive data structures come by default with the programming language and you can implement them out of the box (like arrays and objects). Non-primitive data structures don't come by default and you have to code them up if you want to use them.
Datatypes
Data type refers to the type of data that a JavaScript variable can hold. There are seven primitive data types in JavaScript (Number, BigInt, String, Boolean, Null, Undefined and Symbol). Objects are non-primitives.
Debugging Issues
The browser DevTools debugger allows developers to set breakpoints, step through code, inspect variable values, and trace the call stack. The console allows logging values and evaluating expressions in the current scope. These tools make it possible to understand what code is doing at runtime and identify the source of bugs.
Debugging Memory Leaks
In JavaScript, memory leaks commonly occur within heap allocated memory, where short lived objects are attached to long lived ones and the Garbage Collector cannot safely de-allocate that memory as it is still referenced from the root set (the global object).
Debugging performance
Enter the dev tools and check out the Lighthouse tab. This is essentially a series of tests that analyses the currently open website on a bunch of metrics related to performance, page speed, accessibility, etc. Feel free to run the tests by clicking the **Analyze Page Load** button (you might want to do this in an incognito tab to avoid errors arising from extensions you're using). Once you have the results, take your time and read through them (and do click through to the reference pages mentioned alongside each test result to know more about it!)
Default Parameters
Default function parameters allow named parameters to be initialized with default values if no value or `undefined` is passed.
DOM APIs
With HTML DOM, JavaScript can access and change all the elements of an HTML document such as its attributes, CSS styles, remove elements, add and create new elements on the page. Web API means application programming interface for the web. All browsers have a set of built-in Web APIs to support complex operations, and to help accessing data. Like Geo-location API, Web Storage, Web History and others.
do...while statement
The `do...while` statement creates a loop that executes a specified statement until the test condition evaluates to `false`. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
Equality Comparisons
Comparison operators are used in logical statements to determine equality or difference between variables or values. Comparison operators can be used in conditional statements to compare values and take action depending on the result.
Error Objects
JavaScript provides a set of built-in error types that extend the base `Error` class. These include `TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, and others. Each has a `message` property and a `stack` trace. Using specific error types makes it easier to catch and handle different failure modes separately.
ESModules
ESModules is a standard that was introduced with ES6 (2015). The idea was to standardize how JS modules work and implement these features in browsers. This standard is widely used with frontend frameworks such as react and can also be used in the backend with Node.js. Sometimes these modules will be written with a .mjs extension.
Event Loop
The Event Loop is one of the most important aspects to understand about Node.js. Why is this so important? Because it explains how Node.js can be asynchronous and have non-blocking I/O, it explains the "killer feature" of Node.js, which made it this successful.
Exception Handling
In JavaScript, all exceptions are simply objects. While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object. (excerpt from Rollbar)
Explicit binding
Explicit binding is when you use the `call` or `apply` methods to explicitly set the value of `this` in a function. Explicit Binding can be applied using `call()`, `apply()`, and `bind()`.
Explicit Type Casting
Type casting means transferring data from one data type to another by explicitly specifying the type to convert the given data to. Explicit type casting is normally done to make data compatible with other variables. Examples of typecasting methods are `parseInt()`, `parseFloat()`, `toString()`.
Expressions & Operators
Expressions are combinations of values, variables, and operators that evaluate to a value. Operators perform operations on values and include arithmetic, comparison, logical, assignment, and bitwise operators. Understanding operator precedence and behavior is necessary for writing correct expressions.
Fetch
The `fetch()` method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
The for loop
The `for` loop is a standard control-flow construct in many programming languages, including JavaScript. It's commonly used to iterate over given sequences or iterate a known number of times and execute a piece of code for each iteration.
for...in loop
The `for...in` loop iterates over the enumerable properties of an object, including inherited ones. It is mainly used for iterating over object keys. It is not recommended for arrays because it iterates over all enumerable properties, not just numeric indexes, and does not guarantee order.
for...of statement
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), and the arguments object, generators produced by generator functions, and user-defined iterables.
Kiến Trúc Nâng Cao & Tối Ưu
Giai đoạn 3 tập trung hoàn thiện 26 chủ đề then chốt.
Function Borrowing
Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of `.call()`, `.apply()`, or `.bind()`, all of which exist to explicitly set this on the method we are borrowing.
Function Parameters
The parameter is the name given to the variable declared inside the definition of a function. There are two special kinds of syntax: default and rest parameters.
Function
Function scope means a variable declared inside a function is only accessible within that function. Variables declared with `var` are function-scoped. Each function call creates a new scope, so variables inside a function do not conflict with variables of the same name in other functions.
Functions
Functions exist so we can reuse code. They are blocks of code that execute whenever they are invoked. Each function is typically written to perform a particular task, like an addition function used to find the sum of two or more numbers. When numbers need to be added anywhere within your code, the addition function can be invoked as many times as necessary.
Garbage Collection
Memory management in JavaScript is performed automatically and invisibly to us. We create primitives, objects, functions… All that takes memory. The main concept of memory management in JavaScript is reachability.
Global
Global scope refers to variables declared outside any function or block, making them accessible from anywhere in the program. In browsers, global variables become properties of the `window` object. Overusing global variables is discouraged because it increases the risk of naming conflicts and makes code harder to maintain.
History of JavaScript
JavaScript was initially created by Brendan Eich of NetScape and was first announced in a press release by Netscape in 1995. It has a bizarre history of naming; initially, it was named Mocha by the creator, which was later renamed LiveScript. In 1996, about a year later after the release, NetScape decided to rename it to JavaScript with hopes of capitalizing on the Java community (although JavaScript did not have any relationship with Java) and released Netscape 2.0 with the official support of JavaScript.
Hoisting
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope before code execution. Variables declared with `var` are hoisted and initialized as `undefined`. Function declarations are fully hoisted, meaning they can be called before they appear in the source code. `let` and `const` are hoisted but not initialized, resulting in a temporal dead zone.
How to run JavaScript
JavaScript can be run directly in a browser's developer console, embedded in an HTML page using a `<script>` tag, or executed on the server with Node.js. For development, tools like VS Code with a live server extension or online environments like CodePen and JSFiddle make it easy to write and run JavaScript immediately.
if...else
The `if...else` statement executes a block of code if a condition is true, and an optional `else` block if it is false. Additional conditions can be checked with `else if`. It is the most basic form of conditional logic in JavaScript.
IIFEs
An IIFE (Immediately Invoked Function Expression) is a function that is defined and called at the same time. It is written as `(function() { ... })()` or `(() => { ... })()`. IIFEs are used to create a private scope, avoiding polluting the global namespace, and were common before ES6 modules.
Implicit Type Casting
Implicit type conversion happens when the compiler or runtime automatically converts data types. JavaScript is loosely typed language and most of the time operators automatically convert a value to the right type.
in a method
When a function is called as a method of an object, `this` refers to the object before the dot. For example, in `user.greet()`, `this` inside `greet` refers to `user`. This is the most intuitive use of `this`.
this in a method
Methods are properties of an object which are functions. The value of this inside a method is equal to the calling object. In simple words, this value is the object “before dot”, the one used to call the method.
in arrow functions
Arrow functions do not have their own `this` binding. Instead, they inherit `this` from the lexical scope where they were defined. This makes arrow functions predictable in callbacks and event handlers where regular functions would lose their intended `this` context.
in event handlers
In an event handler attached to a DOM element, `this` refers to the element that received the event. For example, in a click handler, `this` is the button or element that was clicked. Arrow functions do not have their own `this`, so they inherit it from the surrounding scope instead.
Indexed collections
Indexed Collections are collections that have numeric indices i.e. the collections of data that are ordered by an index value. In JavaScript, an array is an indexed collection. An array is an ordered set of values that has a numeric index.
Introduction to JavaScript
JavaScript is a high-level, interpreted programming language created to add interactivity to web pages. It runs in the browser and, with Node.js, on the server as well. JavaScript is the only language that runs natively in web browsers, making it the foundation of frontend web development.
isLooselyEqual
The abstract equality comparison (loose equality) is the algorithm behind the `==` operator. It defines the rules for how values of different types are coerced before comparison. For example, `null == undefined` is `true`, but `null == 0` is `false`. Understanding this algorithm explains many of JavaScript's surprising equality behaviors.
isStrictlyEqual
The strict equality comparison is the algorithm behind the `===` operator. It returns `false` if the types differ, without any coercion. For the same type, it compares values directly, with the exception that `NaN === NaN` is `false`.
Javascript Iterators and Generators
Iterators and generators, introduced into JavaScript with ECMAScript 6, represent an extremely useful concept related to iteration in the language. Iterators are objects, abiding by the iterator protocol, that allows us to easily iterate over a given sequence in various ways, such as using the `for...of` loop. Generators, on the other hand, allow us to use functions and the `yield` keyword to easily define iterable sequences that are iterators as well.
Javascript Versions
JavaScript, invented by Brendan Eich, achieved the status of an ECMA standard in 1997 and adopted the official name ECMAScript. This language has evolved through several versions, namely ES1, ES2, ES3, ES5, and the transformative ES6. These updates have played a crucial role in improving and standardizing JavaScript, making it widely used and valuable in the ever-changing field of web development.
JSON
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
Keyed Collections
Keyed collections are data structures that store values indexed by keys. In JavaScript, `Map` and `WeakMap` are keyed collections that allow any value, including objects and functions, to be used as a key. Unlike plain objects, Maps maintain insertion order and provide methods like `get()`, `set()`, and `has()`.
let
`let` declares a block-scoped variable that can be reassigned after declaration. Unlike `var`, it is limited to the block, statement, or expression where it is defined. `let` is the standard choice when a variable's value needs to change over time.
Lexical scoping
Before one can make an intuition of closures in JavaScript, it's important to first get the hang of the term '**_lexical environment_**'. In simple words, the lexical environment for a function `f` simply refers to the environment enclosing that function's definition in the source code.
Hệ Sinh Thái & Triển Khai Thực Tế
Giai đoạn 4 tập trung hoàn thiện 26 chủ đề then chốt.
Logical Operators
Logical operators combine or invert boolean expressions. The main logical operators are `&&` (AND), `||` (OR), and `!` (NOT). In JavaScript, `&&` and `||` return one of their operands rather than a strict boolean, which makes them useful for short-circuit evaluation and default value patterns.
Loops and Iterations
Loops and iterations allow code to execute repeatedly based on a condition or over a collection of values. JavaScript provides several loop constructs for different use cases: `while`, `do...while`, `for`, `for...in`, and `for...of`. Choosing the right loop depends on what is being ite
Map
A `Map` is a keyed collection that stores key-value pairs and remembers insertion order. Unlike plain objects, Map keys can be of any type, including objects and functions. Maps are preferred over plain objects when keys are dynamic or when the order of entries matters.
Memory Lifecycle
The memory lifecycle has three stages: allocation (memory is reserved when a value is created), use (memory is read and written during execution), and release (memory is freed when it is no longer reachable). In JavaScript, allocation happens implicitly, and release is handled by the garbage collector.
Memory Management
Low-level languages like C, have manual memory management primitives such as `malloc()` and `free()`. In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.
Modules
Modules encapsulate all sorts of code like functions and variables and expose all this to other files. Generally, we use it to break our code into separate files to make it more maintainable. They were introduced into JavaScript with ECMAScript 6.
null
`null` is a primitive value that explicitly represents the absence of any value or object. It is typically used to indicate that a variable intentionally holds no value. `typeof null` returns `"object"`, which is a known quirk of the language from its original implementation.
number
The `number` type represents both integers and floating-point values in JavaScript. It uses the IEEE 754 double-precision format, which means all numbers are stored as floats. Special values include `Infinity`, `-Infinity`, and `NaN` (Not a Number), which result from certain arithmetic operations.
Prototypes
JavaScript is an object-oriented language built around a prototype model. In JavaScript, every object inherits properties from its prototype, if there are any. A prototype is simply an object from which another object inherits properties. To create complex programs using JavaScript, one has to be proficient in working with prototypes — they form the very core of OOP in the language.
Object
JavaScript object is a data structure that allows us to have key-value pairs; so we can have distinct keys and each key is mapped to a value that can be of any JavaScript data type. Comparing it to a real-world object, a pen is an object with several properties such as color, design, the material it is made of, etc. In the same way, JavaScript objects can have properties that define their characteristics.
Object.is
`Object.is()` is a method for comparing two values with stricter behavior than `===`. It handles two edge cases differently: `Object.is(NaN, NaN)` returns `true` (while `NaN === NaN` is `false`), and `Object.is(+0, -0)` returns `false` (while `+0 === -0` is `true`). It is useful when exact value identity is needed.
Promises
Promises are a much better way to work with asynchronous code in JavaScript than the old and error-prone callback approach. They were introduced into JavaScript with ECMAScript 6. Using promises, we can manage extremely complex asynchronous code with rigorous error-handling setup, write code in a more or less synchronous style, and keep ourselves from running into the so-called callback hell.
Prototypal Inheritance
The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the Prototype of an object, we use Object.getPrototypeOf and Object.setPrototypeOf.
Recursion
One of the most powerful and elegant concept of functions, recursion is when a function invokes itself. Such a function is called a **_recursive function_**. As recursion happens, the underlying code of the recursive function gets executed again and again until a terminating condition, called the _base case_, gets fulfilled. As you dive into the world of algorithms, you'll come across recursion in many many instances.
Rest
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. It is defined by prefixing the last parameter with `...`, such as `function sum(...numbers)`. Unlike the `arguments` object, rest parameters are a true array and work with arrow functions.
SameValue
SameValue is the equality algorithm used by `Object.is()`. It is the strictest equality comparison in JavaScript: it returns `true` only when two values are identical, treating `NaN` as equal to `NaN` and `+0` as not equal to `-0`. It is used in a few specific internal operations.
SameValueZero
SameValueZero is an equality algorithm used internally by JavaScript in methods like `Array.prototype.includes()` and `Map` key comparison. It behaves like `===` but treats `NaN` as equal to itself. Unlike `SameValue`, it considers `+0` and `-0` as equal.
Scope & Function Stack
The function stack (call stack) is the mechanism that tracks the execution of function calls. Each time a function is called, a new frame is pushed onto the stack; when it returns, the frame is popped. Scope determines which variables are accessible at each point in the call stack, and closures preserve access to variables from outer scopes.
Set
A `Set` is a collection of unique values with no duplicates. Values in a Set can be of any type, and the Set maintains insertion order. Sets are useful for deduplicating arrays and checking membership efficiently.
setInterval
`setInterval()` repeatedly executes a function at a specified interval in milliseconds. It continues until `clearInterval()` is called with the returned ID. It is used for polling, animations, and periodic tasks, though `requestAnimationFrame` is preferred for visual updates.
setTimeout
`setTimeout()` schedules a function to run after a specified delay in milliseconds. It is asynchronous: the rest of the code continues executing while the timer runs. It returns an ID that can be used with `clearTimeout()` to cancel the scheduled execution.
Strict Mode
Strict mode is an opt-in variant of JavaScript that enforces stricter parsing and error handling. It is enabled by adding `"use strict"` at the top of a file or function. Strict mode prevents the use of undeclared variables, disallows duplicate parameter names, and makes `this` undefined in functions called without a context, among other restrictions.
String Operators
In addition to the comparison operators, which can be used on string values, the concatenation operator (`+`) concatenates two string values together, returning another string that is the union of the two operand strings. The shorthand assignment operator `+=` can also be used to concatenate strings.
String
String is a primitive type that holds a sequence of characters. String in Javascript is written within a pair of single quotation marks `''`, double quotation marks `""`, or backticks ` `` ` (template literals). All types of quotes can be used to contain a string but only if the starting quote is the same as the end quote.
Structured Data
Structured data refers to data organized in a defined, parseable format. In JavaScript, JSON (JavaScript Object Notation) is the primary format for structured data exchange. It represents data as key-value pairs and arrays and is widely used for API communication and configuration files.
Switch
The `switch` statement evaluates an expression and executes the matching `case` block. It is an alternative to a long chain of `if...else if` statements when comparing one value against multiple options. Each `case` should typically end with a `break` to prevent fall-through to the next case.
Chuyên Gia & Mở Rộng Hệ Thống
Giai đoạn 5 tập trung hoàn thiện 22 chủ đề then chốt.
Symbol
Symbols are a unique and immutable primitive data type in JavaScript, introduced in ECMAScript 6 (ES6). They are often used to create unique property keys for objects, ensuring no property key collisions occur. Each Symbol value is distinct, even when multiple are created with the same description. Symbols can be created using the Symbol() function, and their primary use case is to add hidden or special properties to objects that won’t interfere with other properties or methods.
Throw Statement
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate. (excerpt from MDN)
try/catch/finally
The `try` block contains code that might throw an error. If an error occurs, execution jumps to the `catch` block, which receives the error object. The `finally` block runs regardless of whether an error was thrown, making it useful for cleanup operations like closing connections.
Type Casting
Type conversion (or typecasting) means the transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like [JavaScript](https://developer.mozilla.org/en-US/docs/Glossary/JavaScript)) automatically converts data types. The source code can also explicitly require a conversion to take place.
Type Conversion/Coercion
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they convert values from one data type to another with one key difference — type coercion is implicit. In contrast, type conversion can be either implicit or explicit.
Typed Arrays
Typed Arrays are array-like objects for working with raw binary data of a specific numeric type. Types include `Int8Array`, `Uint8Array`, `Float32Array`, and others, each representing a different size and format. They are used in performance-sensitive contexts such as audio processing, WebGL, and network protocols.
typeof operator
The `typeof` operator returns a string indicating the type of an operand. It works with primitives and functions but has some quirks, such as returning `"object"` for `null`. It is commonly used to check whether a variable is defined or to guard against unexpected types in a function.
Unary Operators
JavaScript Unary Operators are the special operators that consider a single operand and perform all the types of operations on that single operand. These operators include unary plus, unary minus, prefix increments, postfix increments, prefix decrements, and postfix decrements.
undefined
`undefined` is the default value of a variable that has been declared but not assigned a value. It is also the return value of functions that do not explicitly return anything. Unlike `null`, which is intentionally empty, `undefined` typically indicates something has not been set.
Using Browser DevTools
Browser DevTools are the built-in developer tools available in browsers like Chrome and Firefox. They provide tools for inspecting HTML and CSS, debugging JavaScript, analyzing network requests, profiling performance, and detecting memory leaks. DevTools are the primary environment for diagnosing and fixing issues in web applications.
using it alone
When `this` is used outside any function, it refers to the global object. In a browser, that is `window`. In Node.js at the top level of a module, `this` refers to `module.exports`. This usage is rarely needed in application code.
Using (this) keyword
The `this` keyword refers to the object that is currently executing the code. Its value depends on how and where a function is called, not where it is defined (except in arrow functions). Understanding `this` is one of the more complex aspects of JavaScript.
[var] keyword
The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
Variable Declarations
Variable declarations introduce a variable name into the current scope. JavaScript provides three ways to declare variables: `var`, `let`, and `const`. The choice between them affects scope, hoisting behavior, and whether the variable can be reassigned.
Naming Rules
A variable name should accurately identify your variable. When you create good variable names, your JavaScript code becomes easier to understand and easier to work with. Properly naming variables is really important. JavaScript also has some rules when it comes to naming variables; read about these rules through the links below.
Variable Scopes
Scope determines where in a program a variable is accessible. JavaScript has three main scope levels: global, function, and block. Understanding scope is important for avoiding naming conflicts and unintended variable access.
Weak Map
A `WeakMap` is a collection of key-value pairs where the keys must be objects and are held weakly. If the key object is garbage collected, the entry is automatically removed from the WeakMap. It is used for storing private data associated with objects without preventing garbage collection.
Weak Set
A `WeakSet` is a collection of objects held with weak references. Unlike a regular Set, it only accepts objects (not primitives), and entries are automatically removed when the object is garbage collected. WeakSet is used when tracking object references without preventing them from being garbage collected.
What is JavaScript
JavaScript is a scripting language used to create dynamic behavior in web applications. It can manipulate HTML and CSS, respond to user events, communicate with servers, and update content without reloading the page. It follows the ECMAScript specification, which defines the language standard.
while
The `while` loop executes a block of code as long as a specified condition is true. The condition is evaluated before each iteration, so if it is false from the start, the body never runs. It is used when the number of iterations is not known in advance.
Working with APIs
When working with remote APIs, you need a way to interact with those APIs. Modern JavaScript provides two native ways to send HTTP requests to remote servers, `XMLHttpRequest` and `Fetch`.
XMLHttpRequest
`XMLHttpRequest` (XHR) is a built-in browser object that can be used to interact with server. XHR allows you to update data without having to reload a web page. Despite the word XML in its name, XHR not only used to retrieve data with XML format, we can use it with any type of data, like JSON, file(s), and much more.