Javascript

Control Flow

• If Else

if(condition_1) {
    // Statements
} else if(condition_2) {
    // Statements
} else(condition_3) {
    // Statements
}

• Switch

switch(variable) {
    case label1:
        // Statements
        break;
    case label2:
        // Statements
        break;
    default:
        // Statements
}

Data Types

There are 6 primative types in JavaScript.

  • string
  • number
  • bigint
  • boolean
  • undefined
  • symbol

null is a special primative like type.

object is a more complex data structure.

• Bigint

BigInt is used to hold large integer values.

const a = 123456789012345n;
const b = BigInt(678967896789678678);

• Boolean

Boolean has two values true or false.

• Null

null means "nothing" or "empty".

var num = null;

• Number

Number in html is a 64-bit floating point number.

var x = 3.14;

There are three special numeric values for Numbers: Infinity, -Infinity, and Nan

• Object

An object in JavaScript is similar to a class in C++.

var person = {
    firstName: "Dalton",
    middleName: "Russell",
    lastName: "Cole",
    fullName: function() {
        return `${firstName:} ${middleName:} ${lastName:}`;
    }
}; // <- DON'T FORGET THE ;

• String

There are three string quote options in JavaScript:

  1. Double quotes: "Hello"
  2. Single quotes: 'Hello'
  3. Backticks: `Hello`

Double and single quotes behave identically. Backticks allow code to be embedded into a string via ${...} wrapping.

var str = "Hello World";
var str2 = 'Hola Mundo';
var str3 = `English: ${str}, Spanish: ${str2}`
var str4 = `${1 + 2}`; // '3'

Escape sequences:

  • Hexadecimal: '\xA9'
  • Unicode: '\u00A9' or '\uP00A9'

• Undefined

undefined means "value is not assigned". Variables are undefined before they are assigned.

var num; // undefined

Document Object Model

Functions

• Arrow Functions

Arrow functions is a more compact and limited version of a function expression.

var func = (arg1, arg2, ..., argN) => expression
var sum = (a, b) => a + b;
console.log(sum(5, 2);)

If only one argument exists, parentheses can be omitted:

var square = n => n ** 2

When there are no arguments, parentheses are still required.

Multi-line arrow functions require {}

var sum_square = (a, b) => {
    let sum = a + b;
    return sum ** 2;
}

• Default Values

Javascript allows default parameter values

function func(apple="Apple") {return apple;}

Default parameters can be more complex, for example, a function can be call when a value is not given and the returned value will become the variable.

function func(apple=apples())

Things to keep in mind:

  • Arguments are passed by value, objects are passed by reference. Similar to Python.
  • Functions may access outer variables
  • Functions that don't return anything return undefined

• Function Expressions

Function expressions are like lambda functions in other languages.

var sum = function(a, b) {
    return a + b;
}

var s = sum(5, 2);

• Syntax

function name(param1, param2, param3) {
    // Code
    // C++ like return statement
}

Indexed Collections

The following are equivalent:

var arr = new Array(0, 1, 2, 3);
var arr = Array(0, 1, 2, 3);
var arr = [0, 1, 2, 3]; // If single Number value, bracket syntax is required

Properties:

  • length: arr.length or arr['length']

Methods:

  • forEach: arr.forEach(n => console.log(n));
  • concat: Joins two or more arrays and returns a new array
  • join: array to string
  • push: Append element
  • pop: Remove and return last element
  • shift: Remove and return first element
  • unshift: Push element to front
  • slice: Make new array consisting of part of the array
  • reverse: reverse order
  • sort: Sorts IN PLACE
  • indexOf: Find the index of the first occurrence of an element
  • lastIndexOf: Finds the last occurrence of an element
  • map: Apply function to all elements in array and return new array
  • filter: Makes new array consisting of only values where the callback returned true
  • every: Returns true if callback returns true for every element
  • some: Returns true if callback returns true for at least one element
  • reduce: Applies callback until only one value exists

Keyed Collections

• Map

Map keeps track of key/value pairs in insertion order

let yum = new Map();
// Set key-value pairs
yum.set('apple': 8);
yum.set('banana': 10);
yum.set('chicken': 0);
// Get value
yum.get('apple'); // 8
// Check if value exists
yum.has('apple'); // true
// Delete key-value pair
yum.delete('chicken');
// Check size
yum.size; // 2

for(let [key, value] of yum) {
    console.log(key + value);
}
// Delete EVERYTHING
yum.clear();

• Set

Collects of values. Keeps track of insertion order. Elements may only occur once.

let mySet = new Set();
// Insert elements
mySet.add(1);
mySet.add('bob');
mySet.add('apple');
// Check if set as an element
mySet.has(1); // true
// Remove element
mySet.delete('bob');
// Size
mySet.size; // 2

for(let v of mySet) {
    console.log(v); // 1, 'apple'
}

Loops And Iteration

• Do While

do {
    console.log(i);
} while(i < 10);

• For In

for...in statements iterates over all the enumerable properties of an object.

var fruit = ['apple', 'banana', 'cherry']
for(var i in fruit) {
    console.log(i); // '0', '1', '2'
    console.log(fruit[i]); // 'apple', 'banana', 'cherry'
}

