1Variables: Declaration, Definition and Type

Variables are made to receive values directly or through evaluated expressions compounding values and operators or results of function calls: the value is stored internally and the variable references this storage, and takes its value and its type.

There are two kinds of values:

  • – primitive values: numbers or strings in literal notation, “built-in” values such as true, false, NaN, infinity, null, undefined, etc.;
  • – objects, including functions, and arrays, which are “containers”, and, as such, their value is the address of the container.

NOTE.– The content of a container can be modified, while the address remains unchanged (this is important for understanding the “const” declaration below).

To fetch the value of a variable, it must have been identified in the lexical phase: which means to be “declared”. Often, JavaScript code starts with declaration instructions such as:

var tableauCandidats = [];
var n = 0; // … …

We will show why it is highly preferable to write:

const tableauCandidats = [];
let n = 0; // … …

Let us look back at the two steps in the interpretation of JavaScript (simplified):

  • – Lexical-time: It deals with the lexical analysis of the code. The names of the declared functions and variables are recorded in a tree structure (lexical tree). Declarations are moved up to the beginning of their block of code: this is named the “hoisting”. Functions are hoisted first, for they define the nodes of the structure, then variables ...

Get JavaScript and Open Data now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.