Types, Values, and Variables
NaN
NaN does not compare equal to any other value, including itself.
You can’t write x === NaN
.
Instead, you should write x != x
or Number.isNaN(x)
Text
JavaScript uses the UTF-16 encoding of the Unicode character set. Unicode characters whose codepoints do not fit in 16 bits are encoded following the rules of UTF-16 as a sequence of two 16-bit values.1
2let e = "𝑒"
e.length // => 2
Template Strings
ES6 has a built-in tag function String.raw()
which returns the text within backticks raw, without any processing of backslash escapes:1
String.raw`\n` // => \n
null and undefined
null |
undefined |
|
---|---|---|
Language keyword | yes | no (predefined global constant) |
Type | object | undefined |
Meaning | A speacial object value that indicates “no object” | The value of variables that have not been initialized and the value you get when you query the value of an object property or array element that does not exist |
1 | null == undefined // => true |
Type Conversions
1 | 8 + " yalu" // => "8 yalu" |
Value | to String | to Number | to Boolean |
---|---|---|---|
undefined | “undefined” | NaN | false |
null | “null” | 0 | false |
true | “true” | 1 | |
false | “false” | 0 | |
“” | 0 | false | |
“2.7” | 2.7 | true | |
“one” | NaN | true | |
0 | “0” | false | |
-0 | “0” | false | |
NaN | “NaN” | false | |
Infinity | “Infinity” | true | |
-Infinity | “-Infinity” | true | |
1 | “1” | true | |
{} (any object) | true | ||
[] | “” | 0 | false |
[2] (one numeric element) | “2” | 2 | true |
[‘a’] (any other array) | use join() | NaN | true |
function(){} (any function) | NaN | true |
You can convert numbers in other bses (between 2 and 36).1
2
3
4let n = 17;
let binary = "0b" + n.toString(2); // => "0b10001"
let octal = "0o" + n.toString(8) // => "0o21"
let hex = "0x" + n.toString(16) // => "0x11"
Variable Declaration and Assignment
let
declares variables that change.
const
declares constant variable.
It is an untyped language, so a JavaScript variable can hold a vlue of any type.
var
has the same syntax as let
. However, it does not have block scope. Instead, it is scoped to the body of the containing function no matter how deeply nested it is inside the function. When it is outside of a function body, it declares a global variable and is implemented as properties of the global object. For example, var x = 2
is like global.x = 2;
or window.x = 2;
. And it cannot be deleted with the delete
operator.
Destructuring Assignment
The value on the right-hand side of the equals sign is an array or object (a “structured” value) and the left-hand side specifies one or more variable names using a syntax that mimics array and object literal syntax.
1 | let [x, y] = [1, 2] // x => 1, y => 2 |
If the left-hand side of the assignment had included a variable whose name was not a property of the object, that variable would be assigned undefined
.
Objects
Property
Attempting to query a property of an object that does not exist throws an error. It can be avoided by using the &&
operator.
1 | let surname = book && book.author && book.author.surname; |
Delete Properties:
1 | delete book.author; |
It can conly delete own properties, not inherited ones. To delete an inherited property, you must delete it from the prototype object in which it is defined.
in
can distinguish between properties that do not exist and properties that exist but have been set to undefined
.
1 | let o = { x: undefined }; |
Serializing Objects
Object serialization is the process of converting an object’s state to a string from which it can later be restored.
JSON - JavaScript Object Notation
1 | let o = {x: 1, y: {z: [false, null, ""]}}; |
Object Methods
toString()
The default toString()
method simply returns [object Object]
which does not display useful information. You can define your own toString()
like this:
1 | let o = { |
valueOf()
It converts an object to some primitive type other than a string, usually a number. And obejcts can then be compared with <
and >
.
1 | let p = { |
Arrays
- untyped: an array element may be of any type
- index from 0 up to (2^32-2)
- dynamic: grow or shrink as needed
- sparse: elements need not have contiguous indexes
Because of the optional trailing comma, [,,]
has a length of 2, not 3.
1 | let undefs = [ , , ] |
To remove duplicates in an array, you can convert it to a set and converted it back to an array.
1 | let letters = [...'yalu studio']; |
Create an array:
1 | let a = new Array() |
When you try to query a nonexistent property of any object, you don’t get an error, instead you get undefined
.
Array’s length is guaranteed to be the largest index + 1, whether it is sparse or not. By setting the length property, the rest of the array will be deleted.
1 | let a = [1, 2, 3, 4, 5]; |
Adding elements into the array
1 | // Simply assign values to new indexes |
forEach()
1 | let data = [1, 2, 3, 4, 5] |
map()
1 | let a = [1, 2, 3]; |
filter()
Keeps the values that let the function return true
.
1 | let a = [5, 4, 3, 2, 1]; |
find() and findIndex()
Return the first element/ index found in the array, otherwise return -1
every() and some()
1 | // return true if and only if the predicate function returns true for all elements in the array |
reduce() and reduceRight()
reduce()
takes 2 arguments, the first one is the accumulated value, initially 0. If ignored, it uses the second arguments as the first arguments. reduceRight()
is the same, but start from the highest index to the lowest.
1 | let a = [1, 2, 3, 4, 5]; |
Add to / Remove from the arrays
push()
add to the end of the arrayunshift()
add to the beginning of the arraypop()
remove the last element of the arrayshift()
remove the first element of the array
splice()
The first argument is the start index, and the second index is the number of the elements are to deleted.
1 | let a = [1, 2, 3, 4, 5, 6, 7, 8] |
The following additional arguements will be inserted at the start position.
1 | let a = [1, 2, 3, 4, 5] |
fill()
1 | let a = new Array(5) |
copyWithin()
Arguments
- The first index to copy to
- The first index to be copied (default 0)
- The end index to be copied (default till the end)
findAll()
You can implements it yourself
1 | // find all indexes of value x in array a |
includes()
Test whether it is in the array, can be used to test NaN
.
1 | let a = [1, true, 3, NaN]; |
sort()
By default, sorted in alphabetical order. Alternatively, provide a function that the first argument appears before the second when the function returns number less than 0.
1 | let a = [33, 4, 1111, 222]; |
Functions
Arrow functions
1 | // Return an object |
Type check
Example:
1 | function sum(a) { |
Anonymous function
The parentheses are required. Otherwise, it parses the function
keyword as a function declaration statement.
1 | (function() { |
Closures
Fundamental rule of lexical scoping: JavaScript functions are executed using the scope they were defined in.
this
is a keyword. this
cannot be used within functions defined with the function
keyword. Use arrorw functions =>
instead, or call bind()
on the closure before returning it, or assign the outer this value to a variable that the closure will inherit:
1 | const self = this; |
Classes
Defining a class
Using a factory method
1 | function range(from, to) { |
Using a constructor
1 | function Range(from, to) { |
- Names begin with a capital letter
- Use
new
keyword
Using the class
keyword
1 | class Range { |
- Use object literal method shorthand, omit the
function
keyword - No commas are used to seperate functions
- constructor function can be ommitted if it doesn’t need to do initializing
Inherit from another class
1 | class Span extends Range { |
- Not “hoisted” (moved to the top of the file)
- Declared in strict mode
Private fields
Private fields start with a #
.
1 | class Buffer { |
Iterators and Generators
An Iterable object is any object with a special iterator method that returns an iterator object.
An iterator is any object with an next()
method that returns an iteration result object.
An iteration result object is an object with properties named value
and done
1 | let iterable = [99]; |
Lazy
1 | function words(s) { |
Generator Examples
1 | function* fibonacciSequence() { |
yield*
and Recursive Generators
1 | function* sequence(...iterables) { |
Note that yield*
must be used in a generator function, thus cannot be used in an arrow function.
Asynchronous JavaScript
Timer
1 | // Set timeout |
Promises
A Promise is an object that represents the result of an asynchronous computation.
1 | getJSON('/api/user/profile') |
Error handling
p.then(null, c)
equals to p.catch(c)
Parallel
1 | const urls = [ /* zero or more urls here */ ] |
async
and await
You can only use the await
keyword within functions that have been declared with the async
keyword.
1 | async function gestHighScore() { |