The JavaScript Encyclopedia

This is a work in progress. The goal of this project is to produce a complete encyclopedia for the current language and any future versions that might appear. The encyclopedia will be developed in Cyc, a simple language that was inspired by Brian Reid's Scribe. Cyc is described in the preface.The source of this book can be found at

https://github.com/douglascrockford/TheJavaScriptEncyclopedia.

public domain

Preface

In 2009, as we were wrapping up ES5, I was thinking about how to organize the material. I designed a hypertext encyclopedia format specifically for programming languages. I think the format would have worked well, but I never finished the project.

It is easy to forget that the web was originally intended to be a hypertext system. The JavaScript Encyclopedia would have used hypertext very effectively. Many of the articles would contain code that demonstrated or implemented a concept.

I intended that The JavaScript Encyclopedia be finished when ES5 was released. Not only did I miss the ES5 deadline, but since then ES6 has been published, which was itself four years late. So it is starting to become clear that I am not going to get this done on my own. I need help.

The very perliminary material can be seen at http://www.crockford.com/javascript/encyclopedia.

Cyc

The most important thing I learned in doing the prototype was that HTML Hypertext Markup Language is a horrible language for writing hypertext. It is clumsy, fussy, ugly, and error-prone. So I designed Cyc, a simple language with only one reserved character. By writing in Cyc, we can use Cyc processors that can produce

A source is a set of enviroments that can contain other environments and content. The environments are

A book may contain one or more chapters. A chapter contains one or more specimens, which can each be a reserved word, name, concept, or special character. A specimen may contain one or more articles. An article may contain sections.

Paragraphs are indicated with a blank line.

A program is a JavaScript program that is illustrating or implementing a concept.

Some paragraphs will be marked with an ES5 flag, indicating a new feature that is not available with, or somehow incompatible with language processors that implement ES6. With each new edition, we should remove all of the old flags, and then add new flags to highlight the latest incompatibilities.

A table is a two dimensional grid structure. @| and @_ are used to separate the cells and rows. @! is used inside of a cell to indicate a header cell.

A list gives each paragraph a bullet.

A link refers to another feature of the hypertext. A url identifies a feature outside of the hypertext.

Text can be marked as bold or italics or typewriter-like. Programmers like their programs to look like they were written with typewriters because they love antiques and steam.

The special mark reserved word shows specimens that are reserved words. Descriptive marks can be placed after special characters and operators to give them names.

There are 6 sets of bracketing characters. They are all available all of the time. It is likely that there is at least one pair that will not conflict with the content being bracketed.

Example:

This sentence contains @b(bold), @i "italics", and @t 'typewriter' stuff.

In addition, @begin and @end provide an alternate way of handling environments that can be easier for larger structures.

@begin[program]
function foo() {
    return '[';
}
@end[program]

Contributions may be submitted at https://github.com/douglascrockford/TheJavaScriptEncyclopedia.

Eventually, this preface will be modified to pertain to the book and not the making of the book.

Introduction

The language described in this book is ES6. The standard, which is designated as ECMA-262, may be found at http://www.ecma-international.org/publications/standards/ECMA-262.HTM.

Because of trademark problems, the standard for the JavaScript language is called ECMAScript. JavaScript is a trademark of Oracle Corporation.

Paragraphs marked with the ES5 icon in the left margin indicate concerns for users of The Fifth Edition. ES6, The Sixth Edition, significantly enlarged the language, creating hazards for users of ES5. Programmers who must honor compatibility commitments should pay close attention to the ES5 warnings.

ES5 describes two dialects, the strict mode dialect and the sloppy mode dialect. Stick with the strict mode dialect.

The use strict pragma is written as a string literal so that it will not cause a syntax error when processed by an ES3 system.

"use strict";

Most of the material in this encyclopedia is organized into 27 chapters (one for each letter and the Special Characters). Each chapter lists several specimens, where a specimen is an element of syntax or a concept. The specimens are ordered alphabetically. A specimen marked with reserved word indicates that the word is reserved and cannot be used as a parameter or variable name. The special characters chapter is sorted according to the ASCII sequence.

Under each specimen there will be one or more articles that explain, expand, or are related to the specimen. An article may be composed of one or more sections.

The title of an article may contain one or more classifiers, such as

The article of a title may contain a comment. It is used in cases where the subject is an abbrievation or special character such as ; semicolon.

Many articles will have examples. Expression examples will be written with a comment showing the result.

3 + 4      // 7
3 + '4'    // "34"

Chapter 16 of the ECMAScript standard gives implementors of ECMAScript processors some license to extend the language with experimental or proprietary features. Such features might be incorporated into a future edition or might be abandoned. It is unwise to rely on such features because of the likelihood of diminished reliability. Such non-standard features will not be included in this encyclopedia.

Special Characters

! exclamation point

! prefix operator not

The ! operator produces false if its operand is truthy, and true if its operand is falsy.

! true        // false
! false       // true
! 'false'     // false
! 0           // true
! 42          // false
!! 42         // true

!= infix operator coercing not equal

The != operator determines if two operands are not equal. If the operands have different types it may attempt to coerce the types of the operands before comparing them. It produces the opposite of the == infix operator coercing equal.

The != operator produces the same result as this function:

function coercing_not_equal(left, right) {
    return !(left == right);
}

Avoid this operator. Always use the !== infix operator not equal instead.

!== infix operator not equal

The !== operator determines if two operands are not equal. It produces the opposite of the === infix operator equal. The result can be false only if the operands are the same type.

If the operands are objects, the result is false only if the operands are the same object. If the operands are similar objects, the result is true .

The !== infix operator not equal produces the same result as this function:

function not_equal(left, right) {
    return !(left === right);
}

The expression x !== x will always result in false except when the value of x is NaN not a number. This bizarre behavior is intentional.

false != 'false'             // true
1 !== '1'                    // true
null !== undefined           // true
{} !== {}                    // true
1 !== 1.0                    // false
'cat' !== 'c' + 'a' + 't'    // false
NaN !== NaN                  // true

" double quotation mark

See string literal.

$ dollar sign

$ identifier character

The $ character is treated as a letter in an identifier. It was added to the language specifically for the use of code generators and macro processors so that they could generate identifiers with confidence that they would not collide with programs produced by humans. Unfortunately, the developer community ignored the intention of $ and used it to create ugly, cryptic identifiers that collide with each other.

% percent sign

% infix operator remainder

The % operator computes the remainder produced by the division of two operands, a dividend and a divisor. If the operands are not numbers, % attempts to coerce them to numbers. If either operand cannot be coerced to a number or is NaN not a number, or if the dividend is an infinity, or if the divisor is a zero, then the result is NaN not a number. Otherwise, if the divisor is an infinity, the result is the dividend.

The % operator produces the same result as this function:

function remainder(left, right) {
    var dividend = +left,
        divisor = +right,
        quotient = dividend / divisor;
    if (divisor === Infinity || divisor === -Infinity) {
        return (isFinite(dividend))
            ? dividend
            : NaN;
    } else {
        return dividend - (
            divisor *
            (Math[
                (quotient >= 0)
                    ? 'floor'
                    : 'ceil'
            ](quotient))
        );
    }
}

The sign of the remainder will be the sign of the dividend, not the divisor. This differs from the modulo operator found in some other languages, where the result has the sign of the divisor. The modulo function can be computed with this function, which adds the divisor to the remainder if the remainder has the wrong sign:

function modulo(left, right) {
    var dividend = +left,
        divisor = +right,
        mod = dividend % divisor;
    if (mod && (divisor > 0) === (mod < 0)) {
        mod += divisor;
    }
    return mod;
}

Examples:

 15 %  4            //  3
-15 %  4            // -3
-15 % -4            // -3
 15 % -4            //  3
 15 %  0            // NaN
 15 % -Infinity     // 15
  0 %  Infinity     //  0
  0 %  0            // NaN
Infinity % 4        // NaN
Infinity % Infinity // NaN

%= assignment infix operator remainder

The %= operator replaces the left value with the remainder of the left value divided by the right value. So

left %= divisor;

is a streamlined equivalent of

left = left % divisor;

& ampersand

& infix operator bitwise and

The & infix operator performs the bitwise and operation. The bitwise and operation uses 32 bits from each operand. If two corresponding bits are 1, then the corresponding result bit is 1. Otherwise, the corresponding result bit is 0. The operands are converted from a number (64 bit floating point) to a 32-bit integer. It produces the same result as this function:

function bitwise_and(left, right) {
    var result = 0, bit, i, left_int, right_int,
        two_32 = 4294967296,    // Math.pow(2, 32)
        two_31 = 2147483648;    // Math.pow(2, 31)

// Make 32-bit unsigned integers from the operands. The % is a remainder
// operator, not a modulo operator, so some sign correction may be necessary.

    left_int = Math[(left >= 0)
        ? 'floor'
        : 'ceil'](left) % two_32;
    if (left_int < 0) {
        left_int += two_32;
    }
    right_int = Math[(right >= 0)
        ? 'floor'
        : 'ceil'](right) % two_32;
    if (right_int < 0) {
        right_int += two_32;
    }

// For each of the 32 bits,
//      Double the current result
//      Set the new bit to 1
//      If the most significant bits are set, then subtract them out
//      Otherwise clear the new bit
//      Add the new bit to the result
//      Double the ints, rotating the next most significant bit into position

    for (i = 0; i < 32; i += 1) {
        result += result;
        bit = 1;
        if (left_int >= two_31) {
            left_int -= two_31;
        } else {
            bit = 0;
        }
        if (right_int >= two_31) {
            right_int -= two_31;
        } else {
            bit = 0;
        }
        result += bit;
        left_int += left_int;
        right_int += right_int;
    }

// If the most significant bit of the result is set, then produce a negative.

    if (result >= two_31) {
        result -= two_32;
    }
    return result;
}

&& infix operator and

Blah.

&= assignment infix operator bitwise and

Blah.

' single quotation mark

See string literal.

( left parenthesis

Parentheses have many uses. In operand position, they provide grouping for overriding operator precedence or to make the meaning of complicated expressions clearer. In suffix position, they cause the invocation of functions. In function definitions and catch blocks they define parameters and exception variables. In statement position, they can disambiguate function literal from function statement. In a statement they denote a conditional expression or a special variable.

( ) grouping

In an expression, parentheses can be used to override the precedence of operators, or to break up complicated expressions to make them easier to read.

3 + 4 * 5      // 23
3 + (4 * 5)    // 23
(3 + 4) * 5    // 35

Parentheses can also be used to improve the readability of an immediate function.

( ) parameter list

See function .

( ) statement punctuator

Parentheses are used in statements. See

( ) suffix operator invoke

Blah.

) right parenthesis

