Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1086355 of Grammar and types

  • Revision slug: Web/JavaScript/Guide/Grammar_and_types
  • Revision title: Grammar and types
  • Revision id: 1086355
  • Created:
  • Creator: haarabi
  • Is current revision? No
  • Comment Improved the code sample by adding the case when the variable is declared as a var as opposed to let.
Tags: 

Revision Content

{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

This chapter discusses JavaScript's basic grammar, variable declarations, data types and literals.

Basics

JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.

JavaScript is case-sensitive and uses the Unicode character set.

In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (ASI) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's lexical grammar.

Comments

The syntax of comments is the same as in C++ and in many other languages:

// a one line comment
 
/* this is a longer, 
   multi-line comment
 */
 
/* You can't, however, /* nest comments */ SyntaxError */

Declarations

There are three kinds of declarations in JavaScript.

{{jsxref("Statements/var", "var")}}
Declares a variable, optionally initializing it to a value.
{{jsxref("Statements/let", "let")}}
Declares a block scope local variable, optionally initializing it to a value.
{{jsxref("Statements/const", "const")}}
Declares a read-only named constant.

Variables

You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, and _name.

Declaring variables

You can declare a variable in three ways:

  • With the keyword {{jsxref("Statements/var", "var")}}. For example, var x = 42. This syntax can be used to declare both local and global variables.
  • By simply assigning it a value. For example, x = 42. This always declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.
  • With the keyword {{jsxref("Statements/let", "let")}}. For example, let y = 13. This syntax can be used to declare a block scope local variable. See Variable scope below.

Evaluating variables

A variable declared using the var statement with no initial value specified has the value {{jsxref("undefined")}}.

An attempt to access an undeclared variable or an attempt to access an identifier declared with let statement before initialization will result in a {{jsxref("ReferenceError")}} exception being thrown:

var a;
console.log("The value of a is " + a); // The value of a is undefined

console.log("The value of b is " + b); // Uncaught ReferenceError: b is not defined

console.log("The value of c is " + c); // The value of c is undefined
var c;

console.log("The value of x is " + x); // Uncaught ReferenceError: x is not defined
let x; 

You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.

var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined:

var myArray = [];
if (!myArray[0]) myFunction(); 

The undefined value converts to NaN when used in numeric context.

var a;
a + 2;  // Evaluates to NaN

When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

var n = null;
console.log(n * 32); // Will log 0 to the console

Variable scope

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

if (true) {
  var x = 5;
}
console.log(x);  // x is undefined

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

if (true) {
  let y = 5;
}
console.log(y);  // ReferenceError: y is not defined

Variable hoisting

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

/**
 * Example 1
 */
console.log(x === undefined); // true
var x = 3;

/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";
 
(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

The above examples will be interpreted the same as:

/**
 * Example 1
 */
var x;
console.log(x === undefined); // true
x = 3;
 
/**
 * Example 2
 */
var myvar = "my value";
 
(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = "local value";
})();

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a {{jsxref("ReferenceError")}}. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

console.log(x); // ReferenceError
let x = 3;

Function hoisting

For functions, only function declaration gets hoisted to the top and not the function expression.

/* Function declaration */

foo(); // "bar"

function foo() {
  console.log("bar");
}


/* Function expression */

baz(); // TypeError: baz is not a function

var baz = function() {
  console.log("bar2");
};

Global variables

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

Constants

You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

const PI = 3.14;

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
  const g = 5;
  var g;

  //statements
}

However, object attributes are not protected, so the following statement is executed without problems.

const MY_OBJECT = {"key": "value"};
MY_OBJECT.key = "otherValue";

Data structures and types

Data types

