Some notes about Javascript

Basics

Fundamental types

  • booleans
  • numbers
  • strings
  • objects
  • arrays

Comments

//

Single line comment

/* ... */

Multi lines comment. Can't be nested.

Expressions

Produce a value; end with a semicolon.

Statements

Perform an action; end with a semicolon.

Blocks

{ ... }

Curly braces can contain zero or more statements.

Strict mode

use strict

Disables some unsafe features and raises more warnings, errors and exceptions.

Javascript values

Primitive types

  • Undefined
  • Null
  • Boolean
  • String
  • Number

Undefined means no value, Null no object.

Primitive types can be compared by value and are alway immutable (can't change, add or remove properties).

Are a fixed set: it not possible to define own primitive types.

Can be turned into objects by wrapping them with the corresponding contructor.

Objects

{
    property: value,
    ...,
    property: value,
}

Objects can be compared by reference; an object is strictly equal to itself. Objects are mutable by default: it is possible to add, change and remove properties.

Coercion

Implict type conversion is done by the engine. Explicit type conversion is done by invoking a function.

Operators

assignment / compound assignment

= / (op)=

strict / lenient equality

===, !== / ==, !=

ordering

<, <= , >, >=

arithmetic

+, -, /, *

boolean

&&, ||, !

bitwise

~, &, |, ^, <<, >>, >>>

conditional

?:

void

void(expression)

discards the result of expression and returns undefined;

categorization

typeof <value>

describes what kind of value value is;

<value> instanceof <object>

checks if an object is an instance of a given constructor.

Booleans

Values: true, false

Automatic conversion

  • Numbers: 0, NaN evaluates to false;
  • Strings: '' evaluate to false;
  • Objects: always evaluates to true
  • undefined, null are always false.

Manual conversion

Boolean(<value>)

Converts any value to its boolean counterpart.

Operators

logical operators

&& (and), || (or), ! (not)

equality operators

===, !==, ==, !=

ordering operators

->, >=, <, <=

Numbers

Literals

Number literals can be integer, floating point, hexadecimal. Invoke methods on literals as: (<literal>).method().

Automatic conversion

  • undefined: NaN;
  • null: 0;
  • boolean: false converted to 0, true converted to 1;
  • string: converted to the string representation of the number;
  • object: converted to primitive and primitive converted to number.

Manual conversion

Number(<value>)

Special values

NaN

It's a number and it's returned when a number cannot be parsed or an operation fails. To check if a variable is NaN use the function isNan().

Infinity

It is returned if a division by zero occours or if a number is too large.

Operators

arithmetic operators

+, -, *, /, %, ++, --

bitwise operators

-, &, |, ^~

shift operators

<<, >>, <<<, >>>

<<< is the unsigned version of the << operator.

Strings

Literals

String literals are enclosed in single or double. \ is the escaping character. Lines can be split across multiple lines with \\ at the end of the line.

Hexadecimal and Unicode escape sequences are supported: \\xHH, \\xUU.

Template literals

let string = `Current value is ${...}`;

Are strings enclosed in backticks. They allow multiline strings and there's no need to escape single and double quotes. Interpolation of both variables and expressions is also available.

Character access

  • <string>.charAt(n)
  • <string>[n]

Automatic conversion

  • undefined: 'undefined';
  • null: 'null';
  • boolean: false converted to 'false', true converted to 'true';
  • number: string representation of the number
  • object: converted to primitive and primitive converted to string

Manual conversion

String(<value>)

Comparison

<, >, ===, <=, >=

Comparision is case sensitive.

Concatenation

  • +
  • <array>.join(' ')

String properties and methods

Length

<string>.lenght

Extracting substring

<string>.slice(start, end?)

Start and end can be negative.

Splitting

<string>.split(separator, limit?)

Separator can be a string or a regex; limit is the maximum number of elements returned.

Trimming

<string>.trim()

Concatenation

<string>.concat(str1, str2, ...)

Lower case conversion

<string>.toLowerCase()

Upper case conversion

<string>.toUpperCase()

Search a substring in a string

<string>.indexOf(substring, position?)

<string>.lastIndexOf(substring, position?)

Locale aware string comparison

<string>.localeCompare(string)

Test, match and replace

<string>.search(regex)

Returns the first index at which regex matches in string.

<string>.match(regex)

Returns a match object for the first match.

<string>.replace(search, replacement)

Search can be a string or a regex. Replace can be a string or a function.

Statements

Variable assignment

let name = value;

Loops

While loop

while (<condition>) {
    <statement>
}

Loop is executed until condition holds.

Do loop

do {
    <statement>
} while (<condition>)

Same as the while loop, but executed at least once.

For loop

for ([<init>]; [<condition>]; [<post-iteration>]) {
    <statement>
}
  • <init> is executed before the loop;
  • <condition> is checked at the end of each iteration;
  • <post-iteration> is executed after each iteration.
for (<variable> in <object) {
    <statement>
}

Iterates over object properties keys, including inherited properties

Do not use to iterate over arrays.

for (<item> of <collection>) {
   <statement>
}

Iterates over the items of a collection.

Control statements

break [label];

Exits from loop [label]; if label is omitted exits the innermost loop.

continue [label];

Skips to the next iteration of loop [label]; if label is omitted skips the innermost loop iteration.

Conditionals

if (<condition>) {
	<then_branch>
} [else {
	<else_branch>
]}

If the condition is true executes the then branch, otherwise the else branch (if present). Conditions can be chained using else if statements.

switch (<expression>) {
case <label1>:
    ...;
    break;
case <label2>:
    ...;
    break;
default: ...; 
}

Evaluates the expression and then jumps to the case clause whose label matches the result. If no label matches jumps to the default clause (if present). <label> can be any expression; it's strictly compared with the result of the condition evaluation. If break is omitted execution continues to the next clause.

Exceptions handling

Intercepting exceptions

  • try { ... } catch (exception) { ... }
  • try { ... } catch (exception) { ... } finally { ... }

The finally block is always executed; it useful for clean-up operations.

Throwing exceptions

throw new Error(description)

Functions

Basics

function name(parameters) {
    ...;
    return <value>
}

If the return statement is omitted, undefined is return implicitly.

All functions are instances of Function object and get their methods from Function.prototype.

Roles

name(...)

Non method function.

new Name(...)

Constructor.

obj.method(...)

Method.

Defining functions

Function expression

let avar = function (...) {
    ...;
};
avar(...);

Give the function a name if self recursion is needed.

Function declaration

function name(...) {
    ...;
};

Functions are hoisted; can be called before being declared.

Function constructor

let avar = new Function(<par1>, <par2>, ..., <parN>, <body>);

Function methods

  • call()
  • apply()
  • bind()

Parameters

Missing paramenters

More formal parameters are required than the ones actually provided. The exceeding formal parameters will be valued as undefined.

Extra parameters

More actual parameters than the formal ones required are provided. Extra values can be accessed through the array like arguments special variable.

Named parameters

Parameters are mapped by name, insted by position as usual. This mechanism is not supported natively but emulated by passing an object as single actual parameter: the object properties will be the named parameters. Can be mixed with positional parameters.

Default parameters

function name(..., <parN> = <defN>, ...)

Set a default value for a parameter. Parameters starting from a default parameter will not contribute to the lenght of the function.

function name(..., <parN> = <par1>, ...)

Earlier parameters are available to later default parameters.

Rest parameter

function name(<par1>, .. , <parN>, ...<rest>)

Allows a function to accept an indefinite number of arguments. <rest> is an array object; only one is allowed.

Arrow functions

(par1, ..., parN) => {
    ...;
}

Are a compact alternative to traditional syntax.

Arrow functions have some limitations:

  • are always unnamed;
  • cannot be used as a method as they do not have an own this context;
  • they do not support binding of arguments as they do not have an own arguments object;
  • cannot be used as contructors as they do not have a prototype property;
  • cannot be used as generators as the yeld keyword cannot be used.

Variables

Declaration

  • let name = value
  • var name = value

Scope

The scope defines where the variable is accessibile.

Variables declared with the var keyword:

  • are function scoped (they are accessibile anywhere inside a function);
  • are hoisted (moved at the beginning of their direct scope).

Variables declared with the let keyword:

  • are block scoped;
  • are not hoisted.

Block scope can be simulated with and Immediately Invoked Function Expression (which alse supports parameters).

Global variables

Global variables are visible in the whole program.

Closures

Functions which stay connected to their birth scope. Variables created outside such functions and used in the functions survive after execution has left the scope.

Objects

Single objects

let obj = {
    prop1: value1,
    ...,
    propn: function() {
	...;
    }
}

Are dictionaries where a key/value pair defines a property.

Properties can be accessed with . or [] (always use [] if the property name is computed). Key is a string and value is a JavaScript value (functions included).

Constructor

Object() converts any value into an object.

Prototypal inheritance

Object.create(<prototype>)

Every object can have a prototype, specified by the Prototype object property. All prototype properties are inherited by the object. Setting and deleting properties affect only the object and not the prototype.

Overriding

Properties and methods can be redefined: this masks the propotype properties and methods with the same keys.

Sharing data

Prototype properties are shared between all objects that have that prototype.

Properties detection

for(<variable> in <object>) { ... }

Lists all enumerable properties of object.

propKey in Obj

Checks if Obj has (or has inherited) propKey.

Object.prototype.hasOwnProperty.call(<Obj>, <propKey>)

Checks if Obj has propKey.

Accessors

Accessors are methods which mask getting and setting of properties.

  • get <property> ()
  • set <property> (<value>)

Can be defined via property descriptors:

Object.prototype {
	<property> : {
	    get function() {
		...;
	    },
	    set function(<value>) {
		...;
	    }
	}
}

Are inherited from prototypes.

Object protection

Prevent extensions

Object.preventExtensions(obj)

Makes impossible to add new properties.

Sealing

Object.seal(obj)

Prevents extensions and make all properties unconfigurable.

Freezing

Object.freeze(obj)

Seals the object and makes all its properties non-writable.

Constructors inheritance

Not directly supported by the language.

Inheriting instance properties

Make explicit call the super class constructor when creating the object. Invoke it as a function passing this as parameter.

Inheriting prototype properties

Sub.prototype = Object.create(Super.prototype)

Assign sub class prototype super class prototype: this adds constructor and methods to sub class prototype.

Overriding a method

Add Sub.prototype a method with the same name of the method to override.

Making a supercall

Call the super class method via prototype passing this as parameter.

Generic methods

Object.prototype.method.call(object, parameters)

Are methods borrowed from prototypes (be them own or others).

Arrays

Creating an array

Array literal

let myarray = ['a','b','c'];

Array constructor

let a = new Array(2)

Creates an empty array of a given length (has only holes in it).

Multidimensional array

Are just nested arrays.

Indices

Index values are between 0 and 2^32-1. Any value outside of this range is treated as a property key (string).

Deleting elements

delete arr[i]

Removes the element at position i from the array (creates a hole).

Length

arr.length

Returns the highest index in the array (so it also counts the holes).

Can be set:

  • if increased, new holes are created;
  • if decreased, the exceeding elements are deleted;
  • if set to zero the array is emptied.

Holes

Holes are indices with no corresponding values; return undefined when read.

Holes can be created by assignment:

arr[0] = 'a'; arr[2] = 'c';

or by omission:

let arr = ['a','b',,'d'];

Regular expressions

Creation

Literal

/xyz/g

Constructor

new RegExp('xyz', 'g')

Properties of RegExp instance

  • global (g);
  • ignore case (i);
  • multiline (m).

Testing

<regex>.test(<string>)

Returns true if there is a match. If /g is set returns true as many times as there are matches.

<string>.search(<regex>)

Returns the index at which a match was found, or -1 if no match is found.

<regex>.exec(<string>)

Returns an array with capture groups, or null if no match is found. If /g is not set only the first match is returned.

<string>.match(<regexp>)

Returns an array with all matching substrings if /g is set, otherwise acts the same as exec.

Search and replace

<string>.replace(<search>, <replacement>)

Search term can be a string or a regular expression. If it's a string, only the first occurrence is replaced.

Replacement term can be a string or a function. If it's a string, the match is replaced verbatim; if it's a function, the function must return the term to use as a replacement.

JSON

Stores data in plain text, using objects made of key: value pairs. Values and keys must be double quoted.

Javascript / JSON conversion

JSON.stringify()

Considers only object enumerable own properties. Uses a toJSON() method if the object provides one.

JSON / Javascript conversion

JSON.parse()


© Alessandro Dotti Contra :: VAT # IT03617481209 :: This site uses no cookies, read our privacy policy for more information.