See ( left parenthesis.

* asterisk

* infix operator multiply

The * operator multiplies its operands together. If the operands are not numbers, it attempts to coerce them to numbers. If either operand cannot be coerced to a number or is NaN not a number, then the result will be NaN not a number.

3 * 4    // 7

*/ Close comment

See /* begin comment.

*= assignment infix operator multiply

Blah.

+ plus sign

+ infix operator add or concatenate

The + operator can perform either addition or concatenation depending of the types of its operands. If either operand is a string, then it converts both operands to strings and concatenates then, producing a new string with all of the characters from both operands. Otherwise, it converts both operands to numbers and then attempts to add them. It produces the same result as this function:

function add_or_concatenate(left, right) {
    if (left && typeof left === 'object') {
        left = left.valueOf();
    }
    if (right && typeof right === 'object') {
        right = right.valueOf();
    }
    if (typeof left === 'string' || typeof right === 'string') {
        return String(left).concat(String(right));
    }
    return +left + (+right);    // return the sum of left + right
}

The + operator is the only arithmetic operator with this type confusion. Addition is commutative. Concatenation is not. It is really weird having an operator that is commutative and noncommutative at the same time.

Examples:

1 + 0                  // 1
1 + 1                  // 2
1 + (-1)               // 0
1 + ''                 // '1'
1 + undefined          // NaN
1 + null               // 1
1 + false              // 1
1 + true               // 2
1 + NaN                // NaN
1 + Infinity           // Infinity
true + true            // 2
true + false           // 1
true + '!'             // 'true!'
Infinity + (-1)        // Infinity
Infinity + Infinity    // Infinity
'' + ''                // ''
'1' + "1"              // '11'
'1' + 0                // '10'
'1' + ''               // '1'
'1' + undefined        // '1undefined'
'1' + null             // '1null'
'1' + NaN              // '1NaN'
'1' + Infinity         // '1Infinity'
'1' + true             // '1true'
'$' + 3 + 4            // '$34'
'$' + (3 + 4)          // '$7'

+ prefix operator to number

Blah.

++ assignment prefix operator pre-increment

Blah.

++ assignment suffix operator post-increment

Blah.

+= assignment infix operator add or concatenate

Blah.

, comma

, infix operator comma

The , infix operator takes two operands, evalutes them both, and returns the value of only the second operand. This operator may not be used in places where a , separator can appear, such as in an argument list, in a var statement, or in an object literal or array literal unless the operand it forms is wrapped in ( ) grouping. This operator invites misuse of the for statement when initializing or incrementing multiple induction variables. The , infix operator comma should not be used.

, separator

The comma is used to separate operands in the object literal, the array literal, the argument list. The comma is used to separate identifiers in the the parameter list and the var statement.

- minus sign

- infix operator subtract

Blah.

- prefix operator negate

Blah.

-- assignment prefix operator pre-decrement

Blah.

-- assignment suffix operator post-decrement

Blah.

-= assignment infix operator subtract

Blah.

. decimal point

Blah.

. suffix operator select

Blah.

... prefix operator ellipsis

Blah. Dot dot dot.

rest

Blah. parameter list

spread

Blah. argument list array literal

/ slash

The / slash character is also known as the solidus and as the virgule. It is used as the division operator, and it is used to form a comment or regexp literal. The overloading of this character is a source of trouble. Also be careful to not confuse it with \ backslash.

/ infix operator divide

Blah.

/ regexp delimiter

Blah.

/* begin comment

Blah.

// comment

Blah.

/= assignment infix operator divide

Blah.

: colon

Blah.

See:

; semicolon

The ; semicolon is used to terminate a statement. It is required on these statements:

In some cases a mechanism called automatic semicolon insertion allows for leaving off the terminating semicolon in some cases. Unfortunately, semicolon insertion has some inherent problems and should not be relied upon.

Semicolon is also used to separate the control clauses in a for statement.

< left angle bracket

< infix operator less than

Blah.

<< infix operator bitwise shift left

Blah.

<<= assignment infix operator bitwise shift left

Blah.

<= infix operator less than or equal

= equal sign

= assignment infix operator

Blah.

== infix operator coercing equal

The == operator determines if two operands are equal. If the operands have different types it may attempt to coerce the types of the operands before comparing them. It produces the opposite of the != infix operator.

The == operator produces the same result as this function:

function coercing_equal(left, right) {
    if (left === right) {
        return true ;
    }
    if (left === null) {
        return right === undefined;
    }
    if (right === null) {
        return left === undefined;
    }
    if (typeof left === 'number' && typeof right === 'string') {
        return left === +right;
    }
    if (typeof left === 'string' && typeof right === 'number') {
        return +left === right;
    }
    if (typeof left === 'boolean') {
        return coercing_equal(+left, right);
    }
    if (typeof right === 'boolean') {
        return coercing_equal(left, +right);
    }
    if
        (typeof left === 'object' &&
        (
            left.constructor === Number ||
            left.constructor === String ||
            left.constructor === Boolean
        ) &&
        (typeof right === 'string' || typeof right === 'number')
    ) {
        return coercing_equal(left.valueOf(), right);
    }
    if (
        (typeof left === 'string' || typeof left === 'number') &&
        typeof right === 'object' &&
        (
            right.constructor === Number ||
            right.constructor === String ||
            right.constructor === Boolean
        )
    ) {
        return coercing_equal(left, right.valueOf());
    }
    return false ;
}

Avoid this operator. It can produce false positives. Always use the === infix operator equal instead.

Examples:

'' == 0                  // false
0 == ''                  // true
0 == '0'                 // true
false == 'false'         // false
false == 0               // true
false == undefined       // false
false == null            // false
null == undefined        // true
' \t\r\n ' == 0          // true
'cat' === "cat"          // true
'cat' === 'CAT'          // false
Infinity == Infinity     // true
-Infinity == Infinity    // false
Infinity == NaN          // false
NaN == NaN               // false

=== infix operator equal

The === operator compares two values, producing true if they are equal and false if they are not. Two strings are considered equal if they have the same length and contain exactly the same code points in the same sequence. To references to the same object or array are considered equal. Two similar objects or two similar arrays are not considered equal.

The expression x === x will always result in true except when the value of x is NaN not a number. Surprisingly, there exist mathematicians that think this was a good idea. It presents an obvious programming hazard. For example, suppose you need a function that tests that a function returns the correct value. Special handling is required for the case where the expected value is NaN not a number. Simply using === to compare the expected value and the result will do the wrong thing when the expected value is NaN not a number, so much more complicated comparisons are required using the typeof prefix operator and the isNaN primordial function.

Two numbers that are only approximately equal may produce a false result.

Examples:

'' === 0                  // false
0 === ''                  // false
0 === '0'                 // false
false === 'false'         // false
false === 0               // false
false === undefined       // false
false === null            // false
null === undefined        // false
' \t\r\n ' === 0          // false
Infinity === Infinity     // true
-Infinity === Infinity    // false
Infinity === NaN          // false
NaN === NaN               // false
0 === 0.00                // true
0 === -0                  // true
{} === {}                 // false
[] === []                 // false
0.1 + 0.2 === 0.3         // false

> right angle bracket

> infix operator greater than

Blah.

>= infix operator greater than or equal

Blah.

>> infix operator bitwise signed shift right

Blah.

>>= assignment infix operator bitwise signed shift right

Blah.

>>> infix operator bitwise unsigned shift right

Blah.

>>>= assignment infix operator bitwise unsigned shift right

Blah.

? question mark

? ternary operator

The ? operator takes three operands which are separated by the ? question mark and a : colon.

condition
    ? then
    : else

It is a short-circuiting operator: only one of the branches will be evaluated. If the condition operand is truthy then the then operand will be evaluated and its value will be the value of the expression. If the condition operand is falsy then the else operand will be evaluated and its value will be the value of the expression.

function signum(number) {

// Return 0 if the number is zero,
//        1 if the number is positive,
//       -1 if the number is negative.

    return (number === 0)
        ? 0
        : (number > 0)
            ? 1
            : -1;
}

[ left bracket

[ ] array literal

See array literal.

[ ] suffix operator subscript

Blah.

\ backslash

\ identifier escapement

Blah.

\ String escapement

Blah.

] right bracket

See [ left bracket.

^ caret

^ infix operator bitwise exclusive or

Blah.

^= assignment infix operator bitwise exclusive or

Blah.

_ underbar

In a name, the _ underbar character is treated as a letter. The _ underbar is used to improve the readability of names, especially when the name contains several words, such as

calculate_the_total

since a name cannot contain a space or hyphen. Another convention is to use camelCase:

calculateTheTotal

Some implementations use leading or trailing _ underbar for internal or dangerous properties, so it is best to avoid such names.

{ left curly brace

{ } block statement

See block.

{ } function body

See function.

{ } object literal

See object literal.

| vertical bar

| infix operator bitwise or

The | operator performs the bitwise or operation. The or operation uses 32 bits from each operand. If two corresponding bits are 0, then the corresponding result bit is 0. Otherwise, the corresponding result bit is 1. The operands are converted from a number (64 bit floating point) to a 32-bit integer.

function bitwise_or(left, right) {
    var result = 0, bit, i, left_int, right_int,
        two_32 = Math.pow(2, 32),    // 4294967296
        two_31 = Math.pow(2, 31);    // 2147483648

// Make 32-bit unsigned integers from the operands. The % is a remainder
// operator, not a modulo operator, so some sign correction may be necessary.

    left_int = Math[(left >= 0)
        ? 'floor'
        : 'ceil'](left) % two_32;
    if (left_int < 0) {
        left_int += two_32;
    }
    right_int = Math[(right >= 0)
        ? 'floor'
        : 'ceil'](right) % two_32;
    if (right_int < 0) {
        right_int += two_32;
    }

// For each of the 32 bits,
//      Double the current result
//      Set the new bit to 0
//      If the most significant bits are set, then subtract out the bits out
//          and set the new bit
//      Add the new bit to the result
//      Double the ints, rotating the next most significant bit into position

    for (i = 0; i < 32; i += 1) {
        result += result;
        bit = 0;
        if (left_int >= two_31) {
            left_int -= two_31;
            bit = 1;
        }
        if (right_int >= two_31) {
            right_int -= two_31;
            bit = 1;
        }
        result += bit;
        left_int += left_int;
        right_int += right_int;
    }

// If the most significant bit of the result is set, then produce a negative.

    if (result >= two_31) {
        result -= two_32;
    }
    return result;
}

|= assignment infix operator bitwise or

Blah.

|| infix operator or

Blah.

} right curly brace

See { left curly brace.

~ tilde

~ prefix operator bitwise not

A

abs

abs Math function absolute value

The Math.abs(number) function returns the absolute value of its number parameter. It could be implemented with this function:

Math.abs = function (number) {
    var result = +number;
    return (result === 0)
        ? 0
        : (result > 0)
            ? result
            : -result;
};

The result is a non-negative number, or NaN not a number if the argument cannot be converted to a valid number.

math.abs(-40)          // 40
Math.abs(-Infinity)    // Infinity
Math.abs(-0)           // 0
Math.abs("8")          // 8
Math.abs("LOL")        // NaN

Also see zero.

accessor property

Blah. See object.

acos

acos Math function arc cosine

The Math.acos(x) function is the inverse cosine function, also known as arc cosine and cos-1. Its argument x should be a number in the range -1 to 1. The result will be an angle in radians in the range 0...Math.PI.

Example:

function sphere_map(x, y, z, radius) {
    var v, u;
    v = Math.acos(z / radius) / Math.PI;
    if (y >= 0) {
        u = Math.acos(
            x / (radius * Math.sin(Math.PI * v))
        ) / (Math.PI * 2);
    } else {
        u = (Math.PI + Math.acos(
            x / (radius * Math.sin(Math.PI * v))
        )) / (Math.PI * 2);
    }
    return {x: v, y: u};
}

This is an approximate implemention of Math.acos:

Math.acos = function acos(x) {
    return (Math.PI / 2) - Math.asin(x);
}

actor

Blah.

addition

See + infix operator add or concatenate.

alert

alert primordial function

The alert function is not formally a part of the language. It is a function provided by the web browser MISSING LINK and other platforms. The alert function can take zero or more arguments. Each argument is converted to a string. All of those strings are concatenated together and shown to the user. It suspends execution of the program. Once the message is dismissed by the user, execution can resume.

The alert function is often used in debugging to display the partial results of a computation. It generally should not be used in applications because it suspends the program thread. This locks up the browser, which could cause problems with communications, timers, and other activities.

and

Blah.

See & infix operator bitwise and and && infix operator and.

angle

See radians.

apply

apply Function prototype function

Functions inherit the apply(thisArg, arguments) function from Function.prototype. The apply function takes two parameters: The thisArg parameter determines what value will be bound to the function's this parameter. The arguments parameter is an array containing the arguments to be passed to the function.

blah.

apply invocation

argument

An argument is the value of an expression that is passed to a function as part of its invocation. Each argument is bound to a parameter.

argument list

Blah.

arguments

arguments parameter

The arguments array is an implicit parameter that is made available to every function that not have an arguments parameter or arguments variable. It contains all of the actual arguments that were supplied with the invocation of the function, independent of the mapping of arguments to parameters. This makes it possible to make a function that can take a variable number of arguments. Such a function is a variadic or vararg function.

function sum() {

// Add all of the arguments.

    var i, total = 0;
    for (i = 0; i < arguments.length; i += 1) {
        total += arguments[i];
    }
    return total;
}

The arguments array is not a true array. Its length property is not as magical as a true array's length property. The isArray Array function produces false when its operand is an arguments array. Also, there can be a weird linkage between the arguments array and the parameters of the function. Changing one can change the other. The linkage can be broken by freezing the arguments array with Object.freeze(arguments).

Every function has its own arguments array, so it is not possible for one function to access the arguments array of another function unless it is explicitly provided access somehow.

It inherits from Object.prototype, not Array.prototype. If you want to use an array method such as slice on arguments, then instead of writing

arguments.slice(2)    // get an array containing all but the first two arguments

you must write

Array.prototype.slice.call(arguments, 2);    // same thing only more so

arithmetic operator

The five arithmetic infix operators are

The two arithmetic prefix operators are

The other arithmetic operations are implemented as functions. See Number prototype function and Math function.

arity

The arity of a function is the number of parameters it specifies.

array

An array is a sequence of values. Each value is given an ordinal number.

Blah.

function eratosthenes(n) {

// Produce an array of the prime numbers that are less than n.

    var composite = [],
        factor,
        result = [],
        series,
        sqrt_n = Math.sqrt(n);

    if (n > 2) {
        result.push(2);
        for (factor = 3; factor < n; factor += 2) {
            if (!composite[factor]) {
                result.push(factor);
                if (factor <= sqrt_n) {
                    for (series = factor * 2; series < n; series += factor) {
                        composite[series] = true;
                    }
                }
            }
        }
    }
    return result;
}

Array primordial function

The Array primordial function is the constructor of arrays. The [ ] array literal form is perfered. Blah.

The Array function contains these methods in Array.prototype:

Array function

The Array function contains

array literal

An array literal is an expression that produces an array value. An array literal starts with [ left bracket and ends with ] right bracket. Between the brackets are zero or more expressions, separated by , comma. Each expression contributes one element to the array. An empty array is created by []. Every time an array literal is evaluated, it produces a new array, so

function wrap_x(x) {
    return [x];
}

wrap_x(x) === wrap_x(x)    // false

because even though the two arrays are similar in structure and content and were produced by the same array literal, they are two different arrays.

Elision is permitted, meaning that if an expression before a , separator is omitted, the the value undefined is used for the member's value. Elision is visually confusing and error-prone, so it is not recommended.

Every array literal inherits from Array.prototype.

Example:

var roman = (function () {

// This immediate function returns the roman function, which converts a
// number to a Roman numeral string. The immediate function provides
// the roman function with a table that contains the elements of Roman
// numerals. The result will be compiled from these elements.

    var table = [
        ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
        ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
        ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
    ];

    return function roman(n) {
        var element, i, result = '';

        n = String(Math.floor(Math.abs(n)));
        for (i = 0; i < table.length; i += 1) {
            element = table[i][n.slice(-1)];
            if (element) {
                result = element + result;
            }
            n = n.slice(0, -1);
        }
        return 'M'.repeat(+n) + result;
    };
}());

Array prototype

Array prototype function

Array prototype number

ArrayBuffer

Blah.

ArrayBuffer function

ArrayBuffer primordial function

Blah.

ArrayBuffer prototype function

ArrayBuffer prototype

Blah.

ArrayBuffer prototype function

Blah.

ArrayBuffer prototype number

Blah.

ASCII

American Standard Code for Information Interchange is a seven bit character set designed for use with teletype machines. The set of 128 characters includes 26 uppercase letters, 26 lowercase letters, 10 decimal digits, 1 space, 32 special characters, and 33 control codes. Most of the control codes are obsolete, although a few of them have significance in JavaScript as whitespace.

All of the special characters used by JavaScript are in the ASCII set. The first 128 characters in the Unicode set are the ASCII set.

The letter A is 41 in hexadecimal.

hex0 123456789ABCDEF
0nul sohstxetxeotenqackbelbs tablf vt ff cr so si
1dle dc1dc2dc3dc4naksynetbcanem subescfs gs rs us
2space! " # $% & ' ( ) * + , - . /
30 1 2 3 45 6 7 8 9 : ; < = > ?
4@ A B C DE F G H I J K L M N O
5P Q R S TU V W X Y Z [ \ ] ^ _
6` a b c de f g h i j k l m n o
7p q r s tu v w x y z { | } ~ del

asi automatic semicolon insertion

See automatic semicolon insertion.

asin

asin Math function arc sine

The Math.asin(x) function is the inverse sine function, also known as arc sine and sin-1. Its argument x should be a number in the range -1...1. The result will be an angle in radians in the range (Math.PI / -2)...(Math.PI / 2).

This is an approximate implemention of Math.asin:

Math.asin = function asin(x) {
    x = +x;
    var even = 0,
        bottom = 1,
        top = 1,
        result = x,
        x2 = x * x,
        xxx = x;
    for (stage = 0; stage < 70; stage += 1) {
        even += 2;
        xxx *= x2;
        top *= even - 1;
        bottom *= even;
        result += (top * xxx) / (bottom * (even + 1));
    }
    return result;
};

assignment

assignment infix operator

An assignment infix operator replaces the contents of a variable or parameter or a member of an object or an element of an array with a new value. The left operand must be an lvalue. The right operand can be any expression. The simplest assignment infix operator is = assignment infix operator, which stores the value of the right operand to the left operand.

pascal = 1;

There are other assignment infix operators that first read the current value of the left operand, and then replace it with a computation performed with the current value and the value of the second operand. For example,

power *= 2;

replaces power with its previous value multiplied by 2. This provides two advantages over

power = power * 2;

It is slightly more compact, and the left operand is only evaluted once. This is beneficial if evaluation of the left operand is expensive or if it has side effects.

my_object[expensive_function(++id)] += 1;

An assignment can be used as an expression, its value being the value that is stored into its left operand. It is possible to nest assignments into complicated expressions. This is generally a bad idea because it can result in code that is difficult understand and maintain.

There is a particular problem in using assignment expressions in the control part of an if statement or while statement. The following line could possibly be correct

while (count = limit) {

but it is more likely that it was intended to be

while (count == limit) {

You should avoid programming conventions that are difficult to distinguish from common errors.

We distinguish between the assignment infix operator and the infix operator in this book because an assignment infix operator is weaker in precedence than an infix operator, and because assignment infix operators put lvalue restrictions on their left operands. An lvalue is a variable, a parameter, or an expression whose outermost operator is either . suffix operator select or [] suffix operator subscript.

The assignment infix operators are

assignment operator

There are three kinds of assignment operator.

The thing they all do in common is change the stored value of an lvalue.

assignment prefix operator

There are two assignment prefix operators:

assignment suffix operator

There are two assignment suffix operators:

associative array

See object.

atan

atan Math function arc tangent

The Math.atan(x) function is the inverse tangent function, also known as arc tangent and tan-1. Its argument x should be a number. The result will be an angle in radians in the range (Math.PI / -2)...(Math.PI / 2).

The Math.atan(x) function converts the ratio of two sides of a right triangle into the angle of the hypotenuse. This is useful when converting cartesian coordinates to polar coordinates. But there are two problems to watch out for. If one of the cartesian coordinates is zero, then the computation of the ratio could result in a division by zero, which is something to be avoided.

The other problem is the selection of the quadrant. The two components of the ratio each has its own sign. Those two signs together identify one of the four quadrants. The ratio has only one sign, so the result may be in the wrong quadrant. This must be corrected.

function polar(point) {
    var radians;
    if (point.x === 0) {
        radians = (point.y === 0)
            ? 0
            : (point.y > 0)
                ? Math.PI / 2
                : Math.PI / -2;
    } else {
        radians = Math.atan(point.y / point.x);
        if (point.x < 0) {
            if (point.y >= 0) {
                radians += Math.PI;
            } else {
                radians -= Math.PI;
            }
        }
    }
    return {
        distance: Math.sqrt(point.x * point.x + point.y * point.y),
        radians:  radians
    };
}

In cases like this, it is better to use the atan2 Math function arc tangent y/x because it does the corrections and avoids division by zero.

This is an approximate implemention of Math.atan:

Math.atan = function atan(x) {
    return Math.asin(x / Math.sqrt(x * x + 1));
};

atan2

atan2 Math function arc tangent y/x

The Math.atan2(y, x) function is the inverse tangent function, also known as arc tangent and tan-1. Its two arguments x and y should be numbers. The result will be an angle in radians in the range (Math.PI / -2)...(Math.PI / 2).

function polar(point) {
    return {
        distance: Math.sqrt(point.x * point.x + point.y * point.y),
        radians:  Math.atan2(point.y, point.x)
    };
}

See atan Math function arc tangent.

attribute

An attribute is an internal characteristic of a property of an object. See object.

automatic semicolon insertion

The rules for placement of ; semicolon at the end of a statement are a little complicated because some statements require it and some do not. The language provides a mechanism called semicolon insertion that makes it possible to leave out ; semicolon in many (but not all) situations. The semicolon insertion feature was intended to make the language simpler, but it actually makes it more complicated and fragile. There are three cases when semicolons are inserted.

It is necessary that the expression part of a return statement begin on the same line as return. For example,

function seconds(day, hour, minute, second) {

// This function will fail in a surprising way.

    return
        day    * 86400 +
        hour   *  3600 +
        minute *    60 +
        second;
}

The value returned by seconds is always undefined because a ; semicolon is inserted between return and day. In this case, that behavior is clearly undesirable, but there is no way to turn semicolon insertion off.

In the next example, a ; semicolon is not inserted after c because there is not a syntax error.

a = b + c
(d + e).print()

It is understood to mean

a = b + c(d + e).print();

which might be quite different than the intention. It is not wise to rely on semicolon insertion. It can mask errors and it can cause errors.

These should always end in ; semicolon:

Fortunately, it is a short list and is not difficult to remember. The situation is made more complicated because some of the other statements, such as if statement and while statement, are compound statements that take a block statement or other statement, and that other statement might also end in ; semicolon. That confusion is easily avoided by always using a block.

When assigning a function literal using = assignment infix operator in an expression statement or var statement, the statement should end with a ; semicolon. So this statement should end with ; semicolon:

var double = function (number) {
    return number * 2;
};

It resembles a function statement that does not end with ; semicolon, but it is a var statement, and a var statement always ends with ; semicolon.

B

banana

The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. [Joe Armstrong]

binary operator

Blah.

bind

bind Function prototype function

Blah.

bit

Blah.

bitbucket

When a bit falls out because of a shift operator, it lands in the bitbucket.

bitwise

bitwise operator

A bitwise operator treats a number as a 32 bit 2's complement signed integer. The bitwise operators are

These operators allow access to some of the primitive operations of CPUs. They all treat NaN, null, and undefined as 0. Also see integer.

Example:

var raw_base64 = (function (alphabet) {

// The raw_base64 object contains two methods, encode and decode, that convert
// strings to base64 and back, as specified in Multipurpose Internet Mail
// Extensions (MIME) Section 6.8. URL: http://www.ietf.org/rfc/rfc2045.txt.
// The standard also requires padding with = and the breaking and joining of
// lines no longer than 76 characters. We are not concerned with that. All
// we are doing here is encoding groups of 3 8-bit characters as 4 7-bit
// characters.

// The original motivation for doing this was to avoid data interchange
// problems caused by poor architectural choices in some mid 20th century
// operating systems. These workarounds became standards that are still in
// force, decades after solution of the root problem. Once something gets into
// a standard, it can take generations to get rid of it.

// We will encode using an alphabet of 64 characters: 26 upper case letters,
// 26 lower case letters, 10 digits, and two special characters. For efficent
// decoding, we will invert the alphabet ('ABC...9+/') into an object, producing
//  {
//      A: 0,
//      B: 1,
//      C: 2,
//          ...
//      '9': 61,
//      '+': 62,
//      '/': 63
//  }

    var alphabet =
            'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
        tebahpla = {};
    alphabet.split('').forEach(function (value, index) {
        tebahpla[value] = index;
    });

// Return the object containing the encode and decode methods.

    return {
        encode: function (unencoded) {
            var i,
                length = unencoded.length,
                result = [],
                in0,
                in1,
                in2;

            for (i = 0; i < length; i += 3) {

// Get the next three character codes.

                in0 = unencoded.charCodeAt(i);
                in1 = unencoded.charCodeAt(i + 1);
                in2 = unencoded.charCodeAt(i + 2);

// Redistribute 3 sets of 8 bits into 4 sets of 6 bits.

//  in:     abcdefgh ijklmnop qrstuvwx
//  out:    00abcdef 00ghijkl 00mnopqr 00stuvwx

// This involves shifting bits into a new positions, using & (and) to mask off
// some bits, and using | (or) to combine.

// Translate the 6-bit values into symbols of the alphabet and push them into
// the results.

                result.push(alphabet[in0 >> 2]);
                result.push(alphabet[((in0 & 3) << 4) | (in1 >> 4)]);

// We only output the third character if in1 was present.

                if (!isNaN(in1)) {
                    result.push(alphabet[((in1 & 15) << 2) | (in2 >> 6)]);

// And we only output the fourth character if in2 was present.

                    if (!isNaN(in2)) {
                        result.push(alphabet[in2 & 63]);
                    }
                }
            }

// Return the result string.

            return result.join('');
        },

        decode: function (encoded) {
            var i,
                length = encoded.length - 1,
                result = [],
                in0,
                in1,
                in2,
                in3;
            for (i = 0; i < length; i += 4) {

// Get the next four character codes.

                in0 = tebahpla[encoded.charAt(i)];
                in1 = tebahpla[encoded.charAt(i + 1)];
                in2 = tebahpla[encoded.charAt(i + 2)];
                in3 = tebahpla[encoded.charAt(i + 3)];

// Redistribute 4 sets of 6 bits into 3 sets of 8 bits.

//  in:     00abcdef 00ghijkl 00mnopqr 00stuvwx
//  out:    abcdefgh ijklmnop qrstuvwx

// Combine bits from in0 and in1 to produce the first character code.
// Convert the code into a character, and push it onto the result.

                result.push(String.fromCharCode((in0 << 2) | (in1 >> 4)));

// We only output the second character if in2 was present.

                if (in2 !== undefined) {
                    result.push(String.fromCharCode(((in1 & 15) << 4) | (in2 >> 2)));

// And we only output the third character if in3 was present.

                    if (in3 !== undefined) {
                        result.push(String.fromCharCode(((in2 & 3) << 6) | in3));
                    }
                }
            }

// Return the result string.

            return result.join('');
        }
    };
}());

bitwise and

Blah.

bitwise or

Blah.

block statement

A block is a compound statement that can occur anywhere that a statement can occur. It begins with a { left curly brace and ends with a } right curly brace, and between the two curly braces there are zero or more statements. Blocks are commonly used as parts of other statements, such as if statement and while statement.

A brace does not create a new scope. Only a function has scope. In many other languages, a block does create a scope, so that a variable that is declared inside of a block is not visible outside of the block. That does not happen in the language, which is why it is unwise to declare a variable in a block.

body

See function body.

boolean

The boolean type contains exactly two values: true and false. The typeof prefix operator returns 'boolean' when its operand is a boolean. A boolean value is produced by a relational operator. The boolean type is named after the mathematician George Boole.

Boolean primordial function

The Boolean(value) primordial function, when called as function, evaluates its parameter. If the value was truthy, it returns true. If the value was falsy, it returns false.

boolean literal

There are two boolean literals, representing the two boolean values: true and false .

Boolean prototype function

boolish

Every value in JavaScript is boolish in that it is either truthy or falsy. The boolean type contains only the true and false values, but the boolish type includes all values.

bound variable

Blah.

brace

See { left curly brace and } right curly brace.

bracket

See [ left bracket and ] right bracket.

break reserved word

break statement

Blah.

buffer

Blah.

buffer DataView prototype arraybuffer

Blah.

byte octet

Eight bits. Blah.

byteLength

byteLength ArrayBuffer prototype number

Blah.

byteLength DataView prototype number

Blah.

byteOffset

byteOffset DataView prototype number

Blah.

C

call

call Function prototype function

Blah.

Function.prototype.call = function (thisObject) {
    return this.apply(
        thisObject, 
        Array.prototype.slice.apply(arguments, [1])
    );
};

callback

The term callback is given to a function that is passed to another function or stored in an object with the intention that it be called at a later time. Callbacks are commonly used in subscription patterns where functions are to be called when some event has occurred. In browser applications, an event handler function is a callback.

var statusHolder = (function () {

// Produce an object containing three functions:
//
//    getStatus(): get the value of a private status variable.
//
//    addCallback(callback): subscribe a function that will be
//        called when the status changes.
//
//    setStatus(newStatus): Change the status and inform the
//        subscribers.

    var status,              // The private status variable.
        subscribers = [];    // The list of subscribing functions.
    return {
        getStatus: function () {
            return status;
        },
        addCallback: function (callback) {
            subscribers.push(callback);
        },
        setStatus: function (newStatus) {
            status = newStatus;
            subscribers.forEach(function (callback) {
                callback(status);
            });
        }
    };
}());

camelCase

Blah.

cascade

An object's methods return the same object... Blah.

Cascading Style Sheets

Blah.

case reserved word

Also see switch statement.

In many of the world's writing systems (including Latin, Greek, Cyrillic, and Armenian), letters come in two forms: lower case (or small or minuscule) and upper case (or big or capital or majuscule). For the purpose of spelling, the two cases are equivalent, but in usage the cases are distinct and Unicode gives then unqiue character codes, so while I and i are the same letter, they are different characters and have different codes.

'I' === 'i'    // false

This language is case sensitive. Case in names and strings case is significant, so 'cat' and 'Cat' are not the same string and getElementById and getElementByID are not the same name. Every reserved word is entirely lower case.

For each lower case letter there is a unique upper case letter, and for each upper case letter there is a unique lower case letter, with the following exceptions:

The German character ß scharfes S \u00df does not have an upper case form. Since ß scharfes S is a ligature for ss, some systems use SS as the upper case form of ß scharfes S. Most languages pair I dotless with i dotted but the Turkish language treats I dotless and İ dotted \u0130 as distinct letters paired with distinct lower case letters ı dotless \u0131 and i dotted. So in order to correctly change the case of a letter, a program must know the language of the text.

toLowerCase string prototype function produces a string in which all of the upper case letters are replaced with their lower case equivalents, so 'VISA'.toLowercase() produces 'visa'. The toLocaleLowerCase string prototype function produces a string in which all of the upper case letters are replaced with their lower case equivalents using the local convention, so for programs in a Turkish environment, 'VISA'.toLocaleLowerCase() might produce 'vısa'.

These functions are aware of case:

In regexp pattern matching, the matching of letters is case sensitive. The i regexp flag makes the matching of letters case insensitive.

/v/.test('VISA')     // false
/v/i.test('VISA')    // true

case is used for a completely unrelated purpose in the switch statement.

case insensitive

Blah.

case sensitive

Blah.

catch reserved word

See try statement.

ceil

ceil Math function ceiling

The Math.ceil(number) function converts a number into an integer. If the number argument is already an integer, it simply returns the number. Otherwise, it returns the lowest integer that is greater than the number. If the number is less than 0 but greater than -1, the result is -0. The function could be implemented like this:

Math.ceil = function (number) {
    return -Math.floor(-number);
};

character

Blah.

charAt

charAt String prototype function

Blah.

charCodeAt

charCodeAt String prototype function

Blah.

circular definition

See definition circular.

class reserved word

closure

Blah.

code point

Blah.

code unit

Blah.

codePointAt

Blah.

codePointAt String prototype function

Blah.

Collator

Collator Intl function

Blah.

comment

A comment is text in a compilation unit that is ignored by the compiler. A comment can be used to document a program, giving information about its construction and operation. There are two forms of comment, the // comment and the /* block comment.

It is important to document programs to help a reader (perhaps future you) understand how the program works. It is even more important to keep comments uptodate. Incorrect comments are worse than no comments.

compareLocale

compareLocale String prototype function

Blah.

compilation unit

A program is delivered as one or more compilation units. In an HTML application, each <script> tag delivers one compilation unit. Scripts are compiled and executed immediately. The result of the execution could be to output a solution. More commonly, however, the result of execution is to create and modify objects in the global environment, setting up callback functions that will execute later in response to user actions and other events. For example, in a web browser, each compilation unit will be attaching event handlers to DOM nodes and installing global objects and functions that will provide services to the event handlers. The program does not stop when the compilation units have finished running. From the user’s perspective, that is when the program starts.

A compilation unit contains a sequence of zero or more statements. The statements are executed sequentially. After a statement has finished executing, the next statement is executed. After executing the last statement, the compilation unit's turn is finished, at which time another compilation unit might be exececuted, or an event might be fired.

A compilation unit executes in a global scope, so every variable created by the var statement or function statement will be global. There is a phenomenon called hoisting that can alter the sequential flow of the compilation unit. Hoisting affects the var statement and the function statement. Every global variable created by one compilation unit will be available to all subsequent compilation units.

In an HTML application, each on- event attribute delivers a deferred compilation unit. Each on- event attribute is compiled and executed when an event is dispatched. Use of on- event attributes is not recommended.

compiler

A compiler is a program that translates a source program into an executable form. In this language, the compiler can be accessed by the eval global function and the Function global function.

concat

concat Array prototype function

Blah.

concat String prototype function

Blah.

concatenation

Concatenation is an operation in which a new things is made by joining two or more other things.

conditional statement

A conditional statement alters the flow of a program, which normally executes from top to bottom, by selecting one path from two or more possibilities, deciding based on the value of an expression or the occurence of an exception.

const reserved word

constant

A constant is a name with a fixed value. Each of these names can be used as an operand, but they may not be used as an lvalue.

constructor

Generally, a constructer is any function that returns an object. But constructors is usually means a function that returns an object using prototypal inheritance using the new prefix operator.

constructor invocation

continuation

Blah.

continue reserved word

continue statement

Blah.

constructor

constructor function

Blah.

constructor Function prototype function

A constructor is a function that is used to create new objects. A constructor should always be invoked with the new prefix operator. If a constructor is invoked without the new prefix operator, then the this parameter will not be bound to a new object. A constructor has a prototype Function prototype object that is used as the prototype of the new object. See invocation.

copy

Blah.

copyWithin

copyWithin Array prototype function

Blah.

correspondence

The correspondence between the variables of a function and the parameters of an inner function.

function frick(n) {
    var result = 1;
    while (n > 1) {
        result *= n;
        n -= 1;
    }
    return result;
}

function frack(n) {
    return (function (result) {
        while (n > 1) {
            result *= n;
            n -= 1;
        }
        return result;
    }(1));
}

The functions frick and frack both compute the factorial function. They produce the same result, but frick declares a variable called result, and frack uses the result of an immediate function that has a parameter called result. This demonstrates the correspondence between variables and parameters.

Holds for expressions except for this and arguments. Renaming as that and them. Holds for statements except return, break, and continue, and var and function. Blah.

cos

cos Math function cosine

The Math.cos(radians) function, also known as cosine, takes an angle in radians and returns a number in the range -1...1.

function rotate(polygon, radians) {

// This function takes an array of points, and returns another array
// of points rotated around the origin.

    var cos = Math.cos(radians),
        sin = Math.sin(radians);

    return polygon.map(function (point) {
        return {
            x: point.x * cos - point.y * sin,
            y: point.x * sin + point.y * cos
        };
    });
}

This is an approximate implemention of Math.cos:

Math.cos = (function () {
    var half_pi = Math.PI / 2;
    return function cos(radians) {
        return Math.sin(radians + half_pi);
    };
}());

See Math function.

cr carriage return

See line terminator.

create

create Object function

Blah.

crlf carriage return linefeed

See line terminator.

CSS

See Cascading Style Sheets.

curly brace

See { left curly brace and } right curly brace.

curry

Blah.

function curry(func) {
    var args = Array.prototype.slice.apply(arguments, [1]);
    return function () {
        return func.apply(null, args.concat(Array.prototype.slice.apply(arguments)));
    };
}

function add(a, b) {
    return a + b;
}

var inc = curry(add, 1);

alert(inc(6));

D

data property

Blah.

DataView

DataView primordial function

Blah. Blah. Blah.

DataView prototype

Blah. Blah. Blah.

DataView prototype ArrayBuffer

DataView prototype function

DataView prototype number

date

Date primordial function

Blah. Blah. Blah.

Date prototype function

Blah.

DateTimeFormat

DateTimeFormat Intl function

Blah.

debugger reserved word

debugger statement

Blah.

decimal base 10

The decimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

Most of humanity represents its numbers in the decimal system.

decodeURI

decodeURI primordial function

Blah.

decodeURIComponent

decodeURIComponent primordial function

Blah.

default reserved word

See switch statement.

defensive programming

Blah.

defineProperties

defineProperties Object function

Blah.

defineProperty

defineProperty Object function

Blah.

definition circular

See circular definition.

degrees

Blah. See radians.

delete reserved word

delete prefix operator

Blah.

disruptive statement

Usually, after a statement completes its execution, the next statement executes. This is not the case with a disruptive statement. A disruptive statement alters the flow of a program, so the next statement is not executed. These are the disruptive statements:

divide

See / infix operator divide and /= assignment infix operator divide.

Also see remainder.

dividend

Blah.

divisor

Blah.

division

Blah.

do reserved word

do statement

Blah.

dunder

A property name that begins and ends with two _ underbar characters.

Example:

__pathetic__

E

e

The letter e or E can indicate the exponent part of a number literal.

E Math number e

Math.E contains an approximate value of e which is somewhere around 2.718281828459045. It is called Euler's number, and is the base of the natural logarithm.

It can be computed with an immediate function:

Math.E = (function () {
    var e = 2,
        f = 1,
        i;
    for (i = 2; i < 18; i += 1) {
        f /= i;
        e += f;
    }
    return e;
}());

Also see exp Math function exponential and log Math function natural logarithm.

E4X

The ECMAScript for XML (E4X) Specification [ECMA-357 Second Edition / December 2005] is a standard that extends ECMAScript with XML literals and XPath-like operators. It is not a part of ES3 or ES5. It is not implemented in most systems. The E4X extentions should be avoided because of their lack of general availability and acceptance.

Ecma International

Ecma International (fna European Computer Manufacturers Association) is the standards body that is responsible for the ECMAScript Programming Language Standard. It was founded in 1961 and is based in Geneva. See http://www.ecma-international.org/.

ECMAScript

Blah.

ecursion

Blah.

else reserved word

See if statement.

empty statement

The empty statement is a statement consisting of nothing but a ; semicolon. It does not do anything. Its principle use is to mask syntax errors. The empty statement should be avoided.

empty string

Blah.

encodeURI

encodeURI primordial function

Blah.

encodeURIComponent

encodeURIComponent primordial function

Blah.

endsWith

endsWith String prototype function

Blah.

entity

An entity in HTML is a character sequence that represents a single character. It is HTML's alternative to escapement as used in a string literal. An entity begins with & ampersand and ends with ; semicolon, and between them there may be a cryptic word or a number. JavaScript tolerates HTML entities in strings, but has no knowledge of them.

'&amp;'.length    // 5

entries

entries Array prototype function

Blah.

enum reserved word

enumeration

See keys object function and for in statement.

enumeration function

Blah.

enumeration object

An enumeration object is an object that is used to map names or mnemonics to codes in the form of numbers or other values. Programs often make use of codes or constant values, but it is generally bad to scatter them thoughout a program because that can make the program difficult to read and modify. So instead we can collect the codes and constants into an object, giving descriptive keys to each one. The descriptive keys help make the program self documenting, and gives us a single place to change in the program should they need to be changed.

In some languages, there is an enum statement or operator that provides such mapping. In this language, simply use an object.

epsilon

Epsilon is the smallest positive number that can be added to 1 giving a result that is larger than 1. Positive numbers that are smaller than epsilon will underflow when added to 1. The value for epsilon is approximately 2.220446049250313e-16. It can be computed with this immediate function:

var epsilon = (function () {
    var next, result;
    for (next = 1; 1 + next !== 1; next = next / 2) {
        result = next;
    }
    return result;
}());

Epsilon is a measure of the limits of the accuracy of number.

1 + epsilon    // 1.0000000000000002 (approximately)
2 + epsilon    // 2 (exactly)

error

Error primordial function

Blah.

ES2015 ES6

Blah. See ES6

ECMAScript Programming Language Standard, Third Edition [1999].

ES3

ECMAScript Programming Language Standard, Third Edition [1999].

ES4

There is no ES4.

ES5

ECMAScript Programming Language Standard, Fifth Edition [2009].

ES6

ECMAScript Programming Language Standard, Sixth Edition [2015].

escapement

Blah.

eteration

Blah.

eval

eval primordial function

Blah.

EvalError

EvalError primordial function

Blah.

event loop

Blah.

every

every Array prototype function

Blah.

evil

Evil is bad. Don't do evil things or use things for evil purposes.

exception

Blah. See try statement.

exec

exec RegExp prototype function

Blah.

exp

exp Math function exponential

The Math.exp(number) function returns e raised to the number power. This is an approximate implementation:

Math.exp = function exp(number) {
    number = +number;
    var fac = 1,
        i,
        result = 1 + number,
        xx = number;
    for (i = 2; i < 20; i += 1) {
        xx *= number;
        fac *= i;
        result += xx / fac;
    }
    return result;
};

Also see E Math number e.

exponentiation

See pow Math function raise to a power.

expression

An expression is a sequence of tokens that delivers a value. An expression can be one of:

A compound expression can be formed by combining one or more expressions with an operator. Expressions can be nested inside of other expressions. The whole expression produces a single value. The order in which the operators are evaluated depends on ( ) grouping and operator precedence.

When an expression provides a value to an operator, it is called an operand.

When an expression provides a value to a function invocation, it is called an argument.

When an expression occurs on the left side of an assignment infix operator, it is called an lvalue. When an expression occurs on the right side of an assignment infix operator, it is called a value, specifically it is the value to be stored in the lvalue.

An expression can produce a value that can control a statement:

expression statement

An expression can be used as a statement. Generally, the only expressions that make sense as statements are

The other forms of expressions are allowed, but most are useless, or even dangerous in that errors can be masked.

An expression statement should end with a ; semicolon.

alert('When my friends need some code who do they call?');
force = mass * velocity;
i += 1;    // add 1 and i and store the result in i
i + 1;     // add 1 and i and ignore the result
i;         // get the value of i and ignore it

export reserved word

extends reserved word

F

false reserved word

The false value is one of the two immutable boolean values. The false value is one of the falsy values.

The false value can be produced by a relational operator.

false literal

The false literal is a convenient way to access the false value.

var found = false;

false positive

Blah.

falsy

Every value is either truthy or falsy. These are the falsy values:

All other values, including empty objects and empty arrays, are truthy.

A falsy value can have consequences:

fill

fill Array prototype function

Blah.

filter

filter Array prototype function

Blah.

finally reserved word

See try statement.

find

find Array prototype function

Blah.

findIndex

findIndex Array prototype function

Blah.

Float32Array

Float32Array primordial function

Float32Array function

Float32Array number

Float32Array prototype

Float32Array prototype ArrayBuffer

Float32Array prototype function

Float32Array prototype number

Float32Array number

Float32Array string

Float64Array

Float64Array primordial function

Float64Array function

Float64Array number

Float64Array prototype

Float64Array prototype ArrayBuffer

Float64Array prototype function

Float64Array prototype number

Float64Array number

Float64Array string

floor

floor Math function

Blah.

for reserved word

for in statement

Blah.

for statement

Blah.

forEach

forEach Array prototype function

Blah.

Example:

from

from Array function

Blah.

fromCharCode

fromCharCode String function

Blah.

fromCodePoint

fromCodePoint String function

Blah.

free variable

Blah.

freeze

freeze Object function

Blah.

fromCharCode

fromCharCode String function

Blah.

function reserved word

Blah.

function *

There is a special form of function that returns an object instead of a function. Blah.

function body

Blah.

function invocation

Blah.

function literal

Blah.

Function primordial function

Blah.

Function prototype function

Blah.

Function prototype object

Blah.

function statement

Blah.

G

g

g regexp flag

get

See object and object literal.

getDate

getDate Date prototype function

Blah.

getFloat32

getFloat32 DataView prototype function

Blah.

getFloat64

getFloat64 DataView prototype function

Blah.

getFullYear

getFullYear Date prototype function

Blah.

getHours

getHours Date prototype function

Blah.

getInt16

getInt16 DataView prototype function

Blah.

getInt32

getInt32 DataView prototype function

Blah.

getInt8

getInt8 DataView prototype function

Blah.

getMilliseconds

getMilliseconds Date prototype function

Blah.

getMinutes

getMinutes Date prototype function

Blah.

getMonth

getMonth Date prototype function

Blah.

getOwnProperties

getOwnProperties Object function

Blah.

getOwnPropertyDescriptor

getOwnPropertyDescriptor Object function

Blah.

getPrototypeOf

getPrototypeOf Object function

Blah.

getSeconds

getSeconds Date prototype function

Blah.

getTime

getTime Date prototype function

Blah.

getUInt16

getUInt16 DataView prototype function

Blah.

getUInt32

getUInt32 DataView prototype function

Blah.

getUInt8

getUInt8 DataView prototype function

Blah.

getUTCDate

getUTCDate Date prototype function

Blah.

getUTCFullYear

getUTCFullYear Date prototype function

Blah.

getUTCHours

getUTCHours Date prototype function

Blah.

getUTCMilliseconds

getUTCMilliseconds Date prototype function

Blah.

getUTCMinutes

getUTCMinutes Date prototype function

Blah.

getUTCMonth

getUTCMonth Date prototype function

Blah.

getYear

getYear Date prototype function

Blah.

global

A program runs in a context, which is sometimes called the global context or the global object. The global context is like other objects in that it is a container of key/value pairs. The keys are the names of global variables, and the values are the values of those variables. The global context is initialized with global functions, the global objects JSON and Math, and the global variables Infinity, NaN, and undefined before the first compilation unit gets its turn.

Some environments, such as web browsers, can have many global objects, one for each frame or window. The browser adds its own variables to the global context, including document, navigator, and window.

Global variables can be created in a compilation unit with the var statement or the function statement. Within a function body, if a

Good Parts

Blah.

grammar

Blah.

grouping parentheses

See ( ) grouping.

H

hasOwnProperty

hasOwnProperty Object prototype function

Blah.

hexadecimal base 16

The hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. The lower case letters a, b, c, d, e, and f can also be used.

Unlike the decimal system which uses base 10, the hexadecimal system uses base 16, where each hexadecimal digit represents exactly 4 bits. In olden times, programming was closer to the machine so a format that was trivially convertable to binary was highly desirable. Today, hexadecimal is mainly used to encode a code value in a Unicode escape sequence and to encode colors in CSS.

Also see number literal, parseInt primordial function, and toString Number prototype function.

higher order function

Blah.

hoisting

Blah.

host object

A host object is an object that is not a ECMAScript object, but that can be interacted with by ECMAScript programs. It might be provided by the host operating system. The ECMAScript standard does not require that there be any host objects, but implementations are allowed to provide them. Host objects, because they are not JavaScript objects, might act funny. You know, funny. Also see native object.

HTML Hypertext Markup Language

Blah.

hyphen

See - minus sign.

I

i

i regexp flag

identifier

See name.

identifier character

See name.

identifier escapement

if reserved word

if statement

Blah.

ignoreCase

ignoreCase regexp boolean

Blah.

immediate function

An immediate function is a function that will be invoked immediately. This is done to allow inner functions to have continuing access to variables created by the immediate function. The entire immediate function and its invocation should be wrapped in parentheses to show reader that the function is immediate. The wrapping in parens is syntactically required in the case where function would be the first token in the statement.

Example:

var wordify = (function () {

// The wordify function converts an integer into English.
// It makes use of three array literals to provide most of the vocabulary.

// It is returned from an immediate function in order to hide the arrays
// units, tens, and illions.

    var units = [
            '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
            'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen',
            'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen',
            'nineteen'
        ],
        tens = [
            '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
            'seventy', 'eighty', 'ninety'
        ],
        illions = [
            '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion'
        ];

// The result of the execution of the immediate function is the wordify
// function.

    return function (n) {
        var result = '', i, clump, hundred, ten, unit, word, illion;

// Force the input to be a non-negative integer.

        n = Math.floor(Math.abs(n));

// If it is zero, we are done.

        if (!n) {
            return 'zero';
        }

// For each illion, extract the bottom clump of 3 digits.

        for (i = 0; i < illions.length; i += 1) {
            clump = n % 1000;
            if (clump) {

// If the clump isn't all zeros, then work out the hundred and the unit parts.

                hundred = Math.floor(clump / 100);
                unit = clump - (hundred * 100);
                illion = illions[i];

// The units array contains 20 rather than 100 entries. If an entry is
// undefined, then split the unit into two parts. For example, unit[21] is
// undefined, so we will combine tens[2] and unit[1] to make 'twenty one'.

                word = units[unit];
                if (typeof word !== 'string') {
                    ten = Math.floor(unit / 10);
                    unit = unit % 10;
                    word = units[unit];
                    if (word) {
                        word = ' ' + word;
                    }
                    word = tens[ten] + word;
                }

// If there is a hundred part, then add that to the word.

                if (hundred) {
                    if (word) {
                        word = ' ' + word;
                    }
                    word = units[hundred] + ' hundred' + word;
                }

// Add the current illion's contributions to the result.

                if (result) {
                    result = ' ' + result;
                }
                if (illion) {
                    word += ' ' + illion;
                }
                result = word + result;
            }

// Discard the bottom three digits and go again if there are any left.

            n = Math.floor(n / 1000);
            if (n === 0) {
                break;
            }
        }
        return result;
    };

// The immediate function and its invocation were wrapped in parens to
// help the reader understand that the immediate function's result is
// being stored.

}());

immutable

Blah.

implements reserved word

implied global

A variable that is not explicitly declared is assumed to be global. This is a hazard. The use of global variables can compromise the reliability of a program. The implied declaration of global variables masks likely errors. It is wise to avoid global variables, and to defend against implied global variables. Always use the var statement to explicitly declare a variable.

function tragic(array) {

// Calling this function may cause the caller to fail if the
// caller uses a variable named i.

    sum = 0;                                   // sum is global
    for (i = 0; i < array.length; i += 1) {    // i is  global
        sum += array[i];
    }
    return sum;
}

import reserved word

in reserved word

Also see for in statement.

in infix operator

Blah.

includes

includes Array prototype function

Blah.

includes String prototype function

Blah.

indexOf

indexOf Array prototype function

Blah.

Example:

function make_sealer() {

// make_sealer is a function that returns a pair of functions. One, the sealer,
// takes a value and returns a locked box. The other, the unsealer, takes a
// locked box and returns the original value. A sealer and unsealer work like
// a public key/private key pair, making it possible for two parties to pass
// a value through an untrusted third party. The third party cannot see the
// contents of the locked box, nor can it tamper with the contents. To unlock a
// locked box, you must hold the locked box and the unsealer that is the mate
// of the sealer that created the locked box.

// The boxes and values are kept in a pair of arrays. We use objects as keys
// because that makes a brute force key guessing attack impossible. Using strings
// as keys, the best we could hope to do is make a guessing attack extremely
// unlikely. It would be tempting to use an object to hold the pairs, where the
// boxes are the keys, but objects can only use strings as keys, and boxes must
// be objects. So instead we have two parallel arrays, and use the indexOf method
// to locate the keys and values.

    var boxes = [],
        values = [];

    return {
        sealer: function (value) {

// Seal the value, returning a locked box object. The box object will be empty.
// It can be given to the matching unsealer to redeem the value.

// If the value has already been boxed, return the old box.

            var i = values.indexOf(value), box;
            if (i >= 0) {
                return boxes[i];
            }

// Make a new box. Append it to the boxes array, and append the value to
// the values array.

            i = boxes.length;
            box = {};
            boxes[i] = box;
            values[i] = value;
            return box;
        },
        unsealer: function (box) {

// Search for the box. If it is found, return the corresponding value.
// If it is not found, return undefined.

            return values[boxes.indexOf(box)];
        }
    };
}

indexOf String prototype function

Blah.

The indexOf method could be implemented like this:

String.prototype.indexOf = (function () {

// The indexOf method returns the position at which a search_string first
// occurs within a search string, or -1 if it cannot be found. An optional
// position parameter (default 0) determines where to start the search.
// The following implements a simplified version of the Boyer Moore algorithm.

// These are memoized variables. They will retain their values between
// invocations, speeding up results when doing multiple searches on the same
// search_string.

    var delta,                  // The delta table that allows for skipping
        lengt,                  // The length of the search string - 1
        length,                 // The length of the search string
        previous_search_string = '';

// And here is the indexOf function itself.

    return function indexOf(search_string, position) {

// Normalize the inputs. Convert this and the search_string to strings just in
// case they are not already strings. Force position to an integer between 0
// and the length of this.

        var h,                  // Past the last possible position
            j,                  // The loop variable
            s = String(this);   // this converted to a string

        search_string = String(search_string);
        position = Math.min(
            Math.max(
                (position === undefined)
                    ? 0
                    : Math.floor(position),
                0
            ),
            s.length
        );

// If the search_string is the empty string, then we are done.

        if (search_string === '') {
            return position;
        }

// If the search_string is the same as the previous_search_string, then we
// can skip the step of building the delta table. The delta table tells us
// how many characters we can skip if there is a mismatch. Typically, the
// number of characters we can skip is equal to the length of the search_string,
// so the longer the search_string, the faster the search.

        if (search_string !== previous_search_string) {
            length = search_string.length;
            lengt = length - 1;
            previous_search_string = search_string;
            delta = {};
            for (j = 0; j <= lengt; j += 1) {
                delta[search_string.charAt(j)] = lengt - j;
            }
        }

// h is the position after the last possible match.
// The search continues while position is less than h.

        h = s.length - length;
        while (position < h) {

// In the worst case, we will compare the search_string with every position
// in this string. But first, compare the last character in the search_string.
// If that shows a total mismatch, then we don't need to look at any other
// characters within the position, so advance by the length of the
// search_string.

            j = delta[s.charAt(position + lengt)];
            if (j === undefined) {
                position += length;

// If we found any character but the last in the search_string, then we can
// advance a smaller amount.

            } else if (j) {
                position += j;

// The last character matched, so try matching the remainder. If that fails,
// advance a single character. If it succeeds, then we return the position.

            } else {
                for (;;) {
                    if (s.charAt(position + j) !== search_string.charAt(j)) {
                        position += 1;
                        break;
                    }
                    j += 1;
                    if (j >= lengt) {
                        return position;
                    }
                }
            }
        }

// If we reach the end without success, then return -1.

        return -1;
    };
}());

infinite loop

An infinite loop is a loop that never terminates. This is a bad thing because the turn never ends, freezing the program. The simplest infinite loop is

for (;;) {}    // This is not a bug. It is much worse.

infinity

Infinity literal

The infinity value is a number that represents all numbers that are larger than MAX_VALUE Number number. It is available as the Infinity primordial variable, and as POSITIVE_INFINITY Number number. Negative infinity is available as -Infinity and as NEGATIVE_INFINITY Number number.

Infinity + Infinity // Infinity Infinity - Infinity // NaN Infinity * Infinity // Infinity Infinity / Infinity // NaN isFinite(Infinity) // false

infix operator

An infix operator is an operator that takes two operands. The infix operator is placed between its two operands.

Also see operator precedence and assignment infix operator.

inheritance

Blah.

inheritance chain

The inheritance chain (or prototype chain) is the linkage through which an object can delegate or inherit properties from another object. When an object is created, it can be chained to another object. If an attempt is made to get the value of a property of the object, and if the object does not have an own property with that name, then the chain is followed to a second object. If that second object has the named own property, then that property's value is delivered as if it had come from the first object. However, if the second object does not have the named own property, then its chain is followed, and so on. The chain is not used to set a property to an object. Assignment is always to an own property of the first object.

The default inheritance chain for an object literal is Object.prototype. There are two ways to make objects with a different chain. The first is to use the create Object function. The second is to use the new prefix operator on a constructor function to produce an object that is chained to the prototype Function prototype object. Once an object is made, it cannot be chained to a different object. See the getPrototypeOf Object function. inherited property

An inherited property of an object is a property that is not present in the object itself, but is instead inherited through the object's inheritance chain.

instanceof reserved word

instanceof infix operator

Blah.

Int16Array

Int16Array primordial function

Int16Array function

Int16Array number

Int16Array prototype

Int16Array prototype ArrayBuffer

Int16Array prototype function

Int16Array prototype number

Int16Array number

Int16Array string

Int32Array

Int32Array primordial function

Int32Array function

Int32Array number

Int32Array prototype

Int32Array prototype ArrayBuffer

Int32Array prototype function

Int32Array prototype number

Int32Array number

Int32Array string

Int8Array

Int8Array primordial function

Int8Array function

Int8Array number

Int8Array prototype

Int8Array prototype ArrayBuffer

Int8Array prototype function

Int8Array prototype number

Int8Array number

Int8Array string

Int8ClampedArray

Int8ClampedArray primordial function

Int8ClampedArray function

Int8ClampedArray number

Int8ClampedArray prototype

Int8ClampedArray prototype ArrayBuffer

Int8ClampedArray prototype function

Int8ClampedArray prototype number

Int8ClampedArray number

Int8ClampedArray string

integer

An integer is a number without a fractional part. Integers are sometimes known as whole numbers, counting numbers, and natural numbers. JavaScript has a single number type that includes all numeric values, including integers. JavaScript does not have a separate integer type.

Integer arithmetic in JavaScript is exact so long as the operands and results fall within the range -9007199254740992...9007199254740992. Integers outside of that domain may be represented inexactly. For example, the integer 9007199254740993 is represented as the same number as 9007199254740992.

// Compute the largest safe integer.

var max_int = (function () {
    var integer = 1;
    while (integer + 1 !== integer) {
        integer = integer * 2;
    }
    return integer;
}());

The / infix operator divide can produce a non-integer result even if both of its operands are integers. For example, 1 / 2 produces 0.5, a non-integer result.

These functions can be used to convert non-integers to integers:

JavaScript is lacking a trunc Math function truncate that rounds toward zero. Such a function would round down for positive numbers and round up for negative numbers.

function trunc(number) {
    return Math[
        (number >= 0)
            ? 'floor'
            : 'ceil'
    ](number);
}

A bitwise operator uses integer operands but over a much smaller range, -2147483648 to 2147483647.

interface reserved word

Intl

Intl function

Intl primordial object

invocation

There are four forms of function invocation:

Each form has distinctive syntax. They vary in what gets bound to the implicit this parameter. It is because of these patterns that

var funky = object.method; funky(); // Function form

may have a different result than

object.method(); // Method form

function

The function form takes a function literal, a variable, or a parameter. The this parameter will be bound to undefined.

funky()

(function () {
    return this;
}())                 // returns undefined

The method form takes an expression in which the outermost operator is . suffix operator select or [ ] suffix operator subscript. The this parameter will be bound of the value that precedes the suffix operator. The late binding of the this parameter makes it possible to have single function act as a method of many objects, either by inheritance or by assigning the function to many objects.

object.method()

object[variable]()

Only use the method form if you intend for the called function to have access to the object. constructor

The constructor form uses the new prefix operator. The this parameter will be bound to a new object that inherits from the function's prototype property.

new Monster() // this is bound to Object.create(Monster.prototype)

apply

The apply form invokes the function by invoking the function's apply or call method. The first parameter is the value that the this parameter will be bound to.

funky.apply(null)

isArray

isArray Array function

blah.

isExtensible

isExtensible Object function

Blah.

isFinite

isFinite primordial function

Blah.

isFrozen

isFrozen Object function

Blah.

isNaN

isNaN primordial function

Blah.

isPrototypeOf

isPrototypeOf Object prototype function

Blah.

isSealed

isSealed Object function

Blah.

isView

isView ArrayBuffer function

Blah.

iteration

Iteration (or repetition)

loop statement

recursion

enumeration function

J

Java

Blah.

JavaScript

Blah.

join

join Array prototype function

Blah.

JScript

Blah.

JSLint

Blah. http://www.JSLint.com/

JSON

The world's best loved data interchange format.

Blah. http://www.JSON.org/

JSON function

JSON primordial object

Blah.

K

key

See object.

key string

Blah. See object.

keys

keys Object function

Blah.

L

label

A label is a prefix before a statement. A label is a name followed by a : colon. The label can then be used to with a break statement to break out of a particular loop statement or switch statement, or with a continue statement to begin the next iteration of a particular loop. Labels are rarely necessary, but are useful in situations where there are nested loops and when it is necessary to break out of the inner loop. This can happen when searching.

function string(current, next) {

// Produce a polished JSON string from a text. This function takes two
// functions, current and next, which return the current character of
// the text and the next character. Both return empty string if there
// are no more characters.

    var i, result = '', hex, hhhh;

// The first character must be '"'.

    if (current() == '"') {

// Loop while there are still more characters. This loop has an outer label.

outer:  while (next()) {

// If we find the closing '"', then return the result.

            if (current() == '"') {
                next();
                return result;
            }

// If we find a backslash, then look for an escape sequence.

            if (current() == '\\') {
                switch (next()) {
                case 'b':
                    result += '\b';
                    break;
                case 'f':
                    result += '\f';
                    break;
                case 'n':
                    result += '\n';
                    break;
                case 'r':
                    result += '\r';
                    break;
                case 't':
                    result += '\t';
                    break;

// If we found \u, then take 4 hexadecimal digits.

                case 'u':
                    hhhh = 0;
                    for (i = 0; i < 4; i += 1) {
                        hhhh = hhhh * 16 + parseInt(next(), 16);

// If the hex value is not finite (most likely NaN), then the text was not a
// well formed JSON text and must be rejected. Break out of the outer loop.

                        if (!isFinite(hhhh)) {
                            break outer;
                        }
                    }
                    result += String.fromCharCode(hhhh);
                    break;
                default:
                    result += current();
                }
            } else {
                result += current();
            }
        }
    }

// We can get here if the string is not opened or closed correctly or if
// a \uhhhh sequence is badly formed.

    throw new SyntaxError("Bad string");
}

lastIndexOf

lastIndexOf Array prototype function

Blah.

lastIndexOf String prototype function

Blah.

String.prototype.lastIndexOf = (function () {

// The lastIndexOf method returns the position at which a search_string last
// occurs within a search string, or -1 if it cannot be found. An optional
// position parameter (default this.length) determines a point within the point
// to not search.

// The following implements a simplified version of the Boyer Moore algorithm.

// These are memoized variables. They will retain their values between
// invocations, speeding up results when doing multiple searches on the same
// search_string.

    var delta,                  // The delta table that allows for skipping
        lengt,                  // The length of the search string - 1
        length,                 // The length of the search string
        previous_search_string = '';

// And here is the indexOf function itself.

    return function lastIndexOf(search_string, position) {

// Normalize the inputs. Convert this and the search_string to strings just in
// case they are not already strings. Force position to an integer between 0
// and the length of this.

        var j,                  // The loop variable
            s = String(this);   // this converted to a string

        search_string = String(search_string);
        position = Math.min(Math.max(position === undefined ?
            s.length : Math.floor(position), 0), s.length);

// If the search_string is the empty string, then we are done.

        if (search_string === '') {
            return position;
        }

// If the search_string is the same as the previous_search_string, then we
// can skip the step of building the delta table. The delta table tells us
// how many characters we can skip if there is a mismatch. Typically, the
// number of characters we can skip is equal to the length of the search_string,
// so the longer the search_string, the faster the result.

        if (search_string !== previous_search_string) {
            length = search_string.length;
            lengt = length - 1;
            previous_search_string = search_string;
            delta = {};
            for (j = lengt; j >= 0; j -= 1) {
                delta[search_string.charAt(j)] = j;
            }
        }

// We start searching at the position, which by default is the end of this.
// We continue to search as long as the number of characters remaining is at
// least as long as the search_string.

        while (position > length) {

// In the worst case, we will compare the search_string with every position
// in this string. First, compare the first character in the search_string.
// If that shows a total mismatch, then we don't need to look at any other
// characters within the position, so advance by the length of the
// search_string.

            j = delta[s.charAt(position - length)];
            if (j === undefined) {
                position -= length;

// If we found any character but the last in the search_string, then we can
// advance a smaller amount.

            } else if (j) {
                position -= j;

// The last character matched, so try matching the remainder. If that fails,
// advance a single character. If it succeeds, then we return the position.

            } else {
                j = 1;
                while (true) {
                    if (s.charAt(position + j - lengt) !== search_string.charAt(j)) {
                        position -= 1;
                        break;
                    }
                    j += 1;
                    if (j >= length) {
                        return position;
                    }
                }
            }
        }

// If we reach the beginning without success, then return -1.

        return -1;
    };
}());

lastLine

lastLine RegExp prototype number

Blah.

Law of Turns

See event loop.

length

length Array prototype number

Blah.

length ArrayBuffer prototype number

Blah.

length String prototype number

Blah.

let reserved word

let statement

Blah.

lf linefeed

See line terminator.

line terminator

A line terminator is character or character sequence that indicates the end of a line. The most popular line terminators are cr carriage return and lf linefeed or both. Avoid ls line separator and ps paragraph separator.

Unicode escape sequence alt line terminator name
\u000A \n lf linefeed
\u000D \r cr carriage return
\\u000D\u000A \r\n crlf carriage return linefeed
\u2028 ls line separator
\u2029 ps paragraph separator

literal

A literal is a sequence of one or more tokens that creates a value within a program.

infinity, NaN not a number, and undefined are not formally literals. Each is a primordial variable.

LN10

LN10 Math number natural logarithm of 10

Math.LN10 contains a number that is approximately 2.302585092994046. It could be implemented as

Math.LN10 = Math.log(10);

LN10 can be used to raise 10 to a power.

function exp10(x) {
    return Math.exp(Math.LN10 * x);
}

Of course, exp10 is better written as

function exp10(x) {
    return Math.pow(10, x);
}

LN2

LN2 Math number natural logarithm of 2

Math.LN2 contains a number that is approximately 0.6931471805599453. It could be implemented as

Math.LN2 = Math.log(2);

LN2 can be used to raise 2 to a power.

function exp2(x) {
    return Math.exp(Math.LN2 * x);
}

Of course, exp2 is better written as

function exp2(x) {
    return Math.pow(2, x);
}

localeCompare

localeCompare String prototype function

Blah. See case .

log

log Math function natural logarithm

The Math.log(x) function returns the natural logarithm of x.

LOG10E

LOG10E Math number base 10 logarithm of e

Math.LOG10E is the base 10 logarithm of e. It is approximately 0.4342944819032518.

It can be used to implement a log10 function.

function log10(x) {
    return Math.LOG10E * Math.log(x);
}

LOG2E

LOG2E Math number base 2 logarithm of e

Math.LOG2E is the base 2 logarithm of e. It is approximately 1.4426950408889634.

It can be used to implement a log2 function.

function log2(x) {
    return Math.LOG2E * Math.log(x);
}

loop statement

There are three loop statements.

Loops can also be implemented with tail recursion.

lower case

See case .

ls line separator

See line terminator.

lvalue

An lvalue (or left value) is an expression on the left side of an assignment infix operator, or on the left side of an assignment suffix operator, or on the right side of an assignment prefix operator. The lvalue specifies where the value is to be stored. An lvalue is more restricted than a general expression because not all expressions describe a place where a value can be stored. For example, a value cannot be stored in a literal, and a value cannot be stored in a subtraction. An lvalue must be one of these:

An lvalue must be mutible.

M

m

m regexp flag

map

map Array prototype function

Blah.

function expand_shorthand(hand) {
    return hand.map(function (value) {
        return {
            rank: value.slice(0, -1),
            suit: value.slice(-1)
        };
    });
});

var hand = expand_shorthand(['AH', 'KH', 'QH', 'JH', '10H']);
// hand is [
//     {suit: 'H', rank: 'A'},
//     {suit: 'H', rank: 'K'},
//     {suit: 'H', rank: 'Q'},
//     {suit: 'H', rank: 'J'},
//     {suit: 'H', rank: '10'}
// ]

Map primordial function

Map prototype

Map prototype function

match

match String prototype function

Blah.

Math

Math function

The standard does not require implementations to compute the most accurate result from these functions. Implementors are allowed to trade off accuracy for speed or other considerations. Blah.

Most of the functions can take one parameter. These are the results of those functions for some particular arguments:

functionNaN-00-InfinityInfinity
absNaN00InfinityInfinity
acosNaNMath.PI / 2Math.PI / 2NaNNaN
asinNaN-00NaNNaN
atanNaN-00-Math.PI / 2Math.PI / 2
ceilNaN-00-InfinityInfinity
cosNaN11NaNNaN
expNaN110Infinity
floorNaN-00-InfinityInfinity
logNaN-Infinity-InfinityNaNInfinity
maxNaN-00-InfinityInfinity
minNaN-00-InfinityInfinity
roundNaN-00-InfinityInfinity
sinNaN-00NaNNaN
sqrtNaN-00NaNInfinity
tanNaN-00NaNNaN

Math.max(...) and Math.min(...) can take many arguments. The table shows the case where there is one argument.

Math.atan2(y, x) and Math.pow(x, y) each take two arguments. Math.random() takes no arguments.

Math primordial object

Blah.

Math number

The Math primordial object is the container for these numeric properties:

max

max Math function maximum

The Math.max(...) function returns the largest number from its arguments. It can take a variable number of arguments. If there are no arguments, it returns -Infinity. If there is one argument, it returns the numeric value of that argument. Otherwise, it compares each of the arguments and returns the greatest. If any of the arguments is NaN not a number or converts to NaN not a number, then the result is NaN not a number. Unlike the > infix operator, Math.max(...) sees -0 as being less than 0 (see zero).

It could be implemented like this:

Math.max = function () {
    var i, length = arguments.length, result = -Infinity, value;
    for (i = 0; i < length; i += 1) {
        value = +arguments[i];
        if (isNaN(value)) {
            return NaN;
        }
        if (value > result ||
                (value === 0 && result === 0 && 1 / value > 0)) {
            result = value;
        }
    }
    return result;
};

Math.max(25, 52)           // 52
Math.max(-1, 0.1, -0.1)    // 0.1
Math.max('2', '10')        // 10

Math.max(...[40, 8, Math.PI, 1000, 1])    // 1000

MAX_VALUE

MAX_VALUE Number number

Number.MAX_VALUE contains the largest positive representable number. It is approximately equal to 1.7976931348623157e+308. A result which is larger than MAX_VALUE is represented as Infinity. Surprisingly, Number.MAX_VALUE + x where x is a non-negative number in most cases does not produce Infinity. If x is less than approximately 9.979201547673598e+291 then the result of the addition is MAX_VALUE and not Infinity. As a result, even given infinite time, this loop will never break:

var x;
for (x = Number.MAX_VALUE; x !== Infinity; x += 9.979201547673598e+291) {
    x += 1;
}

member

Also known as property. See object.

memoization

Blah.

function memoizer(memo, formula) {
    var recur = function (n) {
        var result = memo[n];
        if (typeof result !== 'number') {
            result = formula(recur, n);
            memo[n] = result;
        }
        return result;
    };
    return recur;
};

var factorial = memoizer([1, 1], function (recur, n) {
    return n * recur(n - 1);
});

var fibonacci = memoizer([0, 1], function (recur, n) {
    return recur(n - 1) + recur(n - 2);
});

method

A method is property whose value is a function . A method can get access to the object with the this parameter. See invocation.

All values except null and undefined can have methods.

method chaining

When a function returns this .

See cascade.

method invocation

Blah.

min

min Math function minimum

The Math.min(...) function returns the smallest number from its arguments. It can take a variable number of arguments. If there are no arguments, it returns Infinity. If there is one arguments, it returns the numeric value of that argument. Otherwise, it compares each of the arguments and returns the lowest. If any of the arguments is NaN not a number or converts to NaN not a number, then the result is NaN not a number. Unlike the < infix operator, Math.min(...) sees -0 as being less than 0 (see zero). It could be implemented like this:

Math.min = function () {
    var i, length = arguments.length, result = Infinity, value;
    for (i = 0; i < length; i += 1) {
        value = +arguments[i];
        if (isNaN(value)) {
            return NaN;
        }
        if (value < result ||
                (value === 0 && result === 0 && 1 / value < 0)) {
            result = value;
        }
    }
    return result;
};

Math.min(25, 52)           // 25
Math.min(-1, 0.1, -0.1)    // -1
Math.min('2', '10')        // 2

Math.min(...[40, 8, Math.PI, 1000, 1])    // 1

minification

Blah.

minus sign

See - minus sign.

MIN_VALUE

MIN_VALUE Number number

Number.MIN_VALUE is the smallest positive number that can be represented. It is approximately equal to 5e-324. Dividing this value by 2 produces 0.

modulo

Blah.

See % infix operator remainder.

monad

Blah.

monkey patching

Blah.

multiline

multiline regexp boolean

Blah.

multiply

See * infix operator multiply.

mutabile

Blah.

N

name

A name is a token that typically resembles a word or a sequence of words. The first character of a name must be one of these:

The first character is followed by zero or more additional characters, each of which must be one of these:

A name token can be used as

If a name token is a reserved word then it cannot be used as

Any character in a name can be replaced with a Unicode escape sequence without changing the meaning, so cat and \u0063\u0061\u0074 are the same name.

var \u0063\u0061\u0074 = {\u0063\u0061\u0074: '\u0063\u0061\u0074'};
alert(cat.cat === 'cat');       // true
alert(cat['cat'] === 'cat');    // true

This was intended to make it easier to work with names representing foreign words, but it has little practical use. It is used mainly by evil doers as a way of evading security filters. It is generally safest to stick with the ASCII set.

Names are case sensitive, so cat and Cat and CAT are three different names. It is recommended that all names start with a lowercase character, with the exception that a constructor function should start with an Uppercase Letter, and a global variable should be all UPPER_CASE.

A name cannot contain a whitespace character, but sometimes a name should incorporate two or more words. There are two conventions for doing this. One is to use _ underbar in place of the whitespace.

truth_or_consequences

The other is to use camelCase, where the first letter of each word is capitalized.

truthOrConsequences

NaN not a number

There is a special number value called NaN not a number, which stands for Not a Number, despite the fact that

typeof NaN            // 'number'

NaN not a number is a falsy value. NaN not a number is produced by

0 / 0                 // NaN
Infinity - Infinity   // NaN
Infinity * 0          // NaN
Infinity / Infinity   // NaN
Infinity % 1          // NaN
1 % 0                 // NaN
+"oops"               // NaN
Number("oops")        // NaN
parseFloat("oops")    // NaN
parseInt("oops")      // NaN
1 + NaN               // NaN
1 + undefined         // NaN
0 * NaN               // NaN

Generally, any arithmetic operation with NaN not a number or undefined as an input will have NaN not a number as an output. If a sequence of computations produces NaN not a number, then there must have been at least one bad input or at least one bad operation. No clues are provided as to what went wrong. In bitwise operations, NaN not a number is treated as 0.

There are many techniques for detecting NaN not a number, but none of them are pleasant. The most likely test,

x === NaN    // false, even when x is NaN!

fails because NaN === NaN produces false . It is possible to use

x !== x      // true only if x is NaN

to test for NaN not a number because only NaN not a number is not equal to itself, but it looks mathematically ridiculous, and one hopes for a better future in which logic and good engineering are highly valued when this must fail. Another approach is to use the isNaN primordial function. Unfortunately, it can produce a false positive if an operand is a type other than number, so if it is possible that the operand is a string, then it should be guarded with the typeof prefix operator.

var x = 'not a number';
isNaN(x)                              // true
typeof x === 'number' && isNaN(x)     // false

String(x === 'NaN') has only one false positive, the case where x is the string 'NaN'. So,

String(x) === 'NaN' && x !== 'NaN'

There are many of ways to test for NaN not a number, and they are all absurd.

NaN literal

The literal symbol for NaN not a number is NaN not a number. NaN not a number is not actually a literal. It is a primordial variable that holds a NaN not a number value.

Blah.

NaN Number number

Number.NaN contains the NaN not a number value.

native object

Any object that is created in the language is called a native object. Also see host object.

negation

See - prefix operator negate.

NEGATIVE_INFINITY

NEGATIVE_INFINITY Number number

Number.NEGATIVE_INFINITY contains the -Infinity value.

Netscape

Blah.

new reserved word

new prefix operator

The new operator is used with a function invocation. It treats the function as a constructor, where the constructor fashions a new object that inherits from the constructor's prototype property. If new were a function rather than an operator, it could be implemented like this:

function new(func, arguments) {

// Create a new object that inherits from the constructor's prototype.
// func is a constructor function.
// arguments is an array of arguments that
//     are used to invoke the constructor.

    var that = Object.create(func.prototype),

// Invoke the constructor, binding –this- to the new object.

        other = func.apply(that, arguments);

// If its return value is not an object, substitute the new object.

    return (typeof other === 'object' && other) || that;
}

normalize

normalize String prototype function

Blah.

now

now Date function MISSING LINK

Blah.

null reserved word

Blah.

null literal

Blah.

number

There is a single type for representing number values. It is based on the 64 bit format (double-precision) of the IEEE 754 Standard for Binary Floating-Point Arithmetic.

The language’s numbers are only an approximation of real numbers, so the associativity of addition or multiplication should not be assumed, nor should the distributivity of multiplication and addition. For example:

var a = 0.01,
    b = 0.02,
    c = 0.03;
alert((a + b) + c === a + (b + c));    // false

a = 2;
b = epsilon;
c = epsilon;
alert((a + b) + c === a + (b + c));    // false

Arithmetic operations on approximate values can accumulate noise, and the order of operations can have an impact on the quality of the results. A particular problem is that binary floating point cannot exactly represent decimal fractions, which is a shame because virtually all financial transactions on this planet are conducted using the decimal system.

Fortunately, integers (whole numbers) can be accurately represented as long as the values do not exceed 9007199254740992 (around 9 quadrillion). Sometimes better results can be obtained by scaling real values into integers before computation. For example, dollar values can be converted to whole cents by multiplying by 100. Whole cents can be handled accurately as integers. See integer.

A number value acts as an immutable object. A number value has methods that it inherits from Number.protoype (see Number prototype function).

Using the typeof prefix operator with a number value always produces the string 'number', even when the number is one of the non finite values NaN not a number, Infinity, and -Infinity.

Number primordial function

The primordial function Number can produce number values.

Blah.

number literal

A number literal is used to include a number value in a program. There are two forms of number literal: decimal and hexadecimal.

A decimal number literal is a token containing up to three optional parts.

All parts are optional., but it is recommended that the whole part always be included. If the exponent part is included, then at least one of the other parts must preceed it. If the whole part is omitted, then the fraction part must be included and must contain at least one digit. The exponent part multiplies the value of the preceding parts by Math.pow(10, exponent). These all represent the same number:

.01024e4  1.024e+3  10.24E2  102.4E+1  1024.e0  1024.00  1024  10240e-1

A hexadecimal number literal is a token containing two required parts.

The hexadecimal digits in a hexadecimal number literal are evaluated in base 16, so 0x0400 is the same number as 1024. A hexadecimal number literal produces an integer value.

A number literal does not include a sign, but a number literal can be preceded with the - prefix operator negate to produce a negative value.

A number literal cannot be immediately followed by a name. At least one whitespace character must separate them.

Number prototype function

Blah.

Number number

The Number primordial function is also the container of a set of constants.

Only Number.MAX_VALUE and Number.MIN_VALUE are useful. The other three are redundant.

NumberFormat

NumberFormat Intl function

Blah.

O

object

An object (or native object) is an unordered container of properties. Each property has a key, which is a string. Keys are unique within an object. A property can have any value of any type. Properties are normally accessed with the . suffix operator select and [ ] suffix operator subscript.

The object is the fundamental data structure. The object is the base type for array, date, function , and regexp. Objects are used as containers for clustering collections of data and functions into convenient units. When a function is stored in an object, it is called a method. Methods can provide functionality and protect the integrity of their objects. Objects are used as records or collections of data, and can be nested to form more complicated data structures.

A reference to an object may be stored in a variable, stored in an object as a property, passed as as an argument to a function, and returned as a return value from a function. None of these operations make a copy of an object. Objects are always passed by reference. The === infix operator equal will produce true when both of its operands are references to the same object.

var a = {booga: true};
var b = {booga: true};
alert(a === b);    // false
b = a;
alert(a === b);    // true
a.booga = false;
alert(b.booga);    // false

An object can be made with the create Object function.

The typeof prefix operator returns 'object' when its operand is an object, but the typeof prefix operator also returns 'object' when its operand is an array or null .

Objects are extensible by default, meaning that new properties can be added at any time. New properties can be added with an assignment operator.

a.wooga = true;    // a now has a wooga property

Extensibility can be turned off for an object by the preventExtensions Object function.

Objects can be used as associative arrays or hash collections, with two limitations. First, the keys of an object must be strings. If any other value is used as a key, it is converted into a string first. The second limitation is more serious. In addition to an object's own properties, an object may have inherited properties. This can cause confusion for some applications.

function has_a(object, key) {
    return key in object;
}

var word = {};
word[1.0] = true;
alert(has_a(word, '1.0'));            // false
alert(has_a(word, '1'));              // true

word.cat = true;
alert(has_a(word, 'cat'));            // true
alert(has_a(word, 'dog'));            // false
alert(has_a(word, 'constructor'));    // true (inherted)

It is regrettably necessary to program defensively in the face of this by looking for specific values or types, or by using the hasOwnProperty object prototype function. For example,

function has_a(object, key) {

// Look for a particular value instead of simply having the property.

    return object[key] === true;
}

Another option is to use create Object function instead of an object literal to create an object that does not inherit.

var word = Object.create();

Creation

An object can be created by

There is no explicit object reclamation. All objects are subject to automatic garbage collection. The memory that an object occupies may be reused when the object has been forgotten by the program (when there are no live references to the object). Property

An object is a container of zero or more properties. A property associates a key string with a value. Having a reference to an object and a key string, it is possible to get the value of a property, or to set the value of a property. A property has attributes, which can be manipulated with a property descriptor. The attributes determine whether the key is enumerable, or if the property's value can be changed, or if the property can be reconfigured.

A property can be a data property, associating a key with a value, or an accessor property, associating a key value with a get function and a set function.

An object can inherit some or all of its properties from another object. A property that is directly a part of an object is called an own property. A property that is inherited is called an inherited property.

// Make an elder variable, and initialize it with an object literal,
// creating an object with an mm data property.

var elder = {
    mm: 0
};

// Add to elder an inch accessor property.

Object.defineProperty(elder, 'inch', {
    get: function () {
        return this.mm / 25.4;
    },
    set: function (value) {
        this.mm = value * 25.4;
    }
});

// Make a younger variable, and assign to it a new object that
// inherits from the elder object.

var younger = Object.create(elder);

// Add to younger a unit data property.

younger.unit = 'mm';

// Add to younger a meter accessor property.

Object.defineProperty(elder, 'meter', {
    get: function () {
        return this.mm / 1000;
    },
    set: function (value) {
        this.mm = value * 1000;
    }
});

// younger.mm       inherited, data
// younger.inch     inherited, accessor
// younger.unit     own, data
// younger.meter    own, accessor

// elder.mm         own, data
// elder.inch       own, accessor
// elder.unit       undefined
// elder.meter      undefined

An array containing the keys of all of an object's own enumerable properties can be obtained with the keys Object function. All of an object's enumerable properties can be obtained with the for in statement. Property descriptor

A property descriptor is an object that describes a property and its attributes. A property descriptor object can be passed to the defineProperty Object function and the defineProperties Object function. A property descriptor object can be obtained from the getOwnPropertyDescriptor Object function.

These are all of the properties that may be present in a property descriptor:

value The value of the property. This attribute is only used in data properties. writeable If true, the value may be changed. If false, attempting to change the value throws an exception (ES5 strict) or fails silently (ES3). This attribute is only used in data properties. Once it is set to false, it can no longer be set to true. enumerable If true, the key string will appear in the sequence produced by the for in statement. Once it is set to false, it can no longer be set to true. configurable If true, the data property may be changed into an accessor property or the accessor property may be changed into a data property or the accessor property may have its get and set methods replaced or the property may be deleted with the delete prefix operator. Once it is set to false, it can no longer be set to true. get If the get attribute is a function, the function is called when an attempt is made to get the value. The return value from the function is used instead. The function will receive no parameters, but this will be bound to the object. This attribute is only used in assessor properties. set If the set attribute is a function, the function is called when an attempt is made to set the value of the property. The function will receive one parameter, the value that is intended to be stored in the property, and this will be bound to the object. The return value is ignored. This attribute is only used in assessor properties.

A data property is a property that has neither a set attribute nor a get attribute. An accessor property is a property having either a get attribute, a set attribute, or both. An accessor property can be used to attach behavior to the retrieving or changing of a value.

Example:

function make_temperature(temp) {
    return Object.defineProperties({kelvin: temp || 0}, {
        celsius: {
            get: function () {
                return this.kelvin - 273.15;
            },
            set: function (temp) {
                this.kelvin = temp + 273.15;
            }
        },
        fahrenheit: {
            get: function () {
                return this.kelvin * 9/5 - 459.67;
            },
            set: function (temp) {
                this.kelvin = (temp + 459.67) * 5/9;
            }
        }
    });
}

So make_temperature creates an object that has three properties, kelvin, celsius, and fahrenheit, but keeps only one value. Changing any property will cause apparent change to the others.

var temp = make_temperature();
alert(temp.kelvin);        // 0
alert(temp.fahrenheit);    // -459.67
temp.fahrenheit = 32;
alert(temp.celsius);       // 0
alert(temp.kelvin);        // 273.15

Accessor properties should be used cautiously. Confusing side-effects should be avoided.

Get

The get operation is done by the . suffix operator select or [ ] suffix operator subscript when the operand is an object and when the expression is not an lvalue (the target of an assignment). This is how the get operation could be implemented:

function get(object, key) {    // object[key]

// Get the property descriptor associated with the key string. Use it to
// determine the property's value. If the property is an accessor property
// with a get function, call it and return the result, but return undefined
// if there is no get function. If the property is a data property, return
// its value.

    var property_descriptor,
        prototype = object;

    do {
        property_descriptor = Object.getOwnPropertyDescriptor(prototype, key);
        if (property_descriptor) {
            return (property_descriptor.get) 
                ? property_descriptor.get.call(object) 
                : (property_descriptor.set)
                    ? undefined 
                    : property_descriptor.value;
        }
        prototype = Object.getPrototypeOf(prototype);
    } while (prototype);

// If the object did not contain an own property, and if the object does not
// inherit the property, then return undefined.

    return undefined;
}

If the property is a data property, then the value is the value attribute. If the property is an accessor property and the get attribute is undefined, then the value is undefined. If the property is an accessor property and the get attribute is a function, then the function is called, binding this to the object, using the return value as the value. If there is no property associated with the key string, then undefined is the value.

If the object does not have and own property with that key, and if the object delegates, then we go to the delegate object and go again.

It is possible to set a property's value to undefined. This has been known to cause confusion because undefined is also the value of a missing property.

If neither the object nor its delegate(s) can produce a value for the key, then the result is undefined.

Set

The set operation is done by the . suffix operator select or [ ] suffix operator subscript when the operand is an object and when the expression is an lvalue (the target of an assignment). This is how the set operation could be implemented:

function set(object, key, value) {    // object[key] = value;

// Get the property descriptor associated with the key string.

    var property_descriptor = Object.getOwnPropertyDescriptor(object, key),
        prototype;
    if (property_descriptor) {

// If this is an accessor property, call its set function. If it doesn't
// have a set function, throw an exception.

        if (property_descriptor.set) {
            property_descriptor.set.call(object, value);
            return;
        }
        if (property_descriptor.get) {{
            throw new TypeError();
        }

// If this is a data property, update its value. But if the property is not
// writeable, throw an exception instead.

        if (property_descriptor.writeable) {
            property_descriptor.value = value;
            Object.definePropertyDescriptor(object, key, property_descriptor);
            return;
        }
        throw new TypeError();
    }

// The object does not currently have an own property with this key. Before we
// can add a new own property, we must verify that the object does not inherit
// an accessor property or a non-writeable data property.

    for (prototype = Object.getPrototypeOf(object); prototype;
            prototype = Object.getPrototypeOf(prototype)) {
        property_descriptor = Object.getOwnPropertyDescriptor(prototype, key);
        if (property_descriptor) {
            if (property_descriptor.set) {
                property_descriptor.set.call(object, value);
                return;
            }
            if (property_descriptor.get || !property_descriptor.writeable) {
                throw new TypeError();
            }
        }
    }

// Create a new own property with the value. Object.definePropertyDescriptor
// will fail if the object is not extensible.

    Object.definePropertyDescriptor({
        value:        value,
        writeable:    true,
        enumerable:   true,
        configurable: true
    });
}

The set operation creates or modifies the object's own properties. New properties can be added only if the object is still extensible.

Delete

A property can be removed from an object by the delete prefix operator but only if the property's configurable attribute is true.

Object function

Blah.

object literal

An object literal is an expression that produces an object value. An object literal starts with { left curly brace and ends with } right curly brace. Between the braces are zero or more pairs, separated by , comma. Each expression contributes one property to the object. An empty object is created by {}. There are two kinds of pairs.

A data property pair is a name or string literal followed by a : colon followed by an expression.

An accessor property pair is composed of two parts. Either part can be omitted. If both parts are included, then they must be separated by a comma. The first part is the name get followed by a name or string literal or number literal followed by ( left parenthesis, then ) right parenthesis, followed by a function body. The second part is the name set followed by a name or string literal or number literal followed by( left parenthesis, then a parameter name, then ) right parenthesis, followed by a function body.

function make_temperature(temp) {
    return {
        kelvin: temp || 0,
        get celsius() {
            return this.kelvin - 273.15;
        },
        set celsius(temp) {
            this.kelvin = temp + 273.15;
        },
        get fahrenheit() {
            return this.kelvin * 9/5 - 459.67;
        },
        set fahrenheit(temp) {
            this.kelvin = (temp + 459.67) * 5/9;
        }
    };
}

Every time an object literal is evaluated, it produces a new object, so

{property: x} === {property: x}    // false

because even though the two objects are similar in structure and content, they are two different objects.

Every object literal inherits from Object.prototype. Every property created by an object literal has its configurable, enumerable, and writeable attributes set to true.

var deroman = (function () {

// Use an object literal to create an object containing the values of the
// Roman numerals.

// We make the deroman function inside of an immediate function so that
// the value object is constructed only once. It contains the mapping of
// the Roman letters to numbers.

    var value = {
        I: 1,
        V: 5,
        X: 10,
        L: 50,
        C: 100,
        D: 500,
        M: 1000
    };

// The deroman function converts a string of Roman numerals to a number.

    return function deroman(string) {
        var i = 1, letter, next, result = 0;

// For each numeral, get its numeric value. If a letter's value is greater
// than or equal to the next letter's value, then add the letter's value to
// the result. Otherwise, subtract the value from the result. That causes
// I to be added in 'VI' but subtracted in 'IV'.

        string = string.toUpperCase();
        for (letter = value[string.charAt(0)]; typeof letter === 'number';
                letter = next) {
            next = value[string.charAt(i)];
            if (typeof next !== 'number' || letter >= next) {
                result += letter;
            } else {
                result -= letter;
            }
            i += 1;
        }
        return result;
    };

}());

Object primordial function

Blah.

Object prototype function

The Object primordial function has a prototype property object, Object.prototype, which is delegated to by most objects, including every object literal. Object.prototype contains these methods:

It is possible to add additional methods to Object.prototype, subject to these recommendations: The enumerable attribute should be false. Otherwise, the additional method will appear in the keys produced by the for in statement, which could cause poorly written programs to fail. Also, Object.prototype is shared by all compilation units. Failure could occur if competing compilation units make incompatible changes to Object.prototype. Also, future editions of the language might have new methods in Object.prototype. Also, implementations are allowed to add properties to Object.prototype. Such additions should not cause failures now or in the future.

octal base 8

See number literal, parseInt primordial function, and toString Number prototype function.

of

of Array function

Blah.

operand

An operand is an expression that provides a value to an operator. Also see argument.

operator

There are five kinds of operators.

An operator takes one, two, or three operands, where each operand is the value of an expression. Most operators are formed from special characters, but some such as typeof prefix operator and in infix operator use a name.

operator precedence

Tightness Operator Kind
strong ++ -- () . [] suffix operator
! + ++ - -- ~ delete new typeof void prefix operator
% * / infix operator
+ - infix operator
<< >> >>> infix operator
< <= > >= instanceof in infix operator
!= !== == === infix operator
& infix operator
^ infix operator
| infix operator
&& infix operator
|| infix operator
? : ternary operator
%= &= *= += -= /= <<= = >>= >>>= ^= |= assignment infix operator
weak , infix operator

Operator precedence makes it possible to omit the grouping parentheses from complex expressions. The suffix operators are the strongest. The , infix operator is the weakest. Given competition between two operators with difference precedence, the stronger operator wins.

Given competition between two operators with equal precedence, The leftmost operator is stronger, except for prefix operators and assignment operators where the right operator is stronger.

The following examples show pairs of statements that produce identical results. The first statement in each pair has no parentheses. The second statement shows how the first statement is interpreted using operator precedence.

r = a * b + c * d;
r = ((a * b) + (c * d));

s = a * b / c * d;
s = (((a * b) / c) * d);

t = a / b / c;
t = ((a / b) / c);

u = ~ -a;
u = (~ (-a));

v = a.b[c](d);
v = (((a.b)[c])(d));

w = -a.b;
w = (-(a.b));

x = -a * b;
x = ((-a) * b);

y = a = b = c = d;
y = (a = (b = (c = d)));

z = a(b), c(d);
(z = (a(b))), (c(d));

or

Blah.

See || infix operator or and | infix operator bitwise or.

own property

An own property is a property of an object that is not inherited from another object. Properties that are directly assigned to an object are always own properties. The hasOwnProperty Object prototype function can be used to determine if an object has an own property with a given key.

The keys object function produces all of the enumerable keys of all of the own properties of the object.

P

package reserved word

parameter

A parameter is a variable of a function that is initialized with a value from the arguments. Parameters are declared in a parameter list, which is a comma separated sequence of zero or more names. The entire parameter list is wrapped in a pair of parentheses.

function (first, second, third) {
    ...
}

does the same thing as

function () {
    var first = arguments[0],
        second = arguments[1],
        third = arguments[2];
    ...
}

Blah.

parameter list

Blah.

parenthesis

Also known as parens.

See ( left parenthesis and ) right parenthesis.

parse

parse JSON function

Blah.

parseFloat

parseFloat primordial function

Blah.

parseInt

parseInt primordial function

Blah.

pi

PI Math number pi

Math.PI contains an approximate value of π which is somewhere around 3.141592653589793.

function circumference(radius) {
    return 2 * Math.PI * radius;
}

Also see radians.

poker

var score_poker_hand = (function () {

// This program creates and uses two enumeration objects:
// rank_value and score_prefix.

// The score_poker_hand function takes a hand (an array of cards). The hand
// can contain between 5 and 9 cards, within which it will find the best five
// card poker hand. A hand is an array of objects containing rank and suit
// properties. The order of the cards is not significant. The hand is not
// modified.

// It returns a string which is the hand's score. The score of a better hand
// will always be greater than the score of a lesser hand.

// We are wrapping the score_poker_hand function in an immediate function to
// hide its static data structures (rank_value, score_prefix) and functions
// (hex, count_cards, count_ranks, straight, of_a_kind, kicker).

// The traditional ranks do not sort correctly because 'Q' > 'K', so we replace
// them with numbers in order to assure proper sequencing.  This also allows us
// to accept '10' or 'T' or 'Ten' or 'ten' as synonyms. Card ranks will be
// replaced according to the rank_value enumeration object. Later we will
// represent the ranks in base 16 so that they can be represented as single
// characters, so 'Ace' becomes 14 or 'e', and 'Ten' becomes 10 or 'a'.

    var rank_value = {
        '2':     2,   'Five':  5,   'eight': 8,    'J':     11,   'K':    13,
        'Two':   2,   'five':  5,   '9':     9,    'j':     11,   'k':    13,
        'two':   2,   '6':     6,   'Nine':  9,    'Jack':  11,   'King': 13,
        '3':     3,   'Six':   6,   'nine':  9,    'jack':  11,   'king': 13,
        'Three': 3,   'six':   6,   '10':    10,   '12':    12,   '14':   14,
        'three': 3,   '7':     7,   'T':     10,   'Q':     12,   '1':    14,
        '4':     4,   'Seven': 7,   't':     10,   'q':     12,   'A':    14,
        'Four':  4,   'seven': 7,   'Ten':   10,   'Queen': 12,   'a':    14,
        'four':  4,   '8':     8,   'ten':   10,   'queen': 12,   'Ace':  14,
        '5':     5,   'Eight': 8,   '11':    11,   '13':    13,   'ace':  14
    };

// The first character of the score indicates what kind of hand it is. The
// score_prefix is an enumeration object that maps the names of the poker
// hands to a single letter codes. The single letters sort correctly, so
//           score_prefix.straight_flush > score_prefix.no_pair

    var score_prefix = {
        straight_flush:  'S',    // + high-card
        four_of_a_kind:  'K',    // + 4-rank + kicker
        full_house:      'H',    // + 3-rank + 2-rank
        flush:           'F',    // + 5 kickers
        straight:        'A',    // + high-card
        three_of_a_kind: '3',    // + 3-rank + 2 kickers
        two_pair:        '2',    // + 2-rank + 2-rank + kicker
        one_pair:        '1',    // + 2-rank + 3 kickers
        no_pair:         '0'     // + 5 kickers
    };

// The final score will contain a score_prefix and additional characters
// to help break ties. Examples:

// The worst poker hand from 5 cards is
//    no_pair + 7 5 4 3 2                     = '075432'

// The worst poker hand from 7 cards is
//      no_pair + 9 8 7 5 4                   = '098754'

// The best pair is
       one_pair + A A K Q J                   = '1eedcb'

// The best two pair is
//     two_pair + A A K K Q                   = '2eeddc'

// The best three of a kind is
//     three_of_a_kind + A A A K Q            = '3eeedc'

// The worst straight is
//     straight + 5 4 3 2 A                   = 'A5'

// The best flush that is not a straight flush is
//      flush + A K Q J 9                     = 'Fedcb9'

// The best full house is
//      full_house + A A A K K                = 'Heeedd'

// The best four of a kind is
//      four_of_a_kind + A A A A K            = 'Ked'

// The best poker hand is
//      straight_flush + A (Royal flush)      = 'Se'


    function hex(number) {

// Return the number as a base 16 string. We convert the codes for ten, jack,
// queen, king, and ace to 'a', 'b', 'c', 'd', and 'e'.

        return number.toString(16);
    }


    function count_cards(hand, select) {

// The count_cards function produces an object that contains the counts of the
// elements of an array. If there is no select parameter, then the truthy
// elements are counted. If the select parameter is a function, then the
// elements are each passed to the select function and the results are counted.
// Otherwise, if select is a string and the elements are objects, use the
// select string as a property name and count the properties.

// The result is an object where the keys are elements and the values are the
// counts for each element.

        var element, i, result = {};
        for (i = 0; i < hand.length; i += 1) {
            element = hand[i];
            if (typeof select === 'function') {
                element = select(element);
            } else if (typeof select === 'string') {
                if (!element || typeof element !== 'object') {
                    throw new Error('count_cards expected an object');
                }
                element = element[select];
            }
            if (element) {

// If the current count for the element is not a number (most likely undefined,
// possibly an inherited method) then assign 1 to it. Otherwise, increment it.

                if (typeof result[element] !== 'number') {
                    result[element] = 1;
                } else {
                    result[element] += 1;
                }
            }
        }
        return result;
    }


    function count_ranks(hand) {
        return count_cards(hand, function (element) {
            return rank_value[element.rank];
        });
    }


    function straight(count) {

// Given a rank count, determine if it has a straight. Using the rank_value
// enumeraton object, starting with Ace and work down, look for 5 cards in a
// row. If they are found, return the value of the high card. The lowest
// straight has 6 high.

        var high, j, found;
        for (high = rank_value.ace; high >= rank_value.six; high -= 1) {
            if (count[high]) {
                found = true;
                for (j = 1; j < 5; j += 1) {
                    if (!count[(high - j)]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    return high;
                }
            }
        }

// If holding an Ace, look for a wheel (5-4-3-2-A).

        if (count[rank_value.ace]) {
            for (j = rank_value.five; j >= rank_value.two; j -= 1) {
                if (!count[j]) {
                    return false;
                }
            }
            return rank_value.Five;
        }
        return false;
    }


    function of_a_kind(count, number) {

// Given a rank count, find the highest rank that meets or exceeds the number.
// If successful, subtract the number and return the value. For example, if
// the count contains 4 aces, then of_a_kind(count, 4) would return 14 (the ace
// value) and reduce the ace count to zero. It looks first at the aces, then
// kings, and so on, looking finally at the twos.

        var value;
        for (value = rank_value.ace; value >= rank_value.two; value -= 1) {
            if (count[value] >= number) {
                count[value] -= number;
                return value;
            }
        }
        return false;
    }


    function kicker(count, number) {

// Produce a string containing the hex values of the count's highest ranking
// cards. The number parameter determines how many kickers to take.

        var result = '',
            value;
        for (value = rank_value.ace; value >= rank_value.two; value -= 1) {
            while (count[value]) {
                result += hex(value);
                count[value] -= 1;
                number -= 1;
                if (number <= 0) {
                    break;
                }
            }
        }
        return result;
    }


    return function score_poker_hand(hand) {

// This is the actual score_poker_hand function. It takes a hand of 5 to 9
// cards. If the hand is shorter than 5, then some hands will be impossible
// to produce. For example, with two cards, the only possible scores are
// one_pair and no_pair. If the hand is bigger than 9 cards, then it might
// produce an incorrect score in the case where the hand contains two or more
// flushes. Most games use 5 or 7 cards. The hand is not modified. A hand is
// an array of card objects. A card object has two properties, a rank and a
// suit. So
//      score_poker_hand([
//          {"rank": "four", "suit": "D"},
//          {"rank": "5",    "suit": "D"},
//          {"rank": "Ace",  "suit": "D"},
//          {"rank": "2",    "suit": "D"},
//          {"rank": "Q",    "suit": "D"}
//      ])    // 'Fec542'  (flush + AQ542)

        var count, flush, flush_count, high, pair, suit, suit_count;

// First look for a flush. Did we count 5 or more cards of the same suit?

        suit_count = count_cards(hand, 'suit');
        for (suit in suit_count) {
            if (typeof suit_count[suit] === 'number' && suit_count[suit] >= 5) {
                flush = suit;
                break;
            }
        }

// We see a flush. Is it a straight flush? To find out, make a flush hand
// that includes only the cards that are suited and test it for straightness.

        if (flush) {
            flush_count = count_ranks(hand.filter(function (element) {
                return element.suit === flush;
            }));
            high = straight(flush_count);
            if (high) {
                return score_prefix.straight_flush + hex(high);
            }
        }

// If it is not a straight flush, then make a new rank count that will be used
// for all of the following tests.

        count = count_ranks(hand);

// Four of a kind?

        high = of_a_kind(count, 4);
        if (high) {
            return score_prefix.four_of_a_kind + hex(high) + kicker(count, 1);
        }

// Full house? First look for a 3 of a kind. If we find one, look for a
// two of a kind. If we find one, then we have a full house. If we don't
// find the pair, then we have to undo the matching of the 3 of a kind
// so that it doesn't interfere with the matching of a straight.

        high = of_a_kind(count, 3);
        if (high) {
            pair = of_a_kind(count, 2);
            if (pair) {
                return score_prefix.full_house + hex(high) + hex(pair);
            }
            count[high] += 3;  // undo the matching of the 3 of a kind
        }

// Flush?

        if (flush) {
            return score_prefix.flush + kicker(flush_count, 5);
        }

// Straight?

        high = straight(count);
        if (high) {
            return score_prefix.straight + hex(high);
        }

// Three of a kind?

        high = of_a_kind(count, 3);
        if (high) {
            return score_prefix.three_of_a_kind + hex(high) + kicker(count, 2);
        }

// One pair? Two pair?

        high = of_a_kind(count, 2);
        if (high) {
            pair = of_a_kind(count, 2);
            if (pair) {
                return score_prefix.two_pair + hex(high) + hex(pair) +
                        kicker(count, 1);
            } else {
                return score_prefix.one_pair + hex(high) + kicker(count, 3);
            }
        }

// If all tests failed, then we have a no pair.

        return score_prefix.no_pair + kicker(count, 5);
    };
}());

pop

pop Array prototype function

Blah.

POSITIVE_INFINITY

POSITIVE_INFINITY Number number

Number.POSITIVE_INFINITY is the same as Infinity, and is much more to type.

pow

pow Math function raise to a power

The Math.pow(x, y) function raises a number to a power. In mathematical notation, it is usually written as a superscript: x y. The result is x multiplied by itself as many times as indicated by y, so that Math.pow(2, 4) is the same as 2 * 2 * 2 * 2, having a result of 16. y is not required to be an integer, and it is not required to be positive. If x is 0, then the result is 0. If y is 0, then result is 1. If both x and y are 0, the result is 1. Some programming languages provide an exponentiation operator such as ** or ^. This language does not, you must use the Math.pow function instead. It is used rarely enough that this does not present a hardship.

Math.pow(x, 1 / 2) is mostly the same as Math.sqrt(x). Math.pow(Math.E, x) is mostly the same as Math.exp(x);

It could be implemented like this:

Math.pow = function (x, y) {
    var abs_x, y_is_integer, y_is_odd_integer;
    x = +x;
    y = +y;

// y is zero...

    if (y === 0) {
        return 1;
    }

// x or y are NaN...

    if (isNaN(x) || isNaN(y)) {
        return NaN;
    }

    abs_x = (x < 0)
        ? -x
        : x;
    y_is_integer = Math.floor(y) === y;
    y_is_odd_integer = y_is_integer && Math.floor(y / 2) * 2 !== y;

// y is Infinity...

    if (y === Infinity) {
        return (abs_x > 1)
            ? Infinity
            : (abs_x === 1)
                ? NaN
                : 0;
    }
    if (y === -Infinity) {
        return (abs_x > 1)
            ? 0
            : (abs_x === 1)
                ? NaN
                : Infinity;
    }

// x is Infinity...

    if (x === Infinity) {
        return (y > 0)
            ? Infinity
            : 0;
    }
    if (x === -Infinity) {
        return (y > 0)
            ? (y_is_odd_integer)
                ? -Infinity
                : Infinity
            : (y_is_odd_integer)
                ? -0
                : 0;
    }

// x is zero...

    if (x === 0) {
        if (1 / x > 0) {
            return (y > 0)
                ? 0
                : Infinity;

// x is -0...

        } else {
            return (y > 0)
                ? (y_is_odd_integer)
                    ? -0
                    : 0
                : (y_is_odd_integer)
                    ? -Infinity
                    : Infinity;
        }
    }

    if (x < 0 && !y_is_integer) {
        return NaN;
    }

// eventually the computation occurs.

    return Math.exp(Math.log(x) * y);
};

Also see exp Math function exponential and sqrt Math function.

Example:

function monthly_payment(principal, interest_rate, nr_years) {
    var monthly_interest = (interest_rate / 100) / 12,
        nr_monthly_payments = nr_years * 12;

    return principal * monthly_interest /
        (1 - Math.pow(1 + monthly_interest, -nr_monthly_payments));
}

precedence

See operator precedence.

prefix operator

A prefix operator is a unary operator that is placed before its operand. A prefix operators are higher in precedence than any binary operator, but lower in precedence than an suffix operator.

Also see assignment prefix operator.

preventExtensions

preventExtensions Object function

Blah.

primordial

primordial function

These functions are available in the primordial context. An implementation is allowed to add additional primordial functions.

primordial object

The primordial context contains these objects:

Blah.

primordial variable

private reserved word

program

A program is a complex set of instructions that control the operation of a computer. In this language, a program is delivered to the execution site in a textual form (or as source code or as script) which is then compiled and immediately executed. See compilation unit.

promise

A promise is an object that represents a value that may be unknown at the present time but which might become known in the future. A promise allows us to act on the future value now, remembering our intentions until the promise is ultimately kept or broken. The resolution of a promise might depend in a result that will be determined on the other side of the network or in a different process.

Also see callback.

Promise primordial function

Blah.

Promise function

Promise prototype function

property

A property is a component of an object that is associated with a key string. There are two kinds of property:

A data property holds a value that can be get or set. An accessor property instead holds one or two functions that will be called when an attempt is made to get or set the property. A property can be inherited, or it can be the object’s own property.

See object. Also see . suffix operator select and [ ] suffix operator subscript.

propertyIsEnumerable

propertyIsEnumerable Object prototype function

Blah.

protected reserved word

prototypal inheritance

Blah.

function new_constructor(prototype, initializer) {
    return function () {
        var that = Object.create(prototype);
        initializer.apply(that, arguments);
        return that;
    };
}

prototype

Every object can inherit properties from a prototype object. When fetching a named property of an object using the . suffix operator select or the [ ] suffix operator subscript, if the object does not own a property with that name, then its prototype is examined. If the prototype object owns a property with that name, then the value of that property is fetched.

Every function contains a prototype property that property is usually an object. That object

prototype function

Blah.

prototype object

Blah.

prototype number

Blah.

prototype Function prototype object

Blah.

proxy

Proxy primoridal object MISSING LINK

Blah.

Proxy function

Blah.

Proxy prototype function

Blah.

ps paragraph separator

Blah.

pseudoclassical

Blah.

public reserved word

public domain

Blah.

punctuator

A punctuator is a symbol composed of one or more special characters that is used as a separator or operator.

push

push Array prototype function

Blah.

Q

quality

Blah.

queue

Blah.

quotation marks

See ' single quotation mark and " double quotation mark and string literal.

quotient

The result of a division. See / infix operator divide and /= assignment infix operator divide.

R

radians

Blah.

function degrees(radians) {
    return radians * 180 / Math.PI;
}
function radians(degrees) {
    return radians * Math.PI / 180;
}

raise

raise exception

See throw statement.

raise to a power

See pow Math function raise to a power.

random

random Math function

The Math.random() function returns a number that is greater than or equal to 0 and less than 1. Each time Math.random()is called it is likely to produce a different result. Unfortunately, it is not guaranteed to have sufficient randomness for cryptographic or gambling applications.

Because Math.random() produces a number between 0 and 1, it is usually necessary to scale it a to desired range. For example, to simulate the rolling for a six sided die, use Math.floor(Math.random()* 6) + 1.

Flipping a coin is simpler:

cointoss = Math.random() >= 0.5;    // true is heads, false is tails

An array representing a deck of 52 cards can be shuffled with 51 random numbers.

function shuffle(deck) {

// Shuffle the contents of an array using the Fisher-Yates shuffle. Starting
// at the end of the deck, swap each card with a card randomly selected from
// the front part of the deck.

    var card_nr = deck.length,
        rand,    // The index of the randomly selected card
        temp;    // Temporary storage for the swap.

    while (card_nr > 1) {
        rand = Math.floor(Math.random() * card_nr);
        card_nr -= 1;
        temp = deck[card_nr];
        deck[card_nr] = deck[rand];
        deck[rand] = temp;
    }
}

RangeError

RangeError primordial function

Blah.

raw

raw String function

Blah.

recursion

Blah.

function solve(data, name) {

// The solve function takes a network object and the name of a node in that
// network, and finds the lowest cost path to a terminal node.

// There are two kinds of nodes. An ordinary node contains up and down
// properties which describe the local cost of the next transition. A terminal
// node contains a cost property, and not up or down properties.

// The solve function depends on two recursive functions, chase and follow,
// to do its work.

    var results = [],   // An array of strings, the names on the cheapest path.
        solution = {};  // The cheapest path from this node and the total cost
                        // from this node.

    function chase(name) {

// Given the name of a node in the data set, compute the least total cost from
// this node to a terminal node. Find the solutions to the up and down nodes,
// and make a solution that is the cheaper for this node. This function finds
// the up and down solutions by calling itself.

        var down,
            down_cost,
            down_solution,
            lemma = solution[name],
            node,
            up,
            up_cost,
            up_solution;

// If there is already a solution for this node,
// then there is nothing to be done.

        if (!lemma) {
            node = data[name];
            up = node.up;
            down = node.down;

// If the node has an up, find the up solution.

            if (up) {
                up_solution = chase(up.next);
                up_cost = up.cost + up_solution.cost;

// And if the node also has a down, find the down solution.

                if (down) {
                    down_solution = chase(down.next);
                    down_cost = down.cost + down_solution.cost;

// Choose the less expensive solution.

                    if (up.cost < down.cost) {
                        lemma = {next: up.next, cost: up_cost};
                    } else {
                        lemma = {next: down.next, cost: down_cost};
                    }

// If there wasn't a down, choose the up solution.

                } else {
                    lemma = {next: up.next, cost: up_cost};
                }
            } else {

// If there wasn't an up, choose the down solution.

                if (down) {
                    down_solution = chase(down.next);
                    down_cost = down.cost + down_solution.cost;
                    lemma = {next: down.next, cost: down_cost};

// If this was a terminal node, then take the node.

                } else {
                    lemma = node;
                }
            }

// Record this node in the solution set.

            solution[name] = lemma;
        }

// Return the solution for this node.

        return lemma;
    }


    function follow(name) {

// Make a list of the names that make the cheapest path.
// This function obtains the succeeding names by calling
// itself.

        if (name) {
            results.push(name);
            follow(solution[name].next);
        }
    }

// Now we can call chase and follow and return the results.

    chase(name);
    follow(name);
    return results;
}

var data = {
    a: {
        up:   {next: 'c', cost: 1},
        down: {next: 'd', cost: 0}
    },
    c: {
        up:   {next: 'e', cost: 5},
        down: {next: 'f', cost: 4}
    },
    d: {
        up:   {next: 'f', cost: 7},
        down: {next: 'g', cost: 3}
    },
    e: {
        up:   {next: 'h', cost: 2},
        down: {next: 'i', cost: 1}
    },
    f: {
        up:   {next: 'i', cost: 1},
        down: {next: 'j', cost: 2}
    },
    g: {
        up:   {next: 'j', cost: 5},
        down: {next: 'k', cost: 4}
    },
    h: {
        down: {next: 'l', cost: 3}
    },
    i: {
        up:   {next: 'l', cost: 3},
        down: {next: 'm', cost: 4}
    },
    j: {
        up:   {next: 'm', cost: 2},
        down: {next: 'n', cost: 2}
    },
    k: {
        up:   {next: 'n', cost: 2}
    },
    l: {
        down: {next: 'o', cost: 5}
    },
    m: {
        up:   {next: 'o', cost: 2},
        down: {next: 'p', cost: 8}
    },
    n: {
        up:   {next: 'p', cost: 4}
    },
    o: {
        down: {next: 'b', cost: 2}
    },
    p: {
        up:   {next: 'b', cost: 1}
    },
    b: {cost: 0}
};

alert(solve(data, 'a'));

reduce

reduce Array prototype function

Blah.

reduceRight

reduceRight Array prototype function

Blah.

reference

Blah.

ReferenceError

ReferenceError primordial function

Blah.

Reflect

Also see proxy.

Reflect primordial function

Blah.

Reflect function

regexp

Blah.

regexp boolean

Blah.

regexp delimiter

Blah.

regexp flag

The regexp flags are

Blah.

RegExp function

Blah.

regexp literal

Blah. 7.8.5

regexp operator

Blah.

RegExp primordial function

Blah.

RegExp prototype function

Blah.

RegExp prototype number

Blah.

regular expression

See regexp.

relational operator

The relational operators are

Every relational operator is an infix operator. They all return either the true value or the false value depending on the relationship between the two operands. They resemble mathematical symbols but do not compose like mathematical symbols. The expression

a < b < c

looks like it might be true if a is less than b and if b is also less than c, but that is not what it means. The expression first compares a and b, producing either true or false. Then c will be compared to either true or false, not to b.

remainder

See % infix operator remainder.

repeat

repeat String prototype function

Blah.

replace

replace String prototype function

Blah.

requestor

Blah.

reserved word

A reserved word is an identifier that is reserved for the exclusive use of the language itself. A reserved word may be used as a statement, operator, or a future feature of tomorrow. The reserved words are

A reserved word may not be used as the name of a function , variable, parameter, or statement label. Some of the reserved words are not actually used in any edition of the language.

var break;        // syntax error
var breaky;       // ok

The constants false literal, null literal, and true literal are not formally reserved words, but they have the same restrictions. The constants Infinity literal, NaN literal, and undefined literal do not have these restrictions, which is weird.

var null;         // syntax error
var undefined;    // ok but also very wrong

return reserved word

return statement

Blah.

retursion

Blah. A function returns itself.

reverse

reverse Array prototype function

Blah.

round

round Math function

The Math.round(number) function takes a number argument and returns the nearest integer. It could be implemented as

Math.number = function (number) {
    var value = +number;
    return ((value < 0 && value >= -0.5) || (value === 0 && 1 / value < 0))
        ? -0
        : Math.floor(+value + 0.5);
};

S

scope

Blah.

seal

seal Object function

Blah.

Blah.

semicolon

See ; semicolon.

semicolon insertion

See automatic semicolon insertion

separator

Blah.

set

See object.

set primordial function

set prototype

set prototype function

setDate

setDate Date prototype function

Blah.

setFloat32

setFloat32 DataView prototype function

Blah.

setFloat64

setFloat64 DataView prototype function

Blah.

setFullYear

setFullYear Date prototype function

Blah.

setHours

setHours Date prototype function

Blah.

setInt16

setInt16 DataView prototype function

Blah.

setInt32

setInt32 DataView prototype function

Blah.

setInt8

setInt8 DataView prototype function

Blah.

setMilliseconds

setMilliseconds Date prototype function

Blah.

setMinutes

setMinutes Date prototype function

Blah.

setMonth

setMonth Date prototype function

Blah.

setSeconds

setSeconds Date prototype function

Blah.

setTime

setTime Date prototype function

Blah.

setUInt16

setUInt16 DataView prototype function

Blah.

setUInt32

setUInt32 DataView prototype function

Blah.

setUInt8

setUInt8 DataView prototype function

Blah.

setUTCDate

setUTCDate Date prototype function

Blah.

setUTCFullYear

setUTCFullYear Date prototype function

Blah.

setUTCHours

setUTCHours Date prototype function

Blah.

setUTCMilliseconds

setUTCMilliseconds Date prototype function

Blah.

setUTCMinutes

setUTCMinutes Date prototype function

Blah.

setUTCMonth

setUTCMonth Date prototype function

Blah.

setYear

setYear Date prototype function

Blah.

shift

shift Array prototype function

Blah.

shift operator

sign

Blah.

sin

sin Math function sine

The Math.sin(radians) function, also known as sine, takes an angle in radians and returns a number in the range -1...1.

function cartesian(distance, radians) {

// Given a distance and direction from the origin in radians,
// produce a cartesian point.

    return {
        x: distance * Math.cos(radians),
        y: distance * Math.sin(radians)
    };
}

This is an approximate implemention of Math.sin:

Math.sin = (function () {
    var factorial = 1,
        last_stage = 40,
        sign = -1,
        signed_factorial_recipricals = [],
        stage,
        two_pi = Math.PI * 2;

    for (stage = 3; stage < last_stage; stage += 2) {
        factorial *= (stage - 1) * stage;
        signed_factorial_recipricals[stage] = sign / factorial;
        sign = -sign;
    }
    return function sin(radians) {
        while (radians >= two_pi) {
            radians -= two_pi;
        }
        while (radians < 0) {
            radians += two_pi;
        }
        var result = radians,
            rr = radians * radians,
            stage;
        for (stage = 3; stage < last_stage; stage += 2) {
            radians *= rr;
            result += radians * signed_factorial_recipricals[stage];
        }
        return result;
    };
}());

sizeof

sizeof prefix operator

Blah.

slice

slice Array prototype function

Blah.

slice ArrayBuffer prototype function

Blah.

slice String prototype function

Blah.

sloppy mode

some

some Array prototype function

Blah.

space

Blah.

special character

See

splice

splice Array prototype function

Blah.

split

split String prototype function

Blah.

sqrt

sqrt Math function

Math.sqrt(number) is the square root function. It returns a value which, when multiplied by itself, is approximately equal to the original number. It could be implemented as

Math.sqrt = function (number) {
    return Math.pow(number, 0.5);
};

Example:

function distance(a, b) {

// Compute the distance between two points.

    return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}

SQRT1_2

SQRT1_2 Math number

Math.SQRT1_2 holds the result of Math.sqrt(1 / 2), which is approximately 0.7071067811865476.

SQRT2

SQRT2 Math number

Math.SQRT2 holds the result of Math.sqrt(2), which is approximately 1.4142135623730951.

square root

See sqrt Math function.

stack

Blah.

statement

A statement is a syntactic unit of execution. A compilation unit or a function body contains a list of zero or more statements which will be executed in order from first to last. Each statement runs to completion before the next statement is executed. Some statements can contain other statements. These are the kinds of statements:

Also see ; semicolon, conditional statement, disruptive statement, and loop statement.

statement label

See label.

statement punctuator

See ( left parenthesis, ) right parenthesis, ; semicolon.

static reserved word

strict mode

The ES5/strict dialect removes or modifies a few of the language’s most problematic features. It requires source-level opt-in in order to not break compatibility. It is recommended that strict mode always be requested.

Because strict mode can break compatibility with ES3, it must be explicitly requested with the strict mode pragma. The pragma takes the form of a string literal expression statement:

"use strict";

It will be ignored by ES3 processors, so it is possible to create ES5/strict programs that will work correctly in ES3 processors. The strict mode pragma can be placed at the top of a compilation unit, or as the first statement of a function body. When placed at the top of a compilation unit, it indicates that the entire compilation unit is to be treated strictly. This is the preferred usage. When placed at the top of a function body, it indicates that the function is to be treated strictly. It is possible to mix strict mode code and non-strict mode code. Functions compiled in either mode can call functions compiled in the other mode.

Blah.

string

A string is a finite ordered sequence of zero or more characters. A character is a 16 bit Unicode code unit. A string is immutable, so once a string is made, it cannot be changed. Two strings containing the same code points in the same order will be found to be equal by the === infix operator. The typeof prefix operator produces 'string' when its operand is a string. Two strings can be combined to produce a new sting with the + infix operator add or concatenate.

'cat' === 'c' + 'a' + 't'    // true

A string contains a length String prototype number that produces a number which is the number of code units in the string. There is no fixed limit on the size of a string.

"".length                   // 0
('c' + 'a' + 't').length    // 3

A string value inherits from String prototype. This provides methods such as charAt String prototype function that can fetch a single character from a string, or slice String prototype function that can fetch a substring from a string. See String prototype function.

A string can contain any kind of textual material, including programs.

There is no separate character type. A single character is represented as a string with a length of 1.

String escapement

String function

string literal

A string literal is used to include a string value in a program. There are two forms of string literal: single quote string literal and double quote string literal. They differ only in the character used to wrap the characters.

A string literal is a token made up of a quoting character, zero or more character literals, and a matching quoting character.

The quoting characters are

A character literal can be

A Unicode escape sequence is a \u followed by 4 hexadecimal digits. The digits are evaluated in base 16 to produce a single 16 bit code unit.

A compact escape sequence is a \ backslash followed by one of the following:

Character after \ backslashThe resulting character
' single quotation mark ' single quotation mark
" double quotation mark " double quotation mark
\ backslash \ backslash
bbs MISSING LINK
fff MISSING LINK
nlf linefeed
rcr carriage return
tht MISSING LINK
vvt MISSING LINK
x 2 hexadecimal digitsA character between \u0000 and \u00ff
line terminator line continuation MISSING LINK

These all represent the same string:

'"'  "\""  '\x22'  "\u0022"

If the character after the \ backslash is a line terminator or the line terminator pair cr carriage return lf linefeed, then the line terminator (or line terminator pair) will be ignored. This produces line continuation, permitting a string literal to be continued over more than one line. Be careful, it can be tricky: If the character following the \ backslash is ordinary whitespace and not a line terminator, then a syntax error will result. All whitespace looks alike.

    var long_line_1 = "This is a \
long line";                         // ok
    var long_line_2 = "This is a \
long line";                         // syntax error

There is no limit on the length of a string literal. The empty string can be represented as '' or "".

Because there are two forms of string literal, there is confusion about which to use. The language itself is completely neutral on this question, but there are some principle of good practice to consider:

Be consistent. It can be visually confusing to randomly change forms. Visual confusion can lead to bugs. Use the ' form for symbols, character constants, and internal strings such as property names. Use the " form for strings that will be exported from the program, such as HTML fragments, URLs, or messages to the user.

String primordial function

String is a global function that serves three purposes.

First, when invoked as a function, it takes any operand and produces a string value.

Second, when invoked as a constructor with the new prefix operator, takes an operand and produces an object whose valueOf method produces a string value.

Third, it has a prototype property that holds the methods that are inherited by all strings.

String prototype

Blah.

String prototype function

String prototype number

length

stringify

stringify JSON function

Blah.

substr

substr String prototype function

Blah.

substring

substring String prototype function

Blah.

subtract

See - infix operator subtract.

suffix operator

Blah.

Also see assignment suffix operator.

super reserved word

switch reserved word

switch statement

Blah.

SyntaxError

SyntaxError primordial function

Blah.

T

tab tabulation

Blah.

tail recursion

tan

tan Math function tangent

The Math.tan(radians) function, also known as tangent, takes an angle in radians and returns a number.

This is an approximate implemention of Math.tan:

Math.tan = function tan(radians) {
    return Math.sin(radians) / Math.cos(radians);
};

See Math function.

ternary operator

A ternary operator is an operator that takes three operands. JavaScript has only one ternary operator, the ? ternary operator.

test

test RegExp prototype function

Blah.

this reserved word

this parameter

Using this is like pair programming with Abbott & Costello.

Blah.

throw reserved word

throw statement

Blah.

toDateString

toDateString Date prototype function

Blah.

toExponential

toExponential Number prototype function

Blah.

toFixed

toFixed Number prototype function

Blah.

toGMTString

toGMTString Date prototype function

Blah.

toISOString

toISOString Date prototype function

Blah.

token

A compilation unit is made up of tokens. The tokens of this language are

toLocaleDateString

toLocaleDateString Date prototype function

Blah.

toLocaleFormat

toLocaleFormat Number prototype function

Blah.

toLocaleLowerCase

toLocaleLowerCase String prototype function

Blah.

toLocaleString

toLocaleString Array prototype function

Blah.

toLocaleString Number prototype function

Blah.

toLocaleString Object prototype function

Blah.

toLocaleTimeString

toLocaleTimeString Date prototype function

Blah.

toLocaleUpperCase

toLocaleUpperCase String prototype function

Blah.

toLowerCase

toLowerCase String prototype function

Blah.

toPrecision

toPrecision Number prototype function

Blah.

toString

toString Array prototype function

Blah.

toString Boolean prototype function

Blah.

toString Number prototype function

Blah.

toString Object prototype function

Blah.

toString String prototype function

Blah.

toTimeString

toTimeString Date prototype function

Blah.

toUpperCase

toUpperCase String prototype function

Blah.

trim

trim String prototype function

Blah.

true reserved word

Blah.

true literal

Blah.

truthy

Blah.

trunc

trunc Math function truncate

There is no trunc function. See integer.

try reserved word

try statement

Blah.

In the example for callback, a potential problem with the setStatus function is that if any of the callback functions throw an exception, the remaining callback functions will not be executed. This can be guarded against by wrapping the invocation of each of the callbacks in a try statement. This will allow setStatus to carry on. In this case, the catch clause is empty because we don't care what the exception was. In all cases we recover by ignoring the exception and allowing forEach to proceed to the next iteration.

        setStatus: function (newStatus) {
            status = newStatus;
            subscribers.forEach(function (callback) {
                try {
                    callback(status);
                } catch (e) {}
            });
        }

There are some errors that cannot be caught by a try statement, such as exceeding implementation dependent limits on recursion depth, memory consumption, or execution time.

The catch scope problem.

turn

Program execution happens in turns. First, each compilation unit is given one turn in which it executes to completion. In some environments, that is the end of the program. But in sessionful environments like web browsers, turns will then be given to events, including UI events generated by the user, by the network stack, by the file system, and by interprocess communication, and timer events. An event handler function or deferred function, when given its turn, will run to completion. Once it has completed (usually by returning) then the program goes idle until another event occurs. The next event must wait until the previous turn ends.

The turn model avoids a large class of concurrency hazards, particularly deadlock and race conditions. The turn model tends to make programs easier to make and more reliable than the thread model.

The greatest hazard in the turn model is that if a turn takes too long, then the system becomes unresponsive. This can be avoided by distributing long-running functions to other processes. Processes can communicate with each other (typically using a JSON message delivered as an event or callback) but are unable to directly access the variables or data structures of other processes, thus avoiding the hazards of the thread model. The process model is not yet universally adopted in browsers, but is quickly gaining popularity.

type

These are the types in this language:

An implementation or environment may add additional types.

TypeError

TypeError primordial function

Blah.

typed array

Blah.

typeof reserved word

typeof prefix operator

Blah.

U

\u

See Unicode escape sequence.

Uint16Array

Uint16Array primordial function

Uint16Array function

Uint16Array number

Uint16Array prototype

Uint16Array prototype ArrayBuffer

Uint16Array prototype function

Uint16Array prototype number

Uint16Array number

Uint16Array string

Uint32Array

Uint32Array primordial function

Uint32Array function

Uint32Array number

Uint32Array prototype

Uint32Array prototype ArrayBuffer

Uint32Array prototype function

Uint32Array prototype number

Uint32Array number

Uint32Array string

Uint8Array

Uint8Array primordial function

Uint8Array function

Uint8Array number

Uint8Array prototype

Uint8Array prototype ArrayBuffer

Uint8Array prototype function

Uint8Array prototype number

Uint8Array number

Uint8Array string

unary operator

An operator that takes one operand. See prefix operator and suffix operator.

undefined

@Blah.

undefined literal

Blah.

Unicode

Blah.

Unicode escape sequence

Blah.

unreachable code

Blah.

unshift

unshift Array prototype function

Blah.

upper case

See case .

URIError

URIError primordial function

Blah.

use reserved word

use strict

See strict MISSING LINK.

V

values

values Array prototype function

Blah.

valueOf

valueOf Boolean prototype function

Blah.

valueOf Date prototype function

Blah.

valueOf Number prototype function

Blah.

valueOf Object prototype function

Blah.

valueOf String prototype function

Blah.

var reserved word

var statement

Blah.

variable

A variable is a named value within a function or within the global context. A variable has a name. The initial value of a variable is undefined. The value of a variable can be replaced by using an assignment operator. A variable is declared with the var statement or the function statement.

variadic

A variadic function is a function that takes a variable number of arguments. See arguments parameter and the ... prefix operator ellipsis.

void reserved word

void prefix operator

The void operator takes the value of its operand and gives as its result the undefined value. In other languages, void is a type and not a useless operator, so the likelihood of inducing confusion with the use of void is very high. You don't need that.

void was added to the language for the benefit of in-line scripts in web pages, which is itself a very bad practice.

W

wat

Blah ha ha.

WeakMap

WeakMap primordial function

Blah.

WeakMap prototype

WeakMap prototype function

WeakSet

WeakSet primordial function

WeakSet prototype

WeakSet prototype function

while reserved word

See do statement.

while statement

Blah.

whitespace

Whitespace characters are used in a compilation unit to separate name tokens and to improve the readability of the text. They are called whitespace characters because they do not make any marks. They leave the paper white, creating space around the characters that make marks.

The whitespace characters include

Unicode escape sequencealtnameline terminator
\u0009\ttab tabulation
\u000A\nlf linefeedyes
\u000B\vvt MISSING LINK
\u000C\fff MISSING LINK
\u000D\rcr carriage returnyes
\u0020 sp MISSING LINK
\u00A0 nbsp MISSING LINK
\u2028 ls line separatoryes
\u2029 ps paragraph separatoryes
\uFFFE bom MISSING LINK

Four of the whitespace characters are also line terminator characters. A line terminator character identifies the end of a line of program text. This is important in semicolon insertion, and in the formation of a comment or string literal.

In addition to the characters above, characters in the Unicode general category of Zs separator, space are also treated as whitespace.

with reserved word

with statement

The with statement was a feature of ES3 that was eliminated from ES5.

X

x

Blah. See hexadecimal base 16.

XML

XML Extensible Markup Language is a document format based on SGML. It is often misused as a data format. See http://www.w3.org/TR/REC-xml.

xor exclusive or

Blah. See ^ infix operator bitwise exclusive or and ^= assignment infix operator bitwise exclusive or.

XSS Cross Site Scripting Attack

Blah.

Y

y

y regexp flag

Blah.

y combinator

Blah.

function y(e) {
    return (function (f) {
        return f(f);
    }(function (f) {
        return e(function (x) {
            return f(f)(x);
        });
    }));
}

var factorial = y(function (recur) {
    return function (n) {
        return (n <= 2) 
            ? n 
            : n * recur(n - 1);
    };
});

var number120 = factorial(5);

yield reserved word

yield operator

Blah. See function *.

Z

zero

There are two representation of the number zero: 0 and -0. There are almost no observable differences between them.

0 === -0            // true
0 > -0              // false
1 + -0              // 1
String(-0)          // "0"

Unfortunately, there is an observable difference.

1 / 0               // Infinity
1 / -0              // -Infinity
1 / 0 === 1 / -0    // false

Also, the max Math function maximum and min Math function minimum distinguish between 0 and -0. Because that difference is observable, we can determine that the * infix operator multiply can produce -0.

 1 * -0             // -0
-1 *  0             // -0

Contributors

This chapter will acknowledge the contributors to this book.