Jsspec PDF
Jsspec PDF
JavaScript 1.1
10/3/96
Contents
11 11
Chapter 1 Introduction ............................................................................... 11 1.1 Versions and Implementations ..................................................................... 11 1.2 Grammar Notation......................................................................................... 11 1.3 Example Programs ........................................................................................ 13 1.4 References...................................................................................................... 13
15 15
Chapter 2 Lexical Structure ....................................................................... 15 2.1 ASCII .............................................................................................................. 15 2.2 Lexical Translations ....................................................................................... 15 2.3 Line Terminators............................................................................................ 16 2.4 Input Elements and Tokens.......................................................................... 16 2.4.1 White Space........................................................................................... 17 2.4.2 Semicolons............................................................................................. 17 2.4.3 Comments.............................................................................................. 17 2.5 Keywords....................................................................................................... 19 2.6 Identifiers ....................................................................................................... 20 2.7 Literals............................................................................................................ 20 2.7.1 Integer Literals....................................................................................... 21
Contents iii
2.7.2 Floating-Point Literals ........................................................................... 22 2.7.3 Boolean Literals..................................................................................... 23 2.7.4 String Literals ......................................................................................... 23 2.7.5 Escape Sequences for String Literals.................................................... 24 2.7.6 The Null Literal ..................................................................................... 25 2.8 Separators ...................................................................................................... 25 2.9 Operators....................................................................................................... 25
27 27
Chapter 3 Types, Values, and Variables ................................................ 27 3.1 Types ............................................................................................................. 27 3.1.1 Type Names .......................................................................................... 28 3.1.2 Type Conversion................................................................................... 28 3.1.3 The toString method ............................................................................. 30 3.1.4 The valueOf Method............................................................................. 31 3.2 Primitive Types and Values .......................................................................... 31 3.2.1 Numeric Types and Values .................................................................. 31 3.2.2 Numeric Operations.............................................................................. 32 3.2.2.1 Bitwise integer operations .......................................................... 34 3.2.3 Boolean Types and Values................................................................... 34 3.2.4 Boolean Operations .............................................................................. 34 3.2.5 The Undefined Type............................................................................. 35 3.3 Reference Types and Values ........................................................................ 35 3.3.1 Object Types and Operations .............................................................. 36 3.3.1.1 The Null Object ........................................................................... 36 3.3.1.2 The Delete Operator ................................................................... 36 3.3.1.3 The Void Operator ...................................................................... 36 3.3.2 String Types and Operations................................................................ 36 3.3.3 Function Types...................................................................................... 37 3.4 Variables ........................................................................................................ 38 3.4.1 Kinds of Variables................................................................................. 38 3.4.2 Initial Values of Variables..................................................................... 38
3.5 Names ............................................................................................................ 39 3.5.1 Declarations and Scoping ..................................................................... 39 3.5.2 Hiding Names........................................................................................ 40
41 41
Chapter 4 Expressions ................................................................................ 41 4.1 Evaluation, Denotation and Result ............................................................... 41 4.2 Evaluation Order ........................................................................................... 42 4.3 Primary Expressions ...................................................................................... 42 4.3.1 Literals.................................................................................................... 43 4.3.2 this ......................................................................................................... 43 4.4 Function Invocation Expressions ................................................................. 43 4.4.1 Runtime Evaluation ............................................................................... 43 4.4.1.1 Compute Target Reference.......................................................... 44 4.4.1.2 Evaluate Arguments ..................................................................... 44 4.4.1.3 Locate Function to Invoke .......................................................... 44 4.5 Postfix Expressions........................................................................................ 44 4.5.1 Postfix Increment Operator ++............................................................. 45 4.5.2 Postfix Decrement Operator -- ............................................................. 45 4.6 Unary Operators............................................................................................ 45 4.6.1 Prefix Increment Operator ++ .............................................................. 46 4.6.2 Prefix Decrement Operator --............................................................... 46 4.6.3 Unary Minus Operator -........................................................................ 47 4.6.4 Bitwise Complement Operator ~ ......................................................... 47 4.6.5 Logical Complement Operator ! ........................................................... 47 4.7 Multiplicative Operators................................................................................ 48 4.7.1 Multiplication Operator * ...................................................................... 48 4.7.2 Division Operator /............................................................................... 49 4.7.3 Remainder Operator % ......................................................................... 50 4.8 Additive Operators ........................................................................................ 51 4.8.1 String Concatenation Operator + ......................................................... 51 4.8.1.1 String Conversion......................................................................... 52 4.8.1.2 Examples of String Concatenation .............................................. 52
Contents v
4.8.2 Additive Operators (+ and -) for Numeric Types................................ 52 4.9 Shift Operators .............................................................................................. 53 4.10 Relational Operators ................................................................................... 54 4.10.1 Numerical Comparison Operators ..................................................... 55 4.11 Equality Operators ...................................................................................... 56 4.11.1 Numerical Equality Operators == and !=........................................... 56 4.11.2 Boolean Equality Operators............................................................... 57 4.12 Bitwise and Logical Operators ................................................................... 58 4.12.1 Integer Bitwise Operators .................................................................. 58 4.12.2 Boolean Logical Operators................................................................. 59 4.13 Conditional-And Operator.......................................................................... 59 4.14 Conditional-Or Operator ............................................................................ 60 4.15 Conditional Operator ? : ............................................................................. 60 4.16 Assignment Operators ................................................................................ 61 4.16.1 Simple Assignment Operator =.......................................................... 62 4.17 Special operators ........................................................................................ 62 4.17.1 The new operator ............................................................................... 62 4.17.2 The delete operator ............................................................................ 63 4.17.3 The typeof operator ........................................................................... 63 4.17.4 The void operator............................................................................... 64
65 65
Chapter 5 Object Model .............................................................................. 65 5.1 Functions ....................................................................................................... 65 5.1.1 Definition............................................................................................... 66 5.1.2 Invocation.............................................................................................. 66 5.1.3 The caller property ............................................................................... 67 5.1.4 The arguments array ............................................................................. 67 5.2 This ................................................................................................................ 67 5.3 Constructor Functions ................................................................................... 68 5.3.1 Associative Arrays ................................................................................. 69 5.3.2 Object prototypes ................................................................................. 69 5.3.3 Defining methods ................................................................................. 70
73 73
Chapter 6 Blocks and Statements ............................................................ 73 6.1 Normal and Abrupt Completion of Statements ........................................... 73 6.2 Blocks ............................................................................................................ 74 6.3 Variable Declaration Statements................................................................... 74 6.4 Statements...................................................................................................... 75 6.4.1 The Empty Statement............................................................................ 75 6.4.2 The if Statement .................................................................................... 76 6.4.3 The while Statement ............................................................................. 76 6.4.3.1 Abrupt Completion ...................................................................... 77 6.4.4 The for Statement.................................................................................. 77 6.4.4.1 Initialization.................................................................................. 78 6.4.4.2 Iteration ........................................................................................ 78 6.4.4.3 Abrupt Completion ...................................................................... 79 6.4.5 The break Statement ............................................................................. 79 6.4.6 The continue Statement ........................................................................ 80 6.4.7 The return Statement ............................................................................ 80 6.4.8 The with Statement ............................................................................... 80 6.4.9 The for...in Statement............................................................................ 81 6.4.10 Function Definition Statement ........................................................... 82
83 83
Chapter 7 Built-in Functions and Objects ............................................ 83 7.1 Built-in functions ........................................................................................... 83 7.1.1 eval......................................................................................................... 83 7.1.2 parseInt .................................................................................................. 85 7.1.3 parseFloat .............................................................................................. 86 7.1.4 escape .................................................................................................... 87 7.1.5 unescape................................................................................................ 87 7.2 Array Object................................................................................................... 88 7.2.1 Constructors........................................................................................... 88
Contents vii
7.2.2 Properties .............................................................................................. 89 7.2.2.1 length ........................................................................................... 89 7.2.3 Methods ................................................................................................. 89 7.2.3.1 join................................................................................................ 90 7.2.3.2 reverse.......................................................................................... 90 7.2.3.3 sort................................................................................................ 90 7.3 Boolean Object.............................................................................................. 91 7.3.1 Constructors .......................................................................................... 91 7.3.2 Properties .............................................................................................. 91 7.3.3 Methods ................................................................................................. 91 7.4 Date Object.................................................................................................... 91 7.4.1 Constructors .......................................................................................... 92 7.4.2 Properties .............................................................................................. 93 7.4.3 Methods ................................................................................................. 93 7.4.3.1 parse............................................................................................. 93 7.4.3.2 setDate ......................................................................................... 94 7.4.3.3 setHours ....................................................................................... 94 7.4.3.4 setMinutes .................................................................................... 94 7.4.3.5 setMonth....................................................................................... 95 7.4.3.6 setSeconds.................................................................................... 95 7.4.3.7 setTime......................................................................................... 95 7.4.3.8 setYear.......................................................................................... 96 7.4.3.9 toGMTString ................................................................................. 96 7.4.3.10 toLocaleString ............................................................................ 96 7.4.3.11 UTC ............................................................................................ 97 7.5 Math Object ................................................................................................... 97 7.5.1 Constructors .......................................................................................... 97 7.5.2 Properties .............................................................................................. 98 7.5.2.1 E.................................................................................................... 98 7.5.2.2 LN2 ............................................................................................... 98 7.5.2.3 LN10 ............................................................................................. 98 7.5.2.4 LOG2E .......................................................................................... 98 7.5.2.5 LOG10E ........................................................................................ 98
7.5.2.6 PI .................................................................................................. 98 7.5.2.7 SQRT1_2....................................................................................... 99 7.5.2.8 SQRT2........................................................................................... 99 7.5.3 Methods ................................................................................................. 99 7.5.3.1 abs ................................................................................................ 99 7.5.3.2 acos............................................................................................... 99 7.5.3.3 asin ............................................................................................. 100 7.5.3.4 atan ............................................................................................. 100 7.5.3.5 atan2 ........................................................................................... 100 7.5.3.6 ceil .............................................................................................. 100 7.5.3.7 cos .............................................................................................. 100 7.5.3.8 exp.............................................................................................. 101 7.5.3.9 log............................................................................................... 101 7.5.3.10 max .......................................................................................... 101 7.5.3.11 min ........................................................................................... 101 7.5.3.12 pow .......................................................................................... 101 7.5.3.13 random..................................................................................... 102 7.5.3.14 round........................................................................................ 102 7.5.3.15 sin............................................................................................. 102 7.5.3.16 sqrt ........................................................................................... 102 7.5.3.17 tan ............................................................................................ 102 7.6 Number Object ............................................................................................ 103 7.6.1 Constructors......................................................................................... 103 7.6.2 Properties............................................................................................. 103 7.6.2.1 MAX_VALUE .............................................................................. 103 7.6.2.2 MIN_VALUE ............................................................................... 103 7.6.2.3 NaN............................................................................................. 103 7.6.3 Methods ............................................................................................... 104 7.7 String Object ................................................................................................ 104 7.7.1 Constructors......................................................................................... 104 7.7.2 Properties............................................................................................. 104 7.7.2.1 length.......................................................................................... 104 7.7.3 Methods ............................................................................................... 105
Contents ix
indexOf ...................................................................................... 105 lastIndexOf................................................................................. 105 substring..................................................................................... 106 charAt ......................................................................................... 107 toLowerCase............................................................................... 107 toUpperCase .............................................................................. 108 split............................................................................................. 108
Chapter
1
1 Introduction
JavaScript is a compact, platform-indpendent, object-based scripting language.
Chapter 1, Introduction 11
Grammar Notation
Nonterminal symbols are shown in italic fixed width font. The definition of a nonterminal is introduced by the name of the nonterminal followed by a colon. One or more alternative right-hand sides for the nonterminal then follow on succeeding lines. For example, the syntactic definition:
IfThenStatement: if ( Expression ) Statement
states that the nonterminal IfThenStatement represents the token if, followed by a left parenthesis token, followed by an Expression, followed by a right parenthesis token, followed by a Statement. As another example, the syntactic definition:
ArgumentList: Argument ArgumentList , Argument
states that an ArgumentList may represent either a single Argument or an ArgumentList, followed by a comma, followed by an Argument. This definition of ArgumentList is recursive, that is to say, it is defined in terms of itself. The result is that an ArgumentList may contain any positive number of arguments. Such recursive definitions of nonterminals are common. The subscripted suffix opt, which may appear after a terminal or nonterminal, indicates an optional symbol. The alternative containing the optional symbol actually specifies two right-hand sides, one that omits the optional element and one that includes it. So, for example:
ReturnStatement: return Expressionopt
is an abbreviation for:
ReturnStatement: return return Expression
When the words "one of" follow the colon in a grammar definition, they signify that each of the terminal symbols or tokens on the following line or lines is an alternative definition. For example:
OctalDigit: one of 0 1 2 3 4 5 6 7
12
Example Programs
2 3 4 5 6 7
The right-hand side of a lexical production may indicate that certain expansions are not permitted by using the phrase "but not" and then naming the excluded expansions, as in the productions for Identifier:
Identifier: IdentifierName, but not a Keyword or BooleanLiteral or NullLiteral
Finally, a few nonterminal symbols are described by a descriptive phrase where it would be impractical to list all the alternatives, for example:
RawInputCharacter: any ASCII character
This function is intended for illustrative and pedagogical purposes only, and is not part of the language specification.
1.4 References
Bobrow, Daniel G., Linda G. Demichiel, Richard P. Gabriel, Sonya E. Keene, Gregor Kiczales, and David A. Moon. Common Lisp Object System Specification, X3J13 Document 88-002R, June 1988; appears as Chapter 28 of Steele, Guy. Common Lisp: The Language, 2nd ed. Digital Press, 1990, ISBN 1-55558-041-6, 770-864.
Chapter 1, Introduction 13
References
IEEE Standard for Binary Floating-Point Arithmetic. ANSI/IEEE Std. 754-1985. Available from Global Engineering Documents, 15 Inverness Way East, Englewood, Colorado 80112-5704 USA; 800-854-7179. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd ed. Prentice Hall, Englewood Cliffs, New Jersey, 1988, ISBN 0-13-110362-8. Gosling, James, Bill Joy, and Guy Steele. The Java Language Specification. Addison Wesley Publishing Company, 1996 Cardelli, et. al. Modula-3 Report (revised). Digital Equipment Corporation, 1989, Palo Alto, California Agesen, et. al. The Self 3.0 Programmers Reference Manual. Sun Microsystems, 1993, Mountain View, California. Stroustrup, Bjarne. The C++ Progamming Language, 2nd ed. Addison-Wesley, Reading, Massachusetts, 1991, reprinted with corrections January 1994, ISBN 0201-53992-6.
14
Chapter
2
2 Lexical Structure
This chapter describes the lexical structure of JavaScript by specifying the languages lexical grammar.
2.1 ASCII
JavaScript programs are written using ASCII, the American Standard Code for Information Interchange (defined by ANSI standard X3.4).
A translation of the ASCII character stream into a stream of input characters and line terminators. A translation of the stream of input characters and line terminators into a sequence of JavaScript input elements which, after white space and comments are discarded, comprise the tokens that are the terminal symbols of the syntactic grammar for JavaScript.
2.
Line Terminators
In these lexical translations JavaScript chooses the longest possible translation at each step, even if the result does not ultimately make a correct JavaScript program, while another lexical translation would.
The result of this step is a sequence of line terminators and input characters, which are the terminal symbols for the second step in the tokenization process.
Token
WhiteSpace: the ASCII SP character, also known as "space" the ASCII HT character, also known as "horizontal tab" the ASCII FF character, also known as "form feed" LineTerminator Token: Keyword Identifier Literal Separator Operator
White space and comments can serve to separate tokens that, if adjacent, might be tokenized in another manner. For example, the characters - and = in the input can form the operator token -= only if there is no intervening white space or comment.
2.4.2 Semicolons
The ASCII Semicolon character (;) separates multiple statements on a single line. Unlike Java, a semicolon is not required to terminate a statement. This is equivalent to compile-time error-correction in which JavaScript inserts semicolons as neccessary. Complete lexcical specification of semicolons TBD.
2.4.3 Comments
JavaScript has two kinds of comments: A traditional comment: all the text from /* to */ is ignored (as in C):
/* text */
A single-line comment: all the text from // to the end of the line is ignored (as in C++):
// text
The grammar implies all of the following properties: Multi-line comments cannot be nested /* and */ have no special meaning in // comments. // has no special meaning in either single-line or multi-line comments As a result, these are legal comments:
/* this comment // ends here: */ // This // just /* fine */ as far as JavaScript // is concerned
Keywords
2.5 Keywords
The following sequences of ASCII letters are reserved for use as keywords, and are not legal identifiers:
Keyword: one of
abstract boolean break byte case catch char class const continue default do double
else extends false final finally float for function goto if implements import in
instanceof int interface long native new null package private protected public return short static
super switch synchronized this throw throws transient true try var void while with
The above list includes all keywords used and reserved for future use. The following table lists keywords currently used in JavaScript:
break continue delete else false for function if in new null return this true var void while with
Identifiers
While true and false might appear to be keywords, they are technically Boolean literals; while null might appear to be a keyword, it is technically an object reference.
2.6 Identifiers
An identifier is an unlimited length sequence of ASCII letters and digits, the first of which must be a letter. The letters include uppercase and lowercase ASCII letters (a-z and A-Z) and the ASCII underscore (_) and dollar sign ($). The digits include the ASCII digits 0-9.
Identifier: IdentifierName, but not a Keyword or BooleanLiteral or NullLiteral IdentifierName: JavaScriptLetter GraphicCharacter JavaScriptLetter: any uppercase or lowercase ASCII letter (a-z, A-Z) any digit (0-9) _ $ GraphicCharacter: any symbol in the set: ~!@#%^&*()-+={[}]|\:<,>.?/
2.7 Literals
A literal is the source code representation of a value of a primitive type:
Literal: IntegerLiteral FloatingPointLiteral BooleanLiteral StringLiteral NullLiteral
Literals
A decimal literal consists of a digit from 1 to 9, optionally followed by one or more digits from 0 to 9, and represents a positive integer:
DecimalLiteral: 0 NonZeroDigit Digitsopt Digits: Digit Digits Digit Digit: 0 NonZeroDigit NonZeroDigit: one of 1 2 3 4 5 6 7 8 9
A hexadecimal literal consists of a leading 0x or 0X followed by one or more hexadecimal digits and can represent a positive, zero, or negative integer. Hexadecimal digits with values 10 through 15 are represented by the letters a through f or A through F, respectively; each letter used as a hexadecimal digit may be uppercase or lowercase.
HexLiteral: 0x HexDigit 0X HexDigit HexLiteral HexDigit HexDigit: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
An octal literal consists of a digit 0 followed by one or more of the digits 0 through 7 and can represent a positive, zero, or negative integer.
OctalLiteral: 0 OctalDigit OctalLiteral OctalDigit OctalDigit: one of 0 1 2 3 4 5 6 7
Literals
The largest positive hexadecimal and octal literals of type int are 0x7fffffff and 017777777777, respectively, which equal 2147483647. The most negative hexadecimal and octal literals of type int are 0x80000000 and 020000000000 respectively, each of which represents the decimal value -2147483648. The hexadecimal and octal literals 0xffffffff and 037777777777, respectively, represent the decimal value -1. Examples of integer literals:
0 2 0372 0xDeadBeef 1996 0x00FF00FF
The largest positive finite number is 1.79769313486231570e+308. Numbers greater than this are represented by the literals +Infinity (for positive numbers) and -Infinty (for negative numbers).
Literals
The constant NaN represents a value that is Not-a-Number. Examples of floating-point literals are:
1e1 2. .3 0.0 3.14 1e-9
The escape sequences are described in section 2.7.5 Escape Sequences for String Literals.
Literals
It is a compile-time error for a line terminator to appear after the opening " and before the closing matching ". A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator +. Examples of string literals:
"" "\"" This is a string "This is a " + "two-line string" // The empty string // A string containing " alone // A string containing 16 characters // Actually a string-valued expression // containing two string literals
Separators
null
2.8 Separators
The following characters are used in JavaScript as separators (punctuators):
Separator: one of ( ) { } [ ] , .
2.9 Operators
The following tokens are used in JavaScript as operators:
Operator: one of = > < ! ~ ? : == <= >= != && || ++ -+ - * / & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>= >>>=
Operators
Chapter
3
3 Types, Values, and Variables
JavaScript is a dynamically-typed language, which means that the datatypes of variables are not declared, and the datatypes of variables and expressions are determined at run time.
3.1 Types
There are two kinds of types in JavaScript: primitive types and reference types. There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values and reference values.
Type: PrimitiveType ReferenceType
JavaScripts primitive data types are boolean and number; its reference types are string, object (including the null object), and function. Strings have primitive equality and relational operator semantics. The boolean type has the truth values true and false. A number can be either an integer or floating-point; JavaScript does not explicitly distinguish between them. Integers are 32-bit signed two's-complement integers and floating-point numbers are 64-bit IEEE 754 floating-point numbers.
Types
An object in JavaScript is a container that associates names and indexes with data of arbitrary type. These associations are called properties. Properties with function values are called the objects methods.
28
Types
To type
function undefined function object (not null) (null) number (zero) (nonzero) (NaN) (+Infinity) (-Infinity) Boolean (false) (true) string (empty) (nonempty) error N/C object null number error boolean false error valueof/true false string undefined decompile toString/valueOf/default* null 0 default* NaN +Infinity -Infinity false true N/C
From type
N/C
0 1
error false number (if true string is numeric literal) else error
Key: N/C - No conversion neccessary. decompile - a string containing the functions canonical source toString - the result of the toString method valueOf - The valueof function is tried, and if it returns a value, that value is used. *default: object - [object name] where name is constructor function name number - Numeric value parsed from string, if possible; see Number.toString() Explanation of key TBD.
Types
Examples
For example,
function f() { return 42 } function Car(make, model, year) { this.make = make this.model = model this.year = year } objnull = null o = new Car("Ford", "Mustang", 1969) posInfinity = 10*1e308 d = new Date() n0 = 0 n1 = 123 println(true.toString()) println(false.toString()) println(f.toString()) println(objnull) println(d.toString) println(Math.toString) println(o.toString()) println(n0.toString()) println(n1.toString()) println(posInfinity.toString())
30
Datatypes are not declared, and a variable can change type as different values are assigned to it. A number can be either an integer or a floating-point number.
Except for NaN, numeric values are ordered; arranged from smallest to largest, they are negative infinity, negative finite values, negative zero, positive zero, positive finite values, and positive infinity. NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both of their operands are NaN . The numerical equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN . In particular, x==x is false if and only if x is NaN, and (x<y)==!(x>=y) will be false if x or y is NaN.JavaScript provides a number of operators that act on numeric values. These operators treat their operands as 64-bit floating-point values.
32
JavaScript requires that floating-point arithmetic behave as if every floatingpoint operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standards default rounding mode known as round to nearest. An operation that overflows produces a signed infinity, an operation that underflows produces a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. Since NaN is unordered, a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN. The following example illustrates:
// an example of overflow: d = 1e308 println("overflow produces infinity: ") println(d + "*10==" + d*10) println("") // an example of gradual underflow: d = 1e-305 * Math.PI println("gradual underflow: ") println(d) for (i = 0; i < 4; i++) println(d /= 100000) println("") // an example of NaN: d = 0.0/0.0 println("0.0/0.0 is Not-a-Number: ", d) println("") // an example of inexact results and rounding: println("inexact results with floating point arithmetic:") for (i = 0; i < 100; i++) { z = 1.0/i if (z*i != 1.0) println(i) }
3.1415926535898e-310 3.141592653e-315 3.142e-320 0 0.0/0.0 is Not-a-Number: NaN inexact results with floating point arithmetic: 49 98
This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision. Note that when i is zero, z is NaN, and z*i is NaN.
34
The logical-or and logical-and operators && and || The conditional operator ? : Boolean expressions control the control flow in: The if statement The while statement The for statement When they do so, they determine which subexpression is chosen to be evaluated in the conditional ? : operator . Only Boolean expressions can be used in the control flow statements and as the first operand of the conditional operator ? :. A number is converted to a Boolean value following the C language convention that zero is false and any nonzero value is true, An object is converted to a Boolean, following the C language convention that the null object is false and any object other than null is true.
36
Relational and equality operators (==, >, <, >=, <=) that compare the lexicographical precedence of their operands and return a logical value. Note the reference-type behavior for assignment operations, but not for equality and relational operations.
where block is the set of statements that defines the body of the function.
Examples
Here is a standard declaration of a simple factorial function:
function factorial(n) { if ((n <= 1)) return 1 else return (n * factorial(n-1) ) }
Variables
3.4 Variables
A variable is a storage location for a value and has an associated type, determined at run-time. A variables value is changed by an assignment, by a prefix or postfix ++ (increment) or -- (decrement) operator, or by the delete operator.
38
Names
3.5 Names
A name is used to refer to an entity declared in a JavaScript program. A declared entity is a variable or a function. There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier; it is used when an identifier is associated with an object. In determining the meaning of a name, JavaScript takes into account the context in which the name appears. It distinguishes among contexts where a name must denote (refer to) a type, a variable or value in an expression, or a function. Not all identifiers in JavaScript programs are a part of a name. Identifiers are also used in the following situations: In declarations, where an identifier occurs to specify the name by which the declared entity will be known In property expressions, where an identifier occurs after a "." token to indicate a member of an object that is the value of an expression In method invocation expressions, where an identifier occurs after a "." token and before a "(" token to indicate a method to be invoked for an object that is the value of an expression
A variable declared outside a function is a global variable, and is accessible everywhere in the global scope. A variable declared by assignment inside a function is also a global variable. A variable declared with var inside a function is a local variable, and is accessible only within that function.
Names
40
Chapter
4
4 Expressions
This chapter specifies the meaning of JavaScript expressions and the rules for their evaluation.
Chapter 4, Expressions 41
Evaluation Order
If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, when the expression denotes a variable or a value, we may speak simply of the value of the expression.
Need clarification of this example. Every operand of an operator (except for the conditional operators &&, ||, and ? :) is fully evaluated before any part of the operation itself is performed. In a function or constructor invocation, one or more argument expressions may appear within the parentheses, separated by commas. Each argument expression is fully evaluated before any part of any argument expression to its right is evaluated.
4.3.1 Literals
A literal denotes a fixed, unchanging value. The following production from Chapter 2 is repeated here for convenience:
Literal: IntegerLiteral FloatingPointLiteral BooleanLiteral StringLiteral NullLiteral
4.3.2 this
The keyword this denotes a reference to the invoking object, or to the object being constructed in a constructor function. The invoking object is defined as the object name to the left of the period . or left bracket [ in a method invocation, otherwise it is the parent object of the function.
Chapter 4, Expressions 43
Postfix Expressions
A target reference may be computed. The argument expressions are evaluated. The actual code for the function is executed.
Unary Operators
A postfix expression followed by a ++ operator is a postfix increment expression. The operand must be convertible into a number, and thus the result of the operation must be a variable of type number or a run-time error occurs. The result of the postfix increment expression is not a variable, but a value. At run time, the value 1 is added to the value of the variable and the sum is stored back into the variable. The value of the postfix increment expression is the value of the variable before the new value is stored.
A postfix expression followed by a -- operator is a postfix decrement expression. The operand must be convertible into a number, and thus the result of the operation must be a variable of type number or a run-time error occurs. The result of the postfix decrement expression is not a variable, but a value. At run time, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. The value of the postfix decrement expression is the value of the variable before the new value is stored.
Chapter 4, Expressions 45
Unary Operators
PreIncrementExpression PreDecrementExpression - UnaryExpression UnaryExpressionNotPlusMinus PreIncrementExpression: ++ UnaryExpression PreDecrementExpression: -- UnaryExpression UnaryExpressionNotPlusMinus: PostfixExpression ~ UnaryExpression ! UnaryExpression
4.6.2 Prefix Decrement Operator -A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of type number or a run-time error occurs. The result of the prefix decrement expression is not a variable, but a value. At run time, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. The value of the prefix decrement expression is the value of the variable after the new value is stored.
Unary Operators
4.6.3 Unary Minus Operator The operand expression of the unary - operator must be convertible to a number or a run-time error occurs. At run-time, the value of the unary plus expression is the arithmetic negation of the converted value of the operand. For integer values, negation is the same as subtraction from zero. JavaScript uses twos-complement representation for integers, and the range of twoscomplement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case. For all integer values x, -x equals (~x)+1. Special cases are: If the operand is NaN, the result is NaN (recall that NaN has no sign). If the operand is an infinity, the result is the infinity of opposite sign.
Chapter 4, Expressions 47
Multiplicative Operators
The type of each of the operands of a multiplicative operator must be a primitive numeric type or a run-time error occurs.
Multiplicative Operators
small to represent, the result is then a zero of appropriate sign. The JavaScript language requires support of gradual underflow as defined by IEEE 754.
Chapter 4, Expressions 49
Multiplicative Operators
Examples
5%3 produces 2
Additive Operators
5%(-3) produces 2 (-5)%3 produces -2 (-5)%(-3) produces -2 5.2345%3.0 produces 2.2345 5.0%(-3.0) produces 2.0 (-5.0)%3.0 produces -2.0 (-5.0)%(-3.0) produces -2.0
In an AdditiveExpression, if either of the operands is of type string, then the other operand is convered to a string and the operation is a string concatenation operation (see 4.8.1 String Concatenation Operator +). If one of the operands is of type boolean, then it is converted to a number (true becomes 1 and false becomes 0).
Chapter 4, Expressions 51
Additive Operators
The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression: a + b + c is always regarded as meaning (a + b) + c. Therefore the result of the expression: 1 + 2 + " fiddlers" is "3 fiddlers" but the result of "fiddlers " + 1 + 2 is "fiddlers 12".
Shift Operators
The sum of two infinities of opposite sign is NaN. The sum of two infinities of the same sign is the infinity of that sign. The sum of an infinity and a finite value is equal to the infinite operand. The sum of two zeros is zero. The sum of a zero and a nonzero finite value is equal to the nonzero operand. The sum of two nonzero finite values of the same magnitude and opposite sign is zero. In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the sum is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode. If the magnitude is too large to represent, the operation overflows and the result is then an infinity of appropriate sign. If the magnitude is too small to represent, the operation underflows and the result is then zero. The JavaScript language requires support of gradual underflow as defined by IEEE 754. The binary - operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that a-b produces the same result as a+(-b).
Chapter 4, Expressions 53
Relational Operators
The type of each of the operands of a shift operator must be convertible to a primitive integral type or a run-time error occurs. At run time, shift operations are performed on the twos complement integer representation of the value of the left operand. The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s. The value of n>>s is n right-shifted s bit positions with sign-extension. For non-negative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s. The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value!)
Relational Operators
Chapter 4, Expressions 55
Equality Operators
The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus a<b==c<d is true whenever a<b and c<d have the same truth-value.The type of an equality expression is always boolean. In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative.
Equality Operators
The value produced by the != operator is true if the value of the left-hand operand is not equal to the value of the right-hand operand, and otherwise is false. For example,
x = 345 y = 345 z = 1 b1 = 2== 2== 1 b2 = 2 == 3 == 1 b3 = 2 == 3 == 0 b4 = 2 == 3 == false println("b1= " + b1) println("b2 = " + b2 ) println("b3 = " + b3 ) println("b4 = " + b4 )
Chapter 4, Expressions 57
The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a runtime error.
Conditional-And Operator
Each operand of && must be convertible to type boolean or a run-time error occurs. The type of a conditional-and expression is always boolean. At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the righthand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
Chapter 4, Expressions 59
Conditional-Or Operator
Each operand of || must be convertible to type boolean or a run-time error occurs. The type of a conditional-or expression is always boolean. At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression. Thus || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions. The first expression must be of type boolean or a run-time error occurs.
Assignment Operators
The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean. All other cases result in a run-time error. Note that it is not permitted for either the second or the third operand expression to be an invocation of a void function. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void function could appear At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression: If the value of the first operand is true, then the second operand expression is chosen. If the value of the first operand is false, then the third operand expression is chosen. The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
Chapter 4, Expressions 61
Special operators
The result of the first operand of an assignment operator must be a variable or a run-time error occurs. The type of the assignment expression is the type of the variable. At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
Special operators
The string returned is one of undefined object function number boolean string If the operand is a constructor, such as Date, the return value is function. For example,
typeof typeof typeof typeof typeof typeof foo returns "undefined" eval returns "function" null returns "object" 3.14 returns "number" true returns "boolean" "a string" returns "string" // where foo is undefined
Chapter 4, Expressions 63
Special operators
Chapter
5
5 Object Model
The framework for the JavaScript object model is built around constructor functions, that provide the underpinnings of the JavaScript object model. Built-in objects, that have pre-defined properties and methods. The new operator, that enables creation of new objects with specified property values object syntax: the way that an objects properties and methods are accessed as object.property, object.method, and object[index]. Formal conceptual framework TBD.
5.1 Functions
A function is a set of statements that performs a specific task. A function is defined by a function definition that specifies the functions name and the statements that it contains. A function is executed by a function invocation (also known as a function call).
Functions
5.1.1 Definition
A function definition provides: The name of the function The parameters of the function The statements performed by the function The syntax for defining a function is described in 6.4.10 Function Definition Statement. A function must be declared before it is invoked.
5.1.2 Invocation
A function invocation executes the statements in the function and optionally returns a value. It consists of a defined functions name, followed by a parameter list in parentheses.
functionInvocation: functionName(parameterListopt) parameterList: identifierName identifierName, parameterList
The number of arguments in an invocation does not have to match the number of arguments in the function definition. Each argument in the invocation will be matched from left to right with the arguments in the definition. Any argument in the definition for which there is no argument in the invocation will be undefined. If there are more arguments in the invocation than in the definition, then the extra arguments are accessible within the function using the arguments array; see 5.1.4 The arguments array. The value of a function invocation expression is the value of the expression following the return statement that returned control to the invocation, or undefined if there was no return statement or a return statement without an expression. Note that JavaScript does not require function arguments to be of any particular type.
This
It evaluates to the object or function that invoked the function. If the function call was a top-level invocation, that is, not made from within another function or from an object, then caller is null. Better description TBD.
where functionName is the name of the function and i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function named myfunc would be myfunc.arguments[0]. As for other arrays in JavaScript, the arguments array has a length property that indicates the number of elements in the array. Thus, within the body of the function, the actual number of arguments passed to a function is accessible as arguments.length . Since a a function can be invoked with more arguments than the number of parameters in its definition, the arguments array provides a way to access the excess arguments in the invocation.
5.2 This
The special keyword this is used to refer to the current object. The current object is defined as follows: in an eval expression, string argument What does this mean???
Constructor Functions
In a method, it is the object to which the method belongs. In a constructor function, it is the object being defined. In a top-level script, it is the top-level object defined by the particular JavaScript implementation. For example, in Netscape Navigator, the top-level object is the window object.
Each memberAssignment statement defines a property or method of the object. If the value assigned is an object, string, number, or Boolean, then the memberAssignment defines a property. If identifierName corresponds to a function name in the current scope, then the propertyAssignment defines a method of the object. Frequently, an identifierName in a memberAssignment will correspond to one of the identifierNames in the constructors parameterList, such that the values to be assigned are passed as parameters to the constructor function.
Constructor Functions
are equivalent.
Set the value of constructor.prototype.propertyName to define a property that is shared by all objects of the specified type, where constructor is the name of the constructor function and propertyName is the name of the property.
Examples
function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } function new_rep(n) { return "repeat " + this + " " + n + " times." } String.prototype.rep = str_rep //add a rep() method to String s1 = new String("a") s2 = new String("b") println(s1.rep(3)) println(s2.rep(7))
Constructor Functions
where object is an existing object, methodname is the name being assigned to the method, and function_name is the name of the function. The method can then be called in the context of the object as follows:
object.methodName(parameterList)
Example
To format and display the properties of the previously-defined Car objects, the user would define a method called displayCar based on a function called display by modifying the constructor function as follows:
function car(make, model, year, owner) { this.make = make this.model = model this.year = year this.owner = owner this.displayCar = display }
Then the displayCar method can be called for each of the objects as follows:
Object Creation
car1.displayCar() car2.displayCar()
Example
The following user-defined constructor functions create a Person object with member properties name, age, and sex and a Car object with member properties make, model, year, and owner. Then, two Person objects are created with the new operator, and two Car objects are created. Notice the use of the objects john and fred as arguments to the Car constructor functions. This is an example of members of object type.
function Person(name, age, sex) { this.name = name this.age = age this.sex = sex } function Car(make, model, year, owner) { this.make = make this.model = model this.year = year this.owner = owner } john = new Person("John", 33, "M") fred = new Person("Fred", 39, "M") car1 = new Car("Eagle", "Talon TSi", 1993, john) car2 = new Car("Nissan", "300ZX", 1992, fred)
Object Creation
Chapter
6
6 Blocks and Statements
The sequence of execution of a JavaScript program is controlled by statements, which are executed for their effect and do not have values. The first section of this chapter discusses the distinction between normal and abrupt completion of statements. Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.
Blocks
Unless otherwise specified, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, and all succeeding steps in the normal mode of execution are not performed. Unless otherwise specified, a statement completes normally if all substatements it executes complete normally.
6.2 Blocks
A block is a sequence of statements and variable declarations statements within braces.
Block: Statement { BlockStatementsopt } BlockStatements: BlockStatement BlockStatements BlockStatement BlockStatement: VariableDeclarationStatement Statement
A block is executed by executing each of the variable declarations and statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly.
Statements
var VariableDeclarators
A variable declaration can also appear in the header of a for statement. In this case it is executed in the same manner as if it were part of a variable declaration statement. Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator. If the variable is assigned a value, the variable assumes the type compatible with that value, otherwise it is undefined. The scope of variable declarations is described in 3.5.1 Declarations and Scoping.
6.4 Statements
Some of the statements in the JavaScript language correspond to statements in Java, but some are unique to JavaScript.
Statement: EmptyStatement IfThenStatement WhileStatement ForStatement BreakStatement ContinueStatement ReturnStatement WithStatement ForInStatement
Statements
EmptyStatement: ;
The Expression must be defined, or a run-time error occurs. The Expression is evaluated: If the value of Expression is true, then the first Block is executed. If the value of Expression is false, and there is no else clause, then no further action is taken. If there is an else clause, then the Block after the else keyword is executed. Because JavaScript parses top-down, it does not encounter any ambiguity. in this statement:
if condition1 if Ccndition2 Statement1 else Statement2
The JavaScript top-down parser can determine that the else goes with the second if statement to form an if-else.
Statements
A while statement is executed by first evaluating the Expression: If the value is true, then the Block is executed. Then there is a choice: If execution of the Block completed normally, then the entire while statement is executed again, beginning by re-evaluating the Expression. If execution of the Block completed abruptly, see below. If the value of the Expression is false, no further action is taken and the while statement completes normally. If the value of the Expression is false the first time it is evaluated, then the Block is not executed.
Statements
6.4.4.1 Initialization
A for statement is executed by first executing the ForInit code: If the ForInit code is a list of statement expressions, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForInit code is a variable declaration, it is executed as if it were a variable declaration statement appearing in a block. In this case, the scope of a declared variable is its own initializer, any further declarators in the ForInit part, plus the Expression, ForUpdate, and contained Statement of the for statement. If the ForInit part is not present, no action is taken.
6.4.4.2 Iteration
Next a for iteration step is performed, as follows: If the Expression is present, it is evaluated, and there is then a choice based on the presence or absence of the Expression and the resulting value if the Expression is present: If the Expression is not present, or it is present and the value resulting from its evaluation is true, then the contained Block is executed. Then there is a choice: If execution of the Block completed normally, then the following two steps are performed in sequence: First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForUpdate part is not present, no action is taken. Second, another for iteration step is performed. If execution of the Block completed abruptly, see below.
Statements
If the Expression is present and the value resulting from its evaluation is false, no further action is taken and the for statement completes normally. If the value of the Expression is false the first time it is evaluated, then the Block is not executed. If the Expression is not present, then the for statement cannot complete normally; only abrupt completion (such as use of a break statement) can terminate its execution.
A break statement transfers control to the innermost enclosing while or for statement; this statement, called the break target, then immediately completes normally. If no while or for statement encloses the break statement, a runtime error occurs. A break statement always completes abruptly.
Statements
Example TBD.
A continue statement transfers control to the innermost enclosing while or for statement; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one. If no while or for statement encloses the continue statement, a run-time error occurs. A continue statement always completes abruptly. Example TBD.
A return statement with an Expression must be contained in a function definition or a run-time error occurs. A return statement with an Expression transfers control to the invoker of the function; the value of the Expression becomes the value of the funciton invocation.
Statements
object specifies the default object to use for the statements. The parentheses around object are required. statements is any block of statements. When with statements are nested, the outermost statement defines the default top-level object; the next with statement defines the next level object, and so on. Better description of scoping TBD.
Example
The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.
var a, x, y var r=10 with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2) }
ObjectReference is an identifier that is the object for which the properties are iterated.
Statements
Example
The following function takes as its argument an object and the objects name. It then iterates over all the objects properties and returns a string that lists the property names and their values. This example accesses object properties as elements of an associative array, as described in 5.3.1 Associative Arrays.
function dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<BR>" } return result }
A function declaration statement cannot be nested inside another a function declaration statement or any other statement. Primitive values are passed to functions by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.
Example
function factorial(n) { if (n<=1) return 1 else return (n * factorial(n-1) ) }
Built-in functions
Chapter
7
7 Built-in Functions and Objects
JavaScript also has several top-level built-in functions. JavaScript also has four built-in objects: Array, Date, Math, and String. Each object has special-purpose properties and methods associated with it. JavaScript also has constructors for objects corresponding to the Boolean and numeric primitive types.
7.1.1 eval
Note: Need discussion of eval as method of other objects, eg. eval in scope of an object. Evaluates a string and returns a value.
eval(string)
Built-in functions
If the string argument represents a numeric or Boolean expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Otherwise, it generates a run-time error. The scope of execution is determined as follows: If the call to eval is preceded by a period and an object reference, this object is the scope. If there is no object to the left, then the scope is the object for which eval is defined. Otherwise, the scope is the innermost default scope (see 3.5.1 Declarations and Scoping). Clarification TBD.
Examples
Both of the println statements below display 42. The first evaluates the string x + y + 1, and the second evaluates the string 42.
var x = 2 var y = 39 var z = "42" println(eval("x + y + 1")) println(eval(z))
In the following example, the getFieldName function returns a string value that may represent a number or string. The second statement below uses eval to display the value of the form element.
var field = getFieldName(3) println("Field named ", field, " has value of ", eval(field + ".value"))
The following example uses eval to evaluate the string str. This string consists of JavaScript statements that do different things, depending on the value of x. When the second statement is executed, eval will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z.
var str = "if (x == 5) {z = 42; println("z is" + z);} else z = 0; " println("z is " + eval(str))
Built-in functions
7.1.2 parseInt
Parses a string argument and returns an integer of the specified radix or base. Syntax:
parseInt(string) parseInt(string, radix)
string is a string that represents the value you want to parse. radix is an integer that represents the radix of the return value. The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than ninr. For example, for hexadecimal numbers (base sixteen), A through F are used. If a radixes above 36 is specified, parseInt returns NaN. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. If the radix is not specified or is specified as zero, JavaScript assumes the following: If the input string begins with 0x, the radix is sixteen (hexadecimal). If the input string begins with 0, the radix is eight (octal). If the input string begins with any other value, the radix is ten (decimal). If the first character cannot be converted to a number, parseFloat returns NaN. For example, the following examples all return fifteen:
parseInt("F", 16) parseInt("17", 8) parseInt("15", 10) parseInt(15.99, 10) parseInt("FXX123", 16) parseInt("1111", 2) parseInt("15*3", 10)
Built-in functions
Even though the radix is specified differently, the following examples all return seventeen because the input string begins with 0x.
parseInt("0x11", 16) parseInt("0x11", 0) parseInt("0x11")
7.1.3 parseFloat
Parses a string argument and returns a floating point number. Syntax:
parseFloat(string)
string is a String object or literal. parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, parseFloat returns NaN. You can call the isNaN function to determine if the result of parseFloat is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN. For example, the following examples all return 3.14:
parseFloat("3.14") parseFloat("314e-2") parseFloat("0.0314E+2") var x = "3.14" parseFloat(x)
Built-in functions
7.1.4 escape
Returns the hexadecimal encoding of an argument in the ISO Latin-1 character set. Syntax:
escape("string")
string is a string in the ISO Latin-1 character set. The value returned by the escape function is one of the following: For alphanumeric characters, the same character (i.e. the function has no effect). For the space character, a + sign. For non-alphanumeric characters other than space, a string of the form %xx, where xx is the hexadecimal encoding of the ASCII character in the ISO Latin-1 character set. For example, the following returns abc%26%25:
escape("abc&%")
7.1.5 unescape
Returns the ASCII string for the specified value. Syntax:
unescape("string")
string is a String object or literal. For each distinct set of characters in the argument string of the following form %integer, where integer is a number between 0 and 255 (decimal) hex, where hex is a number between 0x0 and 0xFF (hexadecimal) unescape returns the corresponding ASCII character in the ISO Latin-1 character set. For characters not in the above form, unescape returns the characters unmodified; except for the + character, for which a space is returned. For example, the following returns &:
unescape("%26")
Array Object
7.2.1 Constructors
To create an Array object:
ArrayConstructor: new Array() new Array(arrayLength) new Array(componentList) componentList: componentValue, componentList componentValue componentValue: Identifier Literal
Array Object
arrayLength is a positive integer-valued numeric expression that specifies the initial length of the Array and becomes the value of the Array objects length property. An arrayLength specified to be zero or less results in a run-time error. An arrayLength that is not an integer is truncated to an integer. For example,
a = new Array("alpha", "beta", "gamma", "delta") b = new Array("a", "b", "c", "d") matrix = new Array(a, b) for (i = 0; i < a1.length; i++) { for (j = 0; j < a1[i].length; j++) { println(a1[i][j]) } }
7.2.2 Properties
An Array object has one property, length.
7.2.2.1 length
The length property indicates the number of components in an Array object. See the definition of components versus elements in section 1.1. The syntax is:
arrayObject.length
7.2.3 Methods
The Array object has three methods:
Array Object
join: Joins all elements of an array into a string. reverse: Reverses elements of an array sort: Sorts elements of an array based on a specified comparison function.
7.2.3.1 join
Returns a string containing all the elements of the array. Syntax:
arrayName.join(separator)
arrayName is the name of an Array object. separator specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, a comma (,) is used by default.
7.2.3.2 reverse
Reverses the elements of an array: the first array element becomes the last and the last becomes the first. Returns ? The effect of this method is to change the calling object. Syntax:
arrayName.reverse()
7.2.3.3 sort
Sorts the elements of an array. Syntax:
arrayName.sort(compareFunction) arrayName.sort()
arrayName is the name of an Array object. compareFunction is the name of a function that defines the sort order. It must be a function defined in the current program, a method of a built-in object, or a built-in function. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element. Strict definition of sort order for ASCII character set TBD.
Boolean Object
7.3.1 Constructors
The Boolean constructor creates an object with a Boolean value.
BooleanConstructor: new Boolean(BooleanLiteral) new Boolean()
If no argument is provided, then the constructor creates a object with Boolean value false.
7.3.2 Properties
The Boolean object has no properties.
7.3.3 Methods
The Boolean object has toString and valueOf methods.
Date Object
7.4.1 Constructors
There are five forms of a Date constructor:
DateConstructor: new Date() new Date(StringDate) new Date(year, month, day) new Date(year, month, day, hours, minutes, seconds) new Date(year, month, day, hours, minutes) new Date(year, month, day, hours) new Date(IntegerLiteral)
year, month, day, hours, minutes, and seconds are integers of the format described below. StringDate is a string representing a date in one of the following forms:
month day, year month day, year, hours:minutes:seconds month day, year, hours:minutes month day, year, hours day month, year day month, year hours:minutes:seconds day month, year hours:minutes day month, year hours month/day/year
year is the year, A.D., or the last two digits of the year; month is the full name of the month or a three-letter abbreviation, day is an integer value for the day of the month; hours is an integer between zero and 23; minutes and seconds are integers between zero and 59. If hours, minutes, or seconds are not specified, then the corresponding value is set to zero. msSinceEpoch is an integer representing the number of milliseconds since the epoch (00:00:00 GMT on January 1, 1970). The constructor with no parameters initializes a newly created Date object representing the instant of time that it was created, measured to the nearest millisecond.
Examples
The following examples show several ways to assign dates:
today = new Date() birthday = new Date("December 17, 1995 03:24:00")
Date Object
7.4.2 Properties
The Date object has no pre-defined properties.
7.4.3 Methods
The Date object has two kinds of methods: static methods used as member functions of the Date constructor itself, and dynamic methods used as member functions of instances of the Date object. The static methods are parse and UTC, with syntax:
Date.UTC(parameters) Date.parse(parameters)
where dateObjectName is a Date object created with one of the constructors from 1.2.1.
7.4.3.1 parse
Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time. The syntax is:
Date.parse(dateString)
dateString is a string value representing a date. Given a string representing a time, parse returns the time value. It accepts the IETF standard date syntax: Mon, 25 Dec 1995 13:30:00 GMT. It understands the continental US time-zone abbreviations, but for general use, use a timezone offset, for example, Mon, 25 Dec 1995 13:30:00 GMT+0430 (4 hours, 30 minutes west of the Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent.
Date Object
Because the parse function is a static method of Date, you always use it as Date.parse(), rather than as a method of a Date object you created. For example, If IPOdate is an existing Date object, then
IPOdate.setTime(Date.parse("Aug 9, 1995"))
7.4.3.2 setDate
Sets the day of the month for a specified date.
dateObjectName.setDate(dayValue)
dateObjectName is the name of a Date object. dayValue is an integer from one to thirty-one, representing the day of the month. For example, the second statement below changes the day for theBigDay to the 24th of July from its original value.
theBigDay = new Date("July 27, 1962 23:30:00") theBigDay.setDate(24)
7.4.3.3 setHours
Sets the hours for a specified date.
dateObjectName.setHours(hoursValue)
dateObjectName is the name of a Date object. hoursValue is an integer between zero and twenty-three, representing the hour. For example, the following sets the hour of the Date object theBigDay to 7:
theBigDay.setHours(7)
7.4.3.4 setMinutes
Sets the minutes for a specified date.
dateObjectName.setMinutes(minutesValue)
dateObjectName is the name of a Date object. minutesValue is an integer between zero and fifty-nine, representing the minutes.
theBigDay.setMinutes(45)
Date Object
7.4.3.5 setMonth
Sets the month for a specified date.
dateObjectName.setMonth(monthValue)
dateObjectName is the name of a Date object. monthValue is an integer between zero and eleven (representing the months January through December). For example, the following sets the month of the Date object theBigDay to 6:
theBigDay.setMonth(6)
7.4.3.6 setSeconds
Sets the seconds for a specified date.
dateObjectName.setSeconds(secondsValue)
dateObjectName is the name of a Date object. secondsValue is an integer between zero and fifty-nine. For example, the following sets the seconds of the Date object theBigDay to 30:
theBigDay.setSeconds(30)
7.4.3.7 setTime
Sets the value of a Date object.
dateObjectName.setTime(timevalue)
dateObjectName is the name of a Date object. timevalue is an integer representing the number of milliseconds since the epoch (1 January 1970 00:00:00). Use the setTime method to help assign a date and time to another Date object. For example, the following statements set the value of the Date object sameAsBigDay to have the value of the Date object theBigDay:
theBigDay = new Date("July 1, 1999") sameAsBigDay = new Date() sameAsBigDay.setTime(theBigDay.getTime())
Date Object
7.4.3.8 setYear
Sets the year for a specified date.
dateObjectName.setYear(yearValue)
dateObjectName is the name of a Date object. yearValue is an integer greater than 1900. For example, the following sets the year of the Date object theBigDay to 1996:
theBigDay.setYear(96)
7.4.3.9 toGMTString
Converts a date to a string, using the Internet GMT conventions.
dateObjectName.toGMTString()
dateObjectName is the name of a Date object . The exact format of the value returned by toGMTString varies according to the platform. Need xp definition. In the following example, today is a Date object:
today.toGMTString()
In this example, the toGMTString method converts the date to GMT (UTC) using the operating systems time-zone offset and returns a string value that is similar to the following form. The exact format depends on the platform.
Mon, 18 Dec 1995 17:28:35 GMT
7.4.3.10 toLocaleString
Converts a date to a string, using the current locales conventions.
dateObjectName.toLocaleString()
dateObjectName is either the name of a Date object. In the following example, today is a Date object:
today.toLocaleString()
Math Object
In this example, toLocaleString returns a string value that is similar to the following form. The exact format depends on the platform.
12/18/95 17:28:35
7.4.3.11 UTC
Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT).
Date.UTC(year, month, day [, hrs] [, min] [, sec])
year is a year after 1900. month is a month between zero and eleven. date is a day of the month between one and thirty-one. hrs is hours between zero and twenty-three. min is minutes between zero and fifty-nine. sec is seconds between zero and fifty-nine. UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT). Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a Date object you created. For example, the following statement creates a Date object using GMT instead of local time:
gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))
7.5.1 Constructors
The Math object does not have any constructors. All of its methods and properties are static; that is, they are member functions of the Math object itself. There is no way to create an instance of the Math object.
Math Object
7.5.2 Properties
The Math objects properties represent mathematical constants. For example, the Math objects PI property has the value of pi (3.141...), expressed as
Math.PI
7.5.2.1 E
Eulers constant and the base of natural logarithms, 2.718281828459045. Syntax:
Math.E
7.5.2.2 LN2
The natural logarithm of two, 0.6931471805599453. Syntax:
Math.LN2
7.5.2.3 LN10
The natural logarithm of ten, 2.302585092994046. Syntax:
Math.LN10
7.5.2.4 LOG2E
The base 2 logarithm of e, 1.4426950408889634. Syntax:
Math.LOG2E
7.5.2.5 LOG10E
The base 10 logarithm of e, 0.4342944819032518. Syntax:
Math.LOG10E
7.5.2.6 PI
The ratio of the circumference of a circle to its diameter, 3.141592653589793. Syntax:
Math Object
Math.PI
7.5.2.7 SQRT1_2
The square root of one-half; equivalently, one over the square root of two, 0.7071067811865476. Syntax:
Math.SQRT1_2
7.5.2.8 SQRT2
The square root of two, 1.4142135623730951. Syntax:
Math.SQRT2
7.5.3 Methods
Standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
7.5.3.1 abs
Returns the absolute value of a number. Syntax:
Math.abs(number)
7.5.3.2 acos
Returns the arc cosine (in radians) of a number. Syntax:
Math.acos(number)
number is a numeric expression between -1 and 1, inclusive. The acos method returns a numeric value between zero and pi radians. If the value of number is outside this range, it returns zero.
Math Object
7.5.3.3 asin
Returns the arc sine (in radians) of a number. Syntax:
Math.asin(number)
number is a numeric expression with a value between -1 and 1, inclusive The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is outside this range, it returns zero.
7.5.3.4 atan
Returns the arc tangent (in radians) of a number.
Math.atan(number)
number is a numeric expression representing the tangent of an angle. The atan method returns a numeric value between -pi/2 and pi/2 radians.
7.5.3.5 atan2
Returns the angle (theta component) of the polar coordinate (r,theta) that corresponds to the cartesian coordinate specified by the arguments. Syntax:
Math.atan2(xCoord,yCoord)
xCoord is a numeric expression representing a cartesian x-coordinate. yCoord is a numeric expression representing a cartesian y-coordinate.
7.5.3.6 ceil
Returns the least integer greater than or equal to its argument.
Math.ceil(number)
7.5.3.7 cos
Returns the cosine of a number.
Math.cos(number)
Math Object
The cos method returns a numeric value between -1 and one, which represents the cosine of the argument.
7.5.3.8 exp
Returns enumber, where number is the argument, and e is Eulers constant, the base of the natural logarithms.
Math.exp(number)
7.5.3.9 log
Returns the natural logarithm (base e) of a number.
Math.log(number)
number is any positive numeric expression. If the value of number is outside the suggested range, log returns -1.797693134862316e+308.
7.5.3.10 max
Returns the greater of two numbers. Syntax:
Math.max(number1, number2)
number1 and number2 are any numeric arguments or the properties of existing objects.
7.5.3.11 min
Returns the lesser of two numbers. Syntax:
Math.min(number1, number2)
number1 and number2 are any numeric arguments or the properties of existing objects.
7.5.3.12 pow
Returns base to the exponent power, that is, baseexponent. Syntax:
Math.pow(base, exponent)
Math Object
7.5.3.13 random
Returns a pseudo-random number between zero and one. This method does not have any parameters. Syntax:
Math.random()
7.5.3.14 round
Returns the value of a number rounded to the nearest integer. Syntax:
Math.round(number)
number is any numeric expression. If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.
7.5.3.15 sin
Returns the sine of a number. Syntax:
Math.sin(number)
number is a numeric expression, representing the size of an angle in radians. The sin method returns a numeric value between -1 and one, which represents the sine of the argument.
7.5.3.16 sqrt
Returns the square root of a number. Syntax:
Math.sqrt(number)
number is any non-negative numeric expression. If the value of number is outside the required range, sqrt returns zero.
7.5.3.17 tan
Returns the tangent of a number. Syntax:
Math.tan(number)
Number Object
7.6.1 Constructors
The Number constructor creates an object with a numeric value.
NumberConstructor: new Number(IntegerLiteral new Number(FloatingPointLiteral) new Number()
7.6.2 Properties
The properties of the Number object are constants.
7.6.2.1 MAX_VALUE
The largest number representable in JavaScript, 1.7976931348623157e308.
7.6.2.2 MIN_VALUE
The smallest number representable in JavaScript, 2.2250738585072014e-308.
7.6.2.3 NaN
The literal NaN, representing a value that is not a number.
String Object
7.6.3 Methods
The Number object has toString and valueOf methods.
7.7.1 Constructors
A string object is created whenever a string literal is used or assigned to a variable or with the explicit constructor:
identifierName = new String(stringValue)
7.7.2 Properties
A String object has one property, length.
7.7.2.1 length
The length property indicates the total number of characters in a String object. The syntax is:
stringObject.length
String Object
7.7.3 Methods
To use String methods:
stringName.methodName(parameters)
stringName is a String object.. methodName is a method of String. parameters are the parameters required by the method, if any.
7.7.3.1 indexOf
Returns the index within the calling string object of the first occurrence of the specified value, starting the search at fromIndex.
stringName.indexOf(searchValue) stringName.indexOf(searchValue, fromIndex)
stringName is any string. searchValue is a string, representing the value to search for. fromIndex is the location within the calling string to start the search from. It can be any integer from zero to stringName.length - 1. Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If you do not specify a value for fromIndex, JavaScript assumes zero by default. If searchValue is not found, JavaScript returns -1.
7.7.3.2 lastIndexOf
Returns the index within the calling string object of the last occurrence of the specified value. The calling string is searched backward, starting at fromIndex.
stringName.lastIndexOf(searchValue,) stringName.lastIndexOf(searchValue, fromIndex)
stringName is any string. searchValue is a string, representing the value to search for. fromIndex is the location within the calling string to start the search from. It can be any integer from zero to stringName.length - 1. Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1.
String Object
If you do not specify a value for fromIndex, lastIndexOf assumes stringName.length - 1 (the end of the string) by default. If searchValue is not found, lastIndexOf returns -1.
Example
The following example uses indexOf and lastIndexOf to locate values in the string Brave new world.
var anyString="Brave new world" //returns 8 anyString.indexOf("w") //returns 10 anyString.lastIndexOf("w") //returns 6 anyString.indexOf("new") //returns 6 anyString.lastIndexOf("new"))
7.7.3.3 substring
Returns a subset of a string object.
stringName.substring(indexA, indexB)
stringName is any string. indexA is any integer from zero to stringName.length - 1,. indexB is any integer from zero to stringName.length - 1,. Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If indexA is less than indexB, the substring method returns the subset starting with the character at indexA and ending with the character before indexB. If indexA is greater than indexB, the substring method returns the subset starting with the character at indexB and ending with the character before indexA. If indexA is equal to indexB, the substring method returns the empty string.
Example
The following example uses substring to display characters from the string Netscape:
var anyString="Netscape"
String Object
7.7.3.4 charAt
Returns the character at the specified index.
stringName.charAt(index)
stringName is any string. index is any integer from zero to stringName.length - 1,. Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.
Example
The following example displays characters at different locations in the string Brave new world:
var anyString="Brave new world" // The character at index 0 is B anyString.charAt(0)) // The character at index 3 is v anyString.charAt(3)
7.7.3.5 toLowerCase
Returns the calling string value converted to lowercase.
stringName.toLowerCase()
stringName is any string. The toLowerCase method returns the value of stringName converted to lowercase. toLowerCase does not affect the value of stringName itself.
Example
The following example returns the lowercase string alphabet:
String Object
7.7.3.6 toUpperCase
Returns the calling string value converted to uppercase.
stringName.toUpperCase()
stringName is any string. The toUpperCase method returns the value of stringName converted to uppercase. toUpperCase does not affect the value of stringName itself.
Example
The following example returns the string ALPHABET:
var lowerText="alphabet" lowerText.toUpperCase()
7.7.3.7 split
Splits a String object into an array of strings by separating the string into substrings. Returns an Array object. Syntax:
stringName.split(separator)
stringName is a String object. separator is string literal or expression that separates the string into substrings.
Example
Example TBD.