• For Loop

for(var i; i < 10; i++) {
    console.log(i);
}

• For Of

for...of loops through iterable objects, similar to python for..in loops.

var fruit = ['apple', 'banana', 'cherry']
for(var f of fruit) {
    console.log(f); // 'apple', 'banana', 'cherry'
}

• Label

break_both_loops: for(var i = 0; i < 10; i++) {
    for(int j = 0; j < 10; j++) {
        if(i + j >) {
            break break_both_loops;
        }
    }
}

• Tmp


• While

while(i < 10) {
    console.log(i);
}

Objects

Objects in JavaScript are essentially key-value pairs. These pairs are called properties. Methods are properties that are functions. JavaScript is a prototype-based language. There is no distinction between classes and instances of those classes. This page does a good job of explaining the differences between a class-based (C++) and prototype-based (JavaScript) language.

var person = {
    fname: 'Dalton',
    lname: 'Cole',
    fullName: function() {
        return this.fname + ' ' + this.lname;
    },
    printName: function(func=console.log) {
        func(this.fullName());
    }
};

console.log(person.fullName());     // Dalton Cole
person.printName();                 // Dalton Cole

var person2 = new Object();
person2.fname = 'Dalton';
person2.lname = 'Cole';

// Shallow Copy
var person3 = Object.assign({}, person);

person.fname = 'Colton';
person['lname'] = 'Dal';

person.printName();     // Colton Dal
person2.printName();    // Dalton Cole

• Constructor

function Person(first, last) {
    this.firstname = first;
    this.lastname = last;

    this.fullName = function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
}

let dalton = new Person('Dalton', 'Cole')
let colton = new Person('Colton', 'Dal')

dalton.fullName()
colton.fullName()

• Prototype

The prototype property allows you to add new methods to object constructors.

function Person(first, last) {
    this.firstName = first;
    this.lastName = last;
}

Person.prototype.fullName = function() {
    return this.firstName = ' ' + this.lastName;
}

Person.property.fullName2 = () => this.firstName + ' ' + this.lastName; // Won't work as expected

let dalton = new Person('Dalton', 'Cole');
console.log(dalton.fullName());     // "Dalton Cole"
console.log(dalton.fullName2());    // "undefined undefined"

Operators

• Arthmetic

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentation
/ Division
% Mod
++ Increment
-- Decrement

• Comparison

Operator Description
== Equal to, does not check type
=== Equal value and equal type
!= Not equal, does not check type
!== Not equal value or not equal type
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
?: Ternary operator

• Logical

Operator Description
&& And
|| Or
! Not

• Type

Operator Description Example
typeof Returns the type of a variable
typeof str_var; // "string"
instanceof Returns true if an object is an instance of an object type
auto instanceof Car; // true

Promises

Promises combine asynchronous execution with callbacks! Promises run asynchronously and have optional success and failure function arguments.

• Async

async causes a function to return a promise. For example, the following functions are equivalent:

async function myFunc() {
    return 'Daltie';
}

async function myFunc2() {
    // return Promise.reject('Bad Daltie!'); // Call error function
    return Promise.resolve('Daltie'); // Call success function
}

myFunc().then(value =< console.log(value));
myFunc2().then(
    value => console.log(value),
    error => console.log(error)
);

// Output
// Daltie
// Daltie

• Await

await is used inside of an async function. await waits for Promise to be fulfilled and returns the results.

Examples here.

• Chaining

Promises can be chained:


async function myFunc() {
    return 'Apples!';
}

let success = function (value) {
    console.log(value)
    return value;
}

myFunc()
    .then(success)
    .then(success)
    .then(success)
    .catch(x => console.log(x))

// Output:
// Apples!
// Apples!
// Apples!

• Syntax

Basic syntax:

let myPromise = new Promise(success_func, failure_func) {
    // Do stuff, call func(s)
}
myPromise.then(
    function(value) { /* Code if successful */ }.
    function(error) { /* Code if some error occurs */ }
);

Both the successful and error function are optional.

Basic example:

// Wait 3 seconds, then call myResolve()
let firstPromise = new Promise(function(myResolve, myReject) {
    setTimeout(function() { myResolve('Yay!'); }, 3000);
});

firstPromise.then(function(value) {
    console.log(value);
})

// Second promise. Will finish first
let secondPromise = new Promise(function(success, failure) {
    if(true) {
        success('Success');
    } else {
        failure('Failure');
    }
});

secondPromise.then(
    function(value) {console.log(value);},
    function(error) {console.log(error);}
);

// Output:
// Success
// Yay!

Strict Mode

Strict mode forces the programmer to code properly (in a matter of speaking). It removes some older parts of JavaScript. Check this for more details.

To enable strict mode, add this to the top of the JavaScript file or function body:

'use strict';

Type Conversions

var value = 1;
value = String(value); // "1"
value = Number(value); // 1
value = Boolean(value); // true

Variables

• Const

const variables are variables that behave like let but cannot be reassigned.

• Let

let declares a block-scope variable.

• Var

var variables are function-scoped or globally-scoped variables. A var variable can be declared anywhere, including after it is used, for example, at the bottom of a function that uses the variable.