Dirk Harriman Banner Image

 

Notes Javascript - Overview


 

 
 

Sandbox

Script 1 Script 2 Script 3 Script 4 Script 5
 

 

Javascript

A semicolon is not necessary after a statement if it is written on its own line, but if more than one statement on a line is desired, then they must be separated by semicolons. Although they are not required, IMHO it's good programming practice to be consistent.


 

Variables

JavaScript has three kinds of variable declarations.

 

Declaration & Initialization

let x = 42; // ( let x ) - Declaration, ( = 42 ) - Initializer var y = 12; // ( var y ) - Declaration, ( = 12 ) - Initializer const z = 35; // ( const z ) - Declaration, ( = 35 ) - Initializer

In a statement like let x = 42, the let x part is called a declaration, and the = 42 part is called an initializer.

With the var and let declarations, the initializer is optional. If a variable is declared without an initializer, it is assigned the value undefined.
With const, the initializer is required.

let x = 42; // IS EQUIVALENT TO let x; x = 42;


 

var

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

var name1; var name1 = value1; var name1 = value1, name2 = value2; var name1, name2 = value2; var name1 = value1, name2, /* ..., */ nameN = valueN;

Hoisting

var declarations, wherever they occur, are processed before any code is executed. This behavior is called hoisting, as it appears that the variable declaration is moved to the top of the function or global code. Because var declarations are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared.

It's important to point out that only a variable's declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached. Until then the variable remains undefined (but declared):

In the global context, a variable declared using var is added as a non-configurable property of the global object. This means its property descriptor cannot be changed and it cannot be deleted using delete. The corresponding name is also added to a list on the internal [[VarNames]] slot on the global environment record (which forms part of the global lexical environment). The list of names in [[VarNames]] enables the runtime to distinguish between global variables and straightforward properties on the global object.

The property created on the global object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object. JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable.

Unassigned var Variables

Any var declared variables without assigned values are given the javascript primative type of undefined.

Scope

The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.


 

let

The let declaration declares a block-scoped local variable, optionally initializing it to a value. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter can only be accessed after its declaration is reached. For this reason, let declarations are commonly regarded as non-hoisted.

Just like const, let does not create properties of the window object when declared globally (in the top-most scope).

Many issues with let variables can be avoided by declaring them at the top of the scope in which they are used (doing so may impact readability).

