qiangc.net

Javascript

Web <!DOCTYPE html> <html> <head> <script> alert("Hello, world!"); </script> <head> <body /> <html> NodeJs console.log("Hello, world!");

Variable declaration

var

Declares a variable, optionally initializing it to a value.

let

Declares a block-scoped, local variable.

const

Declares a block-scoped, read-only named constant.

Function declaration

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: name, a list of parameters, and function body enclosed in curly brackets { }.

function name (...args) { ... }

Declares an async function with the specified parameters.

async function

Generator declaration

Generator Functions enable writing iterators more easily.

function* { ... }

Class declaration

The class declaration creates a new class with a given name using prototype-based inheritance. Class declarations are not hoisted.

class name { ... }

Expression

this

"this" refers to the current object. In general, this refers to the calling object in a method.

()

Grouping operator

yield

Pause and resume a generator function.

yield*

Delegate to another generator function or iterable object.

Literal

true and false

The Boolean type has two literal values: true and false.

""

A string literal is zero or more characters enclosed in double (") or single (') quotation marks.

[]

Array initializer/literal.

{}

Object initializer/literal syntax.

/ab+c/i

Regular expression literal syntax.

Left-hand-side

new

Use the "new" operator to create an instance of a user-defined object type or of one of the built-in object types.

super

The super keyword is used to call functions on an object's parent.

...

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Function

A function expression, such a function can be anonymous, does not have to have a name.

function (...args) { ... }

Generator

The function* keyword defines a generator function expression.

function* (...args) { ... }

Class

A class expression

class { ... }

Assignment operator

=

Shorthand assignment operator

Addition += Subtraction -= Multiplication *= Division /= Remainder %= Left shift <<= Right shift >>= Unsigned right shift >>>= Bitwise AND &= Bitwise XOR ^= Bitwise OR |=

Destructuring assignment operator

Destructuring assignment: to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

var [one, two, three] = ['one', 'two', 'three'];

Comparison operator

Equal == Not equal != Strict equal === Strict not equal !== Greater than > Greater than or equal <= Less than < Less than or equal <=

Arithmetic operator

Addition + Subtraction - Multiplication * Division / Remainder % Increment ++ Decrement --

Unary arithmetic operator

Negation - Plus +

Bitwise logical operator

Bitwise AND & Bitwise OR | Bitwise XOR ^ Bitwise NOT ~

Bitwise shift operator

Left shift << Sign-propagating right shift >> Zero-fill right shift >>>

Logical operator

Logical AND && Logical OR || Logical NOT !

Logical short-circuit evaluation operator

Short-circuit evaluated to false. false && anything Short-circuit evaluated to true. true || anything

String operator

Concatenation +

Conditional (ternary) operator

condition ? val1 : val2

Comma operator

,

Unary operator

The delete operator deletes an object, an object's property, or an element at a specified index in an array. delete The typeof operator returns a string indicating the type of the unevaluated operand. typeof The void operator specifies an expression to be evaluated without returning a value. void

Relational operator

The in operator returns true if the specified property is in the specified object. in The instanceof operator returns true if the specified object is of the specified object type. instanceof

Primitive type

undefined

A top-level property whose value is not defined.

null

A special keyword denoting a null value.

boolean

true and false

number

An integer or floating point number. For example: 42 or 3.14159.

string

A sequence of characters that represent a text value. For example: "Howdy"

Symbol

Symbol (new in ECMAScript 2015). A data type whose instances are unique and immutable.

Object type

Object

The Object constructor creates an object wrapper. Object can be named container for values.

JSON

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON.

Function

The Function constructor creates a new Function object, e.g. new function ([arg1[, arg2[, ...argN]],] body)

Date

Generator

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

GeneratorFunction

The GeneratorFunction constructor creates a new generator function object, e.g. new GeneratorFunction ([arg1[, arg2[, ...argN]],] body). GeneratorFunction could be obtained by: Object.getPrototypeOf(function*(){}).constructor

Promise

Starting with ECMAScript2015, JavaScript gains support for Promise objects allowing you to control the flow of deferred and asynchronous operations.

Proxy

Reflect

Math

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

Indexed collection object

Array

Array object is a global object that is used in the construction of arrays.

  • Int8Array
  • Uint8Array
  • Uint8ClampedArray
  • Int16Array
  • Uint16Array
  • Int32Array
  • Uint32Array
  • Float32Array
  • Float64Array

Keyed collection object

Map

The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

WeakMap

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced.

WeakSet

The WeakSet object lets you store weakly held objects in a collection.

Error object

  • Error
  • EvalError
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Text processing object

RegExp

Internationalization object

  • Intl
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat

WebAssembly object

  • WebAssembly
  • WebAssembly.Module
  • WebAssembly.Instance
  • WebAssembly.Memory
  • WebAssembly.Table
  • WebAssembly.CompileError
  • WebAssembly.LinkError
  • WebAssembly.RuntimeError

Flow control statement

Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

break

Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

continue

Conditional flow control statement

Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.

if...else

Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

switch

Error handling flow control statement

The throw statement throws a user-defined exception.

throw

Marks a block of statements to try, and specifies a response, should an exception be thrown.

try...catch

Loop statement

The for statement creates a for loop.

for

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true.

white

The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false.

do...while

Iterate statement

Iterats over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

for...of

Iterates over all non-Symbol, enumerable properties of an object. for...in should not be used to iterate over an Array where the index order is important.

for...in

Import, export statement

Used to import functions exported from an external module, another script.

import

Used to export functions to make them available for imports in external modules, another scripts.

export

Declaration

A declaration is a language construct that specifies properties of an identifier: it declares what a word (identifier) means. A declaration is used to announce the existence of the entity to the compiler.

Variable

A symbolic name for a stored value. A variable declared using the var or let statement with no assigned value specified has the value of undefined, and its type is undefined.

Type (value)

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals. e.g.

var [one, two, three] = ['one', 'two', 'three'];

Unary operation

A unary operation is an operation with only one operand.

Expression

An expression is any valid unit of code that resolves to a value. Expression always returns a result and often does not have side effects at all.

Expression: arithmetic

Evaluates to a number, for example 3.14159. (Generally uses arithmetic operators.)

Expression: string

Evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators.)

