Hướng dẫn dùng compariosns JavaScript
JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes and classes. It also supports functional programming since functions can be easily created via expressions and passed around like any other object. Nội
dung chính This page serves as a quick overview of various JavaScript language features, written for readers with background in other languages, such as C or Java. Data typesLet's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript offers seven primitive types:
Everything else is known as an Object. Common object types include:
Functions aren't special data structures in JavaScript — they are just a special type of object that can be called. NumbersJavaScript has two built-in numeric types: Number and BigInt. The Number type is a IEEE 754 64-bit double-precision floating point value, which means integers can be safely represented between -(253 − 1) and 253 − 1 without loss of precision, and floating point numbers can be stored all the way up to 1.79 × 10308. Within numbers, JavaScript does not distinguish between floating point numbers and integers.
So an apparent integer is in fact implicitly a float. Because of IEEE 754 encoding, sometimes floating point arithmetic can be imprecise.
For operations that expect integers, such as bitwise operations, the number will be converted to a 32-bit integer. Number literals can also have prefixes to indicate the base (binary, octal, decimal, or hexadecimal), or an exponent suffix.
The BigInt type is an arbitrary length integer. Its behavior is
similar to C's integer types (e.g. division truncates to zero), except it can grow indefinitely. BigInts are specified with a number literal and an
The standard arithmetic operators are supported, including addition, subtraction, remainder arithmetic, etc. BigInts and numbers cannot be mixed in arithmetic operations. The
There are three ways to convert a string to a number:
You can also use the unary plus Number values also include
StringsStrings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are UTF-16 encoded.
Strings can be written with either single or double quotes — JavaScript does not have the distinction between characters and strings. If you want to represent a single character, you just use a string consisting of that single character.
To find the length of a string (in code units), access its Strings have utility methods to manipulate the string and access information about the string. Because all primitives are immutable by design, these methods return new strings. The
Other typesJavaScript distinguishes between
JavaScript has a Boolean type, with possible values
You can perform this conversion explicitly using the
However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an Boolean operations such as The Symbol type is often used to create unique identifiers. Every symbol created with the VariablesVariables in JavaScript are declared using one of three keywords:
A variable declared with
If you declare a variable without assigning any value to it, its value is
In most other languages, this would log "1" and "2", because before the JavaScript is dynamically typed. Types (as described in the previous section) are only associated with values, but not with variables. For OperatorsJavaScript's numeric operators include You can use The
If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:
Adding an empty string to something is a useful way of converting it to a string itself. Comparisons in JavaScript can be made using
The double-equals and triple-equals also have their
inequality counterparts: JavaScript also has bitwise operators and logical operators. Notably, logical operators don't work with boolean values only — they work by the "truthiness" of the value.
The
Or for caching values (when falsy values are invalid):
For a comprehensive list of operators, see the guide page or reference section. You may be especially interested in the operator precedence. GrammarJavaScript grammar is very similar to the C family. There are a few points worth mentioning:
For an in-depth look at the JavaScript grammar, see the reference page for lexical grammar. Control structuresJavaScript has a similar set of control structures to
other languages in the C family. Conditional statements are supported by
JavaScript doesn't have JavaScript has
JavaScript's
JavaScript also contains two other prominent for loops:
The
Similar to C, case clauses are conceptually the same as labels, so if you don't add
a Unlike some languages like Rust, control-flow structures are statements in JavaScript, meaning you can't assign them to a variable, like
JavaScript errors are handled using the
Errors can be thrown using the
In general, you can't tell the type of the error you just caught, because anything can be thrown from a
If an error is uncaught by any For a comprehensive list of control flow statements, see the reference section. ObjectsJavaScript objects can be thought of as collections of key-value pairs. As such, they are similar to:
JavaScript objects are hashes. Unlike objects in statically typed languages, objects in JavaScript do not have fixed shapes — properties can be added, deleted, re-ordered, mutated, or dynamically queried at any time. Object keys are always strings or symbols — even array indices, which are canonically integers, are actually strings under the hood. Objects are usually created using the literal syntax:
Object properties can be accessed using dot (
Property access can be chained together:
Objects are always references, so unless something is explicitly copying the object, mutations to an object would be visible to the outside.
This also means two separately created objects will never be equal (
For more on objects and prototypes, see the This page has omitted all details about object prototypes and inheritance because you can usually achieve inheritance with classes without touching the underlying mechanism (which you may have heard to be abstruse). To learn about them, see Inheritance and the prototype chain. ArraysArrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can
naturally be accessed only using Arrays are usually created with array literals:
JavaScript arrays are still objects — you can assign any properties to them, including arbitrary number indices. The only "magic" is that
The array we got above is called a sparse array because there are uninhabited slots in the middle, and will cause the engine to deoptimize it from an array to a hash table. Make sure your array is densely populated! Out-of-bounds indexing doesn't throw. If you query a non-existent array index, you'll get a value of
Arrays can have any elements and can grow or shrink arbitrarily.
Arrays can be iterated with the
Or, since arrays
are iterable, you can use the
Arrays come with a plethora of array methods. Many of them would iterate the array — for example,
FunctionsAlong with objects, functions are the core component in understanding JavaScript. The most basic function declaration looks like this:
A JavaScript
function can take 0 or more parameters. The function body can contain as many statements as you like and can declare its own variables which are local to that function. The Functions can be called with more or fewer parameters than it specifies. If you call a function without passing the parameters it
expects, they will be set to
There are a number of other parameter syntaxes available. For example, the rest parameter syntax allows collecting all the extra parameters passed by the caller into an array, similar to Python's
In the above code, the variable The rest parameter will store all arguments after where it's declared, but not before. i.e. If a function accepts a list of arguments and you already hold an array, you can use the spread syntax in the function call to spread the array as a list of elements. For instance: We mentioned that JavaScript doesn't have named parameters. It's possible, though, to implement them using object destructuring, which allows objects to be conveniently packed and unpacked.
There's also the default parameter syntax, which allows omitted parameters (or those passed as
Anonymous functionsJavaScript lets you create anonymous functions — that is, functions without names. In practice, anonymous functions are typically used as arguments to other functions, immediately assigned to a variable that can be used to invoke the function, or returned from another function.
That makes the anonymous function invocable by calling There's another way to define anonymous functions — using an arrow function expression.
Arrow functions are not semantically equivalent to function expressions — for more information, see its reference page. There's another way that anonymous functions can be useful: it can be simultaneously declared and invoked in a single expression, called an Immediately invoked function expression (IIFE):
For use-cases of IIFEs, you can read emulating private methods with closures. Recursive functionsJavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.
Function expressions can be named as well, which allows them to be recursive.
The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging. If you are used to functional programming, beware of the performance implications of recursion in JavaScript. Although the language specification specifies tail-call optimization, only JavaScriptCore (used by Safari) has implemented it, due to the difficulty of recovering stack traces and debuggability. For deep recursion, consider using iteration instead to avoid stack overflow. Functions are first-class objectsJavaScript functions are first-class objects. This means that they can be assigned to variables, passed as arguments to other functions, and returned from other functions. In addition, JavaScript supports closures out-of-the-box without explicit capturing, allowing you to conveniently apply functional programming styles.
Note that JavaScript functions are themselves objects — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the Objects section. Inner functionsJavaScript function declarations are allowed inside other functions. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:
This provides a great deal of utility in writing more maintainable code. If a called function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside it. This keeps the number of functions that are in the global scope down. This is also a great counter to the lure of global variables. When writing complex code, it is often tempting to use global variables to share values between multiple functions, which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together without polluting your global namespace. ClassesJavaScript offers the class syntax that's very similar to languages like Java.
JavaScript classes are just functions that must be instantiated with the
Static properties are created by prepending For a detailed guide on various class features, you can read the guide page. Asynchronous programmingJavaScript is single-threaded by nature. There's no paralleling; only concurrency. Asynchronous programming is powered by an event loop, which allows a set of tasks to be queued and polled for completion. There are three idiomatic ways to write asynchronous code in JavaScript:
For example, here's how a file-read operation may look like in JavaScript:
The core language doesn't specify any asynchronous programming features, but it's crucial when interacting with the external environment — from asking user permissions, to fetching data, to reading files. Keeping the potentially long-running operations async ensures that other processes can still run while this one waits — for example, the browser will not freeze while waiting for the user to click a button to grant permission. If you have an async value, it's not possible to get its value synchronously. For example, if you have a promise, you can only access the eventual result via the In fact, the single-threaded model has made Node.js a popular choice for server-side programming due to its non-blocking IO, making handling a large number of database or file-system requests very performant. However, CPU-bound (computationally intensive) tasks that's pure JavaScript will still block the main thread. To achieve real paralleling, you may need to use workers. To learn more about asynchronous programming, you can read about using promises or follow the asynchronous JavaScript tutorial. ModulesJavaScript also specifies a module system supported by most runtimes. A module is usually a file, identified by it's file path or
URL. You can use the
Unlike Haskell, Python, Java, etc., JavaScript module resolution is entirely host-defined — it's usually based on URLs or file paths, so relative file paths "just work" and are relative to the current module's path instead of some project root path. However, the JavaScript language doesn't offer standard library modules — all core functionalities are powered by global variables like
Different runtimes may use different module systems. For example, Node.js uses the package manager npm and is mostly file-system based, while Deno and browsers are fully URL-based and modules can be resolved from HTTP URLs. For more information, see the modules guide page. Language and runtimeThroughout this page, we've constantly mentioned that certain features are language-level while others are runtime-level. JavaScript is a general-purpose scripting language. The core language specification focuses on pure computational logic. It doesn't deal with any input/output — in fact, without extra runtime-level APIs (most notably A runtime, or a host, is something that feeds data to the JavaScript engine (the interpreter), provides extra global properties, and provides hooks for the engine to interact with the outside world. Module resolution, reading data, printing messages, sending network requests, etc. are all runtime-level operations. Since its inception, JavaScript has been adopted in various environments, such as browsers (which provide APIs like DOM), Node.js (which provides APIs like file system access), etc. JavaScript has been successfully integrated in web (which was its primary purpose), mobile apps, desktop apps, server-side apps, serverless, embedded systems, and more. While you learn about JavaScript core features, it's also important to understand host-provided features in order to put the knowledge to use. For example, you can read about all web platform APIs, which are implemented by browsers, and sometimes non-browsers. Further explorationThis page offers a very basic insight into how various JavaScript features compare with other languages. If you want to learn more about the language itself and the nuances with each feature, you can read the JavaScript guide and the JavaScript reference. There are some essential parts of the language that we have omitted due to space and complexity, but you can explore on your own:
|