Unlike var, let begins declarations, not statements. That means you cannot use a lone let declaration as the body of a block (which makes sense, since there's no way to access the variable).

// The following will cause a syntax error: Lexical declaration cannot appear in a single-statement context if (true) let a = 1;

Syntax

let name1; let name1 = value1; let name1 = value1, name2 = value2; let name1, name2 = value2; let name1 = value1, name2, /* ..., */ nameN = valueN;

Hoisting

Unlike var, let is not hoisted.

Unassigned var Variables

Scope

Variables declared by let have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

function varTest() { var x = 1; { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 }

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

var x = "global"; let y = "global"; console.log(this.x); // "global" console.log(this.y); // undefined


 

const

The const declaration creates block-scoped constants, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it cannot be redeclared (i.e. through a variable declaration). However, if a constant is an object or array its properties or items can be updated or removed.

Initialization

A const must be initialized when declared. Failing to do so creates a syntax error.

Syntax

const name1 = value1; const name1 = value1, name2 = value2; const name1 = value1, name2 = value2, /* ..., */ nameN = valueN;

Hoisting

Constants are non-hoisted.

Scope

It's important to note the nature of block scoping.

if (MY_FAV === 7) { // this is fine and creates a block scoped MY_FAV variable // (works equally well with let to declare a block scoped non const variable) let MY_FAV = 20; // MY_FAV is now 20 console.log("my favorite number is " + MY_FAV); // this gets hoisted into the global context and throws an error var MY_FAV = 20; } // MY_FAV is still 7 console.log("my favorite number is " + MY_FAV);

 

Data Structures & Types

The latest ECMAScript standard defines eight data types. Seven are known as Primatives and the eighth is the javascript Object.

Primatives
Boolean True or false.
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.)
undefined A top-level property whose value is not defined.
Number An integer or floating point number. For example: 42 or 3.14159.
BigInt An integer with arbitrary precision. For example: 9007199254740992n.
String A sequence of characters that represent a text value. For example: "Howdy".
Symbol A data type whose instances are unique and immutable.
Non-Primative
Object In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String value or a Symbol value. There are two types of object properties: The data property and the accessor property.

Literals

Literals represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script.

Array Literals
Boolean Literals
Numeric Literals
Object Literals
Regexp Literals
String Literals

Literal Examples

// ARRAY LITERAL const coffees = ["French Roast","Columbian","Kona"]; // EMPTY ELEMENTS coffees[1] = undefined const coffees = ["French Roast",,"Columbian","Kona"]; // THE LENGTH OF THE FOLLOWING ARRAY IS 3. // myList[0] = undefined, myList[1] = "home", myList[2] = undefined, myList[3] = "school" const myList = [, "home", , "school"]; // THE LAST COMMA IS IGNORED // myList[0] = "home", myList[1] = undefined, myList[2] = "school", myList[3] = undefined const myList = ["home", , "school", ,]; // BOOLEAN LITERALS ARE true OR false // INTEGER LITERALS const myint = 0; // DECIMAL BASE 10 const myoct = 015; // OCTAL BASE 8 const myhex = 0x1123; // HEXIDECIMAL BASE 16 const mybin = 0b0011; // BINARY BASE 2 // FLOATING POINT SYNTAX [digits].[digits][(E|e)[(+|-)]digits] // FLOATING POINT LITERALS const myfloat = 3.14159; const myfloat = .123456789; const myfloat = 3.1E+12; const myfloat = .1e-23; // STRING LITERALS var mystring = 'foo'; var mystring = "bar"; var mystring = '1234' var mystring = 'One line\n Another line'; var mystring = "Sentence with an apostrophy. Dirk's computer." // REGULAR EXPRESSION LITERALS const re = /ab+c/;

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 ({}).

Note: Do 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 curly brace 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).

const sales = "Toyota"; function carTypes(name) { return name === "Honda" ? name : `Sorry, we don't sell ${name}.`; } const 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.

const car = { manyCars: { a: "Saab", b: "Jeep" }, 7: "Mazda" }; console.log(car.manyCars.b); // Jeep console.log(car[7]); // Mazda

Template Literals

Template literals are enclosed by the back-tick (`) (grave accent) character instead of double or single quotes. Template literals provide syntactic sugar for constructing strings. (This is similar to string interpolation features in Perl, Python, and more.)

// Basic literal string creation `In JavaScript '\n' is a line-feed.` // Multiline strings `In JavaScript, template strings can run over multiple lines, but double and single quoted strings cannot.` // String interpolation const name = 'Lev', time = 'today'; `Hello ${name}, how are you ${time}?`

Tagged templates are a compact syntax for specifying a template literal along with a call to a "tag" function for parsing it. A tagged template is just a more succinct and semantic way to invoke a function that processes a string and a set of relevant values. The name of the template tag function precedes the template literal — as in the following example, where the template tag function is named print. The print function will interpolate the arguments and serialize any objects or arrays that may come up, avoiding the pesky [object Object].

const formatArg = (arg) => { if (Array.isArray(arg)) { // Print a bulleted list return arg.map((part) => `- ${part}`).join("\n"); } if (arg.toString === Object.prototype.toString) { // This object will be serialized to "[object Object]". // Let's print something nicer. return JSON.stringify(arg); } return arg; }; const print = (segments, ...args) => { // For any well-formed template literal, there will always be N args and // (N+1) string segments. let message = segments[0]; segments.slice(1).forEach((segment, index) => { message += formatArg(args[index]) + segment; }); console.log(message); }; const todos = [ "Learn JavaScript", "Learn Web APIs", "Set up my website", "Profit!", ]; const progress = { javascript: 20, html: 50, css: 10 }; print`I need to do: ${todos} My current progress is: ${progress} `; // I need to do: // - Learn JavaScript // - Learn Web APIs // - Set up my website // - Profit! // My current progress is: {"javascript":20,"html":50,"css":10}

Since tagged template literals are just sugar of function calls, you can re-write the above as an equivalent function call:

print(["I need to do:\n", "\nMy current progress is: ", "\n"], todos, progress);

This may be reminiscent of the console.log-style interpolation:

console.log("I need to do:\n%o\nMy current progress is: %o\n", todos, progress);

You can see how the tagged template reads more naturally than a traditional "formatter" function, where the variables and the template itself have to be declared separately.

Special Characters

Character Meaning
\0 Null Byte
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab
\v Vertical Tab
\' Apostrophy
\" Double Quote
\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.
\u{XXXXX} Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.

Escaping Characters

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:

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

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:

const 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.

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