Expression: logical

Evaluates to true or false. (Often involves logical operators.)

Expression: primary expressions

Basic keywords and general expressions in JavaScript.

Expression: left-hand-side

Left values are the destination of an assignment.

Expression: literal

Literals to represent values in JavaScript. These are fixed values, not variables.

Statement

Statements do not return results and are executed solely for their side effects.

  • statement: flow control
  • statement: conditional statement
  • statement: error handling
  • statement: loop
  • statement: iteration

Collection

collection: indexed

Collections of data which are ordered by an index value. This includes arrays and array-like constructs such as Array objects and TypedArray objects.

collection: keyed

Collections of data which are ordered by a key.

Collection operation

iterator

Processing each of the items in a collection is a very common operation. Iterators and generators provide a mechanism for customizing the behavior of for...of loops.

generator

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Hoisting

Move to the scope top. Only declaration gets hoisted to the top and not the assigement.

Closure

JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). A closure is created when the inner function is somehow made available to any scope outside the outer function.

Meta programming

Starting with ECMAScript 2015, JavaScript gains support for the Proxy and Reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). With the help of these two objects you are able to program at the meta level of JavaScript.

Type: boolean

let isDone: boolean = false;

Type: number

let decimal: number = 6; let hex: number = 0xf00d;

Type: string

let color: string = "blue";

Type: Array

let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3];

Type: Tuple

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same. e.g.

let x: [string, number]; x = ["hello", 10];

Type: Enum

Enum is a way of giving more friendly names to sets of numeric values.

enum Color { Red, Green, Blue }

Type: any

To opt-out of type-checking and let the values pass through compile-time checks.

let notSure: any = 4;

Type: void

Commonly see this as the return type of functions that do not return a value. Declaring variables of type void is not useful because you can only assign undefined or null to them.

Type: null

let n: null = null;

Type: undefined

let u: undefined = undefined;

Type: never

The never type represents the type of values that never occur.

Type: Object

Object is a type that represents the non-primitive type, i.e. any thing that is not number, string, boolean, symbol, null, or undefined.

Type assertion

<T>, Type assertion, e.g., <string> value as-syntax, e.g., value as string

Type intersection

&, An intersection type combines multiple types into one. e.g, Object, String & Serializable is a Object, String and Serializable.

Type union

|, A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so string | number is the type of a value that can be a number or a string.

Variable declaration

var let cons

Define interface.

interface I { //... }

Optional interface property

Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration.

interface I { s?: string; ... }

Readonly interface property

Define readonly property by adding readonly before the name of the property. Readonly property should only be modifiable when an object is first created. TypeScript comes with a ReadonlyArray<T> type that is the same as Array<T> with all mutating methods removed.

interface I { readonly s: string; ... }

Function type interface property

To describe a function type with an interface, we give the interface a call signature. This is like a function declaration with only the parameter list and return type given. Each parameter in the parameter list requires both name and type.

interface I { (s: string, t: string): boolean; ... } let o: I = function(s: string, t: string) { //... }

Indexable type interface property

I interface that has an index signature. This index signature states that when a I is indexed with a number, it will return a string. There are two types of supported index signatures: string and number.

interface I { [i: number]: string; }

String index signature

interface I { [s: string]: any; }

Extends interface

Interfaces extending Interfaces.

interface I extends I1 {}

An interface can extend multiple interfaces, creating a combination of all of the interfaces.

interface I extends I1, I2 {}

When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. This means that when you create an interface that extends a class with private or protected members, that interface type can only be implemented by that class or a subclass of it.

interface I extends C {}

Generics interface

Generics interface, take object literal from the call signature and move it to an interface.

interface I { <T>(arg: T): T; }

Generics interface, move the generic parameter to be a parameter of the whole interface.

interface I<T> { (arg: T): T; }

Class

Defina a class. A class declaration creates two things: a type representing instances of the class and a constructor function.

class C {}

Abstract class

Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members.

abstract class C { }

Implements an interfacee

class C implements I { }

Class inheritance

class C extends A { constructor() { super(); } }

Class property modifier

Modifiers. Public by default. When a member is marked private, it cannot be accessed from outside of its containing class. The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes.

class C { public a: string; protected b: string; private _c: string; }

Readonly modifier.

class C { readonly s: string; }

Class property accessor

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object.

class C { private _p: string; get p(): string {} }

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object.

class C { private _p: string; set p(s: string) {} }

Class static property

We can also create static members of a class. Static members are visible on the class itself rather than on the instances. Each instance accesses this value through prepending the name of the class. Similarly to prepending "this".

class C { static s : string = ""; }

Generics class

class C<T>{}

Optional function parameter

Adding a ? to the end of parameters we want to be optional. Any optional parameters must follow required parameters.

function f(s: string, t?: string) { }

Default function parameter

Default-initialized parameters set a value that a parameter will be assigned if the user does not provide one, or if the user passes undefined in its place. Default-initialized parameters that come after all required parameters are treated as optional, and just like optional parameters, can be omitted when calling their respective function. Unlike plain optional parameters, default-initialized parameters don’t need to occur after required parameters. If a default-initialized parameter comes before a required parameter, users need to explicitly pass undefined to get the default initialized value.

function f(s: string, t = "") { }

Rest function parameter

Rest parameters are treated as a boundless number of optional parameters.

function f(s: string, ...t: string[]) { }

Generics function

The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations.

function f<T>(arg: T): T { return arg; }

Generic type as a call signature of an object literal type.

let i: {<T>(arg: T): T} = f;

Function expression

A function’s type has two parts: the type of the arguments and the return type. When writing out the whole function type, both parts are required.

let v: (x: number, y: number) => number = function(x: number, y: number): number { return 0; };

Function contextual typing

Same as the full type of the function. TypeScript compiler can figure out the type if you have types on one side of the equation but not the other.

let v: (x: number, y: number) => number = function(x, y) { return 0; };

Same as the full type of the function. TypeScript compiler can figure out the type if you have types on one side of the equation but not the other.

let v = function(x: number, y: number): number { return 0; };

Generics constraint

Declare a type parameter that is sub class of another type. function f<T extends O>(arg: T): T { return arg; } Declare a type parameter that is constrained by another type parameter. function f<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } Using class types in generics. function f<T>(c: {new(): T; }): T { return new c(); }

Excess property check

Object literals undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, it will be an error. Three approaches to get around these checks:

  • type assertion
  • string index signature
  • assign the object to another variable

Type assertion

A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. e.g., <string> someValue

Type guard

A type guard is some expression that performs a runtime check that guarantees the type in some scope. To define a type guard, we simply need to define a function whose return type is a type predicate.

Generics

Generics is one of the main tools for creating reusable components.

Type variable

Type variable, a special kind of variable that works on types rather than values.