The latest ECMAScript standard defines seven data types:

  • Six data types that are {{Glossary("Primitive", "primitives")}}:
    • {{Glossary("Boolean")}}. true and false.
    • {{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant.
    • {{Glossary("undefined")}}. A top-level property whose value is undefined.
    • {{Glossary("Number")}}. 42 or 3.14159.
    • {{Glossary("String")}}. "Howdy"
    • {{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.
  • and {{Glossary("Object")}}

Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

Data type conversion

JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:

var answer = 42;

And later, you could assign the same variable a string value, for example:

answer = "Thanks for all the fish...";

Because JavaScript is dynamically typed, this assignment does not cause an error message.

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

"37" - 7 // 30
"37" + 7 // "377"

Converting strings to numbers

In the case that a value representing a number is in memory as a string, there are methods for conversion.

  • {{jsxref("parseInt", "parseInt()")}}
  • {{jsxref("parseFloat", "parseFloat()")}}

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

"1.1" + "1.1" = "1.11.1"
(+"1.1") + (+"1.1") = 2.2   
// Note: the parentheses are added for clarity, not required.

Literals

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

  • {{anch("Array literals")}}
  • {{anch("Boolean literals")}}
  • {{anch("Floating-point literals")}}
  • {{anch("Integers")}}
  • {{anch("Object literals")}}
  • {{anch("RegExp literals")}}
  • {{anch("String literals")}}

Array literals

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

The following example creates the coffees array with three elements and a length of three:

var coffees = ["French Roast", "Colombian", "Kona"];

Note : An array literal is a type of object initializer. See Using Object Initializers.

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

Extra commas in array literals

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

var fish = ["Lion", , "Angel"];

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

var myList = ['home', , 'school', ];

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

var myList = [ , 'home', , 'school'];

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

var myList = ['home', , 'school', , ];

Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.

Boolean literals

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

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.

Integers

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

  • Decimal integer literal consists of a sequence of digits without a leading 0 (zero).
  • Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.
  • Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.
  • Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)

For more information, see Numeric literals in the Lexical grammar reference.

Floating-point literals

A floating-point literal can have the following parts:

  • A decimal integer which can be signed (preceded by "+" or "-"),
  • A decimal point ("."),
  • A fraction (another decimal number),
  • An exponent.

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

More succinctly, the syntax is:

[(+|-)][digits][.digits][(E|e)[(+|-)]digits]

For example:

3.1415926
-.123456789
-3.1E+12
.1e-23

Object literals

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

var sales = "Toyota";

function carTypes(name) {
  if (name === "Honda") {
    return name;
  } else {
    return "Sorry, we don't sell " + name + ".";
  }
}

var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };

console.log(car.myCar);   // Saturn
console.log(car.getCar);  // Honda
console.log(car.special); // Toyota 

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda

Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation("[]").

var unusualPropertyNames = {
  "": "An empty string",
  "!": "Bang!"
}
console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
console.log(unusualPropertyNames[""]);  // An empty string
console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
console.log(unusualPropertyNames["!"]); // Bang!

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

Please note:

var foo = {a: "alpha", 2: "two"};
console.log(foo.a);    // alpha
console.log(foo[2]);   // two
//console.log(foo.2);  // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two

RegExp literals

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

var re = /ab+c/;

String literals

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

"foo"
'bar'
"1234"
"one line \n another line"
"John's cat"

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

console.log("John's cat".length) 
// Will print the number of symbols in the string including whitespace. 
// In this case, 10.

In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`https://foo.org/bar?a=${a}&b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

Using special characters in strings

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

"one line \n another line"

The following table lists the special characters that you can use in JavaScript strings.

Table: JavaScript special characters
Character Meaning
\0 Null Byte
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\' Apostrophe or single quote
\" Double quote
\\ Backslash character
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX} Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.

Escaping characters

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);

The result of this would be:

He read "The Cremation of Sam McGee" by R.W. Service.

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

var home = "c:\\temp";

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

var str = "this string \
is broken \
across multiple\
lines."
console.log(str);   // this string is broken across multiplelines.

Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:

var poem = 
"Roses are red,\n\
Violets are blue.\n\
Sugar is sweet,\n\
and so is foo."

More information

This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:

In the next chapter, we will have a look at control flow constructs and error handling.

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

Revision Source

<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div>

<p class="summary">This chapter discusses JavaScript's basic grammar, variable declarations, data types and literals.</p>

<h2 id="Basics">Basics</h2>

<p>JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.</p>

<p>JavaScript is <strong>case-sensitive</strong> and uses the <strong>Unicode</strong> character set.</p>

<p>In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.</p>

<h2 id="Comments">Comments</h2>

<p>The syntax of <strong>comments</strong> is the same as in C++ and in many other languages:</p>

<pre class="brush: js">
// a one line comment
 
/* this is a longer, 
   multi-line comment
 */
 
/* You can't, however, /* nest comments */ SyntaxError */</pre>

<h2 id="Declarations">Declarations</h2>

<p>There are three kinds of declarations in JavaScript.</p>

<dl>
 <dt>{{jsxref("Statements/var", "var")}}</dt>
 <dd>Declares a variable, optionally initializing it to a value.</dd>
 <dt>{{jsxref("Statements/let", "let")}}</dt>
 <dd>Declares a block scope local variable, optionally initializing it to a value.</dd>
 <dt>{{jsxref("Statements/const", "const")}}</dt>
 <dd>Declares a read-only named constant.</dd>
</dl>

<h3 id="Variables">Variables</h3>

<p>You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.</p>

<p>A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).</p>

<p>You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a> as characters in identifiers.</p>

<p>Some examples of legal names are <code>Number_hits</code>, <code>temp99</code>, and <code>_name</code>.</p>

<h3 id="Declaring_variables">Declaring variables</h3>

<p>You can declare a variable in three ways:</p>

<ul>
 <li>With the keyword {{jsxref("Statements/var", "var")}}. For example, <code>var x = 42</code>. This syntax can be used to declare both local and global variables.</li>
 <li>By simply assigning it a value. For example, <code>x = 42</code>. This always declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.</li>
 <li>With the keyword {{jsxref("Statements/let", "let")}}. For example, <code>let y = 13</code>. This syntax can be used to declare a block scope local variable. See <a href="#Variable_scope">Variable scope</a> below.</li>
</ul>

<h3 id="Evaluating_variables">Evaluating variables</h3>

<p>A variable declared using the <code>var</code> statement with no initial value specified has the value {{jsxref("undefined")}}.</p>

<p>An attempt to access an undeclared variable or an attempt to access an identifier declared with let statement before initialization will result in a {{jsxref("ReferenceError")}} exception being thrown:</p>

<pre class="brush: js">
var a;
console.log("The value of a is " + a); // The value of a is undefined

console.log("The value of b is " + b); // Uncaught ReferenceError: b is not defined

console.log("The value of c is " + c); // The value of c is undefined
var c;

console.log("The value of x is " + x); // Uncaught ReferenceError: x is not defined
let x; </pre>

<p>You can use <code>undefined</code> to determine whether a variable has a value. In the following code, the variable <code>input</code> is not assigned a value, and the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code> statement evaluates to <code>true</code>.</p>

<pre class="brush: js">
var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}
</pre>

<p>The <code>undefined</code> value behaves as <code>false</code> when used in a boolean context. For example, the following code executes the function <code>myFunction</code> because the <code>myArray</code> element is undefined:</p>

<pre class="brush: js">
var myArray = [];
if (!myArray[0]) myFunction(); 
</pre>

<p>The <code>undefined</code> value converts to <code>NaN</code> when used in numeric context.</p>

<pre class="brush: js">
var a;
a + 2;  // Evaluates to NaN</pre>

<p>When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:</p>

<pre class="brush: js">
var n = null;
console.log(n * 32); // Will log 0 to the console
</pre>

<h3 id="Variable_scope">Variable scope</h3>

<p>When you declare a variable outside of any function, it is called a <em>global</em> variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a <em>local</em> variable, because it is available only within that function.</p>

<p>JavaScript before ECMAScript 2015&nbsp;does not have <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; rather, a variable declared within a block is local to the <em>function (or global scope)</em> that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p>

<pre class="brush: js">
if (true) {
  var x = 5;
}
console.log(x);  // x is undefined
</pre>

<p>This behavior changes, when using the <code>let</code> declaration introduced in ECMAScript 2015.</p>

<pre class="brush: js">
if (true) {
  let y = 5;
}
console.log(y);  // ReferenceError: y is not defined
</pre>

<h3 id="Variable_hoisting">Variable hoisting</h3>

<p>Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as <strong>hoisting</strong>; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted&nbsp;will return a value of <code>undefined</code>. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.</p>

<pre class="brush: js">
/**
 * Example 1
 */
console.log(x === undefined); // true
var x = 3;

/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";
 
(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();
</pre>

<p>The above examples will be interpreted the same as:</p>

<pre class="brush: js">
/**
 * Example 1
 */
var x;
console.log(x === undefined); // true
x = 3;
 
/**
 * Example 2
 */
var myvar = "my value";
 
(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = "local value";
})();
</pre>

<p>Because of hoisting, all <code>var</code> statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.</p>

<p>In ECMAScript 2015, <code>let (const)</code> <strong>will not hoist</strong> the variable to the top of the block. However, referencing&nbsp;the&nbsp;variable in the&nbsp;block before the variable declaration&nbsp;results in a {{jsxref("ReferenceError")}}. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.</p>

<pre class="brush: js">
console.log(x); // ReferenceError
let x = 3;</pre>

<h3 id="Function_hoisting">Function hoisting</h3>

<p>For functions, only function declaration gets hoisted to the top and not the function expression.</p>

<pre class="brush: js">
/* Function declaration */

foo(); // "bar"

function foo() {
  console.log("bar");
}


/* Function expression */

baz(); // TypeError: baz is not a function

var baz = function() {
  console.log("bar2");
};
</pre>

<h3 id="Global_variables">Global variables</h3>

<p>Global variables are in fact properties of the <em>global object</em>. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p>

<p>Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called <code>phoneNumber</code> is declared in a document, you can refer to this variable from an iframe as <code>parent.phoneNumber</code>.</p>

<h3 id="Constants">Constants</h3>

<p>You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.</p>

<pre class="brush: js">
const PI = 3.14;
</pre>

<p>A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.</p>

<p>The scope rules for constants are the same as those for <code>let</code> block scope variables. If the <code>const</code> keyword is omitted, the identifier is assumed to represent a variable.</p>

<p>You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p>

<pre class="brush: js">
// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
  const g = 5;
  var g;

  //statements
}
</pre>

<p>However, object attributes are not protected,&nbsp;so the following statement is executed without problems.</p>

<pre class="brush: js">
const MY_OBJECT = {"key": "value"};
MY_OBJECT.key = "otherValue";</pre>

<h2 id="Data_structures_and_types">Data structures and types</h2>

<h3 id="Data_types">Data types</h3>

<p>The latest ECMAScript standard defines seven data types:</p>

<ul>
 <li>Six data types that are {{Glossary("Primitive", "primitives")}}:
  <ul>
   <li>{{Glossary("Boolean")}}. <code>true</code> and <code>false</code>.</li>
   <li>{{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, <code>null</code> is not the same as <code>Null</code>, <code>NULL</code>, or any other variant.</li>
   <li>{{Glossary("undefined")}}. A top-level property whose value is undefined.</li>
   <li>{{Glossary("Number")}}. <code>42</code> or <code>3.14159</code>.</li>
   <li>{{Glossary("String")}}. "Howdy"</li>
   <li>{{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.</li>
  </ul>
 </li>
 <li>and {{Glossary("Object")}}</li>
</ul>

<p>Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.</p>

<h3 id="Data_type_conversion">Data type conversion</h3>

<p>JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:</p>

<pre class="brush: js">
var answer = 42;
</pre>

<p>And later, you could assign the same variable a string value, for example:</p>

<pre class="brush: js">
answer = "Thanks for all the fish...";
</pre>

<p>Because JavaScript is dynamically typed, this assignment does not cause an error message.</p>

<p>In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:</p>

<pre class="brush: js">
x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"
</pre>

<p>In statements involving other operators, JavaScript does not convert numeric values to strings. For example:</p>

<pre class="brush: js">
"37" - 7 // 30
"37" + 7 // "377"
</pre>

<h3 id="Converting_strings_to_numbers">Converting strings to numbers</h3>

<p>In the case that a value representing a number is in memory as a string, there are methods for conversion.</p>

<ul>
 <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li>
 <li>{{jsxref("parseFloat", "parseFloat()")}}</li>
</ul>

<p><code>parseInt</code> will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for <code>parseInt</code> is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.</p>

<p>An alternative method of retrieving a number from a string is with the <code>+</code>&nbsp;(unary plus) operator:</p>

<pre class="brush: js">
"1.1" + "1.1" = "1.11.1"
(+"1.1") + (+"1.1") = 2.2   
// Note: the parentheses are added for clarity, not required.</pre>

<h2 id="Literals">Literals</h2>

<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p>

<ul>
 <li>{{anch("Array literals")}}</li>
 <li>{{anch("Boolean literals")}}</li>
 <li>{{anch("Floating-point literals")}}</li>
 <li>{{anch("Integers")}}</li>
 <li>{{anch("Object literals")}}</li>
 <li>{{anch("RegExp literals")}}</li>
 <li>{{anch("String literals")}}</li>
</ul>

<h3 id="Array_literals">Array literals</h3>

<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (<code>[]</code>). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.</p>

<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p>

<pre class="brush: js">
var coffees = ["French Roast", "Colombian", "Kona"];
</pre>

<div class="note">
<p><strong>Note :</strong> An array literal is a type of object initializer. See <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers">Using Object Initializers</a>.</p>
</div>

<p>If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.</p>

<p>Array literals are also <code>Array</code> objects. See {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> for details on <code>Array</code> objects.</p>

<h4 id="Extra_commas_in_array_literals">Extra commas in array literals</h4>

<p>You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p>

<pre class="brush: js">
var fish = ["Lion", , "Angel"];
</pre>

<p>This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p>

<p>If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no <code>myList[3]</code>. All other commas in the list indicate a new element.</p>

<div class="note">
<p><strong>Note :</strong> Trailing commas can create errors in older browser versions and it is a best practice to remove them.</p>
</div>

<pre class="brush: js">
var myList = ['home', , 'school', ];
</pre>

<p>In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p>

<pre class="brush: js">
var myList = [ , 'home', , 'school'];
</pre>

<p>In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p>

<pre class="brush: js">
var myList = ['home', , 'school', , ];
</pre>

<p>Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as <code>undefined</code> will increase your code's clarity and maintainability.</p>

<h3 id="Boolean_literals">Boolean literals</h3>

<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p>

<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.</p>

<h3 id="Integers">Integers</h3>

<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).</p>

<ul>
 <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li>
 <li>Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.</li>
 <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li>
 <li>
  <p>Leading 0b (or 0B) indicates&nbsp;binary. Binary integers can include digits only 0 and 1.</p>
 </li>
</ul>

<p>Some examples of integer literals are:</p>

<pre class="eval">
0, 117 and -345 (decimal, base 10)
015, 0001 and -0o77 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
0b11, 0b0011 and -0b11 (binary, base 2)
</pre>

<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p>

<h3 id="Floating-point_literals">Floating-point literals</h3>

<p>A floating-point literal can have the following parts:</p>

<ul>
 <li>A decimal integer which can be signed (preceded by "+" or "-"),</li>
 <li>A decimal point ("."),</li>
 <li>A fraction (another decimal number),</li>
 <li>An exponent.</li>
</ul>

<p>The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").</p>

<p>More succinctly, the syntax is:</p>

<pre class="eval">
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
</pre>

<p>For example:</p>

<pre class="eval">
3.1415926
-.123456789
-3.1E+12
.1e-23
</pre>

<h3 id="Object_literals">Object literals</h3>

<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (<code>{}</code>). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p>

<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>, and assigns to it a new string, "<code>Saturn</code>"; the second element, the <code>getCar</code> property, is immediately assigned the result of invoking the function <code>(carTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>sales</code>).</p>

<pre class="brush: js">
var sales = "Toyota";

function carTypes(name) {
  if (name === "Honda") {
    return name;
  } else {
    return "Sorry, we don't sell " + name + ".";
  }
}

var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };

console.log(car.myCar);   // Saturn
console.log(car.getCar);  // Honda
console.log(car.special); // Toyota 
</pre>

<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p>

<pre class="brush: js">
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
</pre>

<p>Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (<code>.</code>) property, but can be accessed and set with the array-like notation("<code>[]</code>").</p>

<pre class="brush: js">
var unusualPropertyNames = {
  "": "An empty string",
  "!": "Bang!"
}
console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
console.log(unusualPropertyNames[""]);  // An empty string
console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
console.log(unusualPropertyNames["!"]); // Bang!</pre>

<p>In ES2015, object literals are extended to support setting the prototype at construction, shorthand for&nbsp;<code>foo: foo</code>&nbsp;assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.</p>

<pre class="brush: js">
var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() =&gt; 42)() ]: 42
};</pre>

<p>Please note:</p>

<pre class="brush: js">
var foo = {a: "alpha", 2: "two"};
console.log(foo.a);    // alpha
console.log(foo[2]);   // two
//console.log(foo.2);  // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two
</pre>

<h3 id="RegExp_literals">RegExp literals</h3>

<p>A regex literal is&nbsp;a pattern enclosed between slashes.&nbsp;The following is an example of an regex literal.</p>

<pre class="brush: js">
var re = /ab+c/;</pre>

<h3 id="String_literals">String literals</h3>

<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p>

<pre class="brush: js">
"foo"
'bar'
"1234"
"one line \n another line"
"John's cat"
</pre>

<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p>

<pre class="brush: js">
console.log("John's cat".length) 
// Will print the number of symbols in the string including whitespace. 
// In this case, 10.
</pre>

<p>In ES2015, template literals are also available.&nbsp;Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.</p>

<pre class="brush: js">
// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`https://foo.org/bar?a=${a}&amp;b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);</pre>

<p>You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on <code>String</code> objects.</p>

<h4 id="Using_special_characters_in_strings">Using special characters in strings</h4>

<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p>

<pre class="brush: js">
"one line \n another line"
</pre>

<p>The following table lists the special characters that you can use in JavaScript strings.</p>

<table class="standard-table">
 <caption>Table: JavaScript special characters</caption>
 <thead>
  <tr>
   <th scope="col">Character</th>
   <th scope="col">Meaning</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>\0</code></td>
   <td>Null Byte</td>
  </tr>
  <tr>
   <td><code>\b</code></td>
   <td>Backspace</td>
  </tr>
  <tr>
   <td><code>\f</code></td>
   <td>Form feed</td>
  </tr>
  <tr>
   <td><code>\n</code></td>
   <td>New line</td>
  </tr>
  <tr>
   <td><code>\r</code></td>
   <td>Carriage return</td>
  </tr>
  <tr>
   <td><code>\t</code></td>
   <td>Tab</td>
  </tr>
  <tr>
   <td><code>\v</code></td>
   <td>Vertical tab</td>
  </tr>
  <tr>
   <td><code>\'</code></td>
   <td>Apostrophe or single quote</td>
  </tr>
  <tr>
   <td><code>\"</code></td>
   <td>Double quote</td>
  </tr>
  <tr>
   <td><code>\\</code></td>
   <td>Backslash character</td>
  </tr>
  <tr>
   <td><code>\<em>XXX</em></code></td>
   <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td>
  </tr>
  <tr>
  </tr>
  <tr>
   <td><code>\x<em>XX</em></code></td>
   <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td>
  </tr>
  <tr>
  </tr>
  <tr>
   <td><code>\u<em>XXXX</em></code></td>
   <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</td>
  </tr>
  <tr>
   <td><code>\u<em>{XXXXX}</em></code></td>
   <td>Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.</td>
  </tr>
 </tbody>
</table>

<h4 id="Escaping_characters">Escaping characters</h4>

<p>For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p>

<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p>

<pre class="brush: js">
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);
</pre>

<p>The result of this would be:</p>

<pre class="eval">
He read "The Cremation of Sam McGee" by R.W. Service.
</pre>

<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p>

<pre class="brush: js">
var home = "c:\\temp";
</pre>

<p>You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.</p>

<pre class="brush: js">
var str = "this string \
is broken \
across multiple\
lines."
console.log(str);   // this string is broken across multiplelines.
</pre>

<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:</p>

<pre class="brush: js">
var poem = 
"Roses are red,\n\
Violets are blue.\n\
Sugar is sweet,\n\
and so is foo."
</pre>

<h2 id="More_information">More information</h2>

<p>This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:</p>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li>
</ul>

<p>In the next chapter, we will have a look at control flow constructs and error handling.</p>

<p>{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p>
Revert to this revision