JavaScript

To Bottom

ECMA5, 6

JavaScript is specified by the European Association for Standardizing Information and Communication Systems (ECMA 5, 6) and the World Wide Web Consortium (W3C).

v8 is the C++ JavaScript interpreter used by Google Chrome.

Data types are String, Number, Boolean, Null, Undefined, and Object (typeof function() {} yields function).

Falsy values in JavaScript are: false, null, undefined, 0, NaN, "", document.all.

e.g. Boolean(document.all) == false; // Yields true

Simple equality ( == ) attempts to convert operands that are of different types before checking equality (for objects, returns true only if both reference the same object).

Strict equality operator ( === ) always considers operands of different types to be different.

Scope is divided into Global Scope, Local Scope, Function Scope and Block Scope.

Can I use...

Eloquent JavaScript by Marijn Haverbeke.

Variable name validator

regex101

Regex Cheat Sheet

Regex Numeric Range Generator

To Top

// Declarations

To Top

// Input / Output

To Top

// Strings


    var myString = '<p>The quick brown fox jumps over the lazy dog. The \
        quick brown fox jumps over the lazy dog. The quick brown fox jumps over \
        the lazy dog.</p>';
    
    const myString2 = '<p>The quick brown fox jumps over the lazy dog. The quick ' +
        'brown fox jumps over the lazy dog. The quick brown fox jumps over the ' +
        'lazy dog.</p>';
    
    // Template Literals (ES6)
    const myStringFoo = `foo is set to ${foo}. Let's say hello: ${sayHello()}`;

    const templateString = (
        `<p>How to draw an owl:</p>
        <ul>
            <li>Draw a circle</li>
            <li>Draw the rest of the owl</li>
        </ul>`
    );

    // String Methods
    .bold() // Depricated
    .fontcolor() // Depricated
    .fontsize() // Depricated
    .italics() // Depricated
    .link() // Depricated
    .small() // Depricated
    .strike() // Depricated
    .sub() // Depricated
    .sup() // Depricated
    .substr() // Deprecated
    .length // (property) Returns the number of characters in string
    .substring() Returns new string
    .slice() // Faster than substring
    const someString = 'The quick brown fox jumps over the lazy dog.';
    someString.slice(4, 19) === 'quick brown fox'
    someString.slice(-9, -5) === 'lazy'
    .replace() // Returns a new string with some or all matches of a pattern replaced
    console.log(someString.replace('lazy', 'playful'));
    .split() // Returns an array of substrings divided by a pattern - if no pattern is supplied will return an array of one element
    .test() // Returns a Boolean after searching for a match of a regular expression and a string
    /^foobar/.test(someString);
    .charAt(index)
    .trim()
    .toUpperCase()
    .toLowerCase()
    .startsWith(searchString, startPos) // Returns a Boolean (ES6)
    .endsWith(searchString, length) // Returns a Boolean (ES6)
    .repeat(numCopies) // Returns a new string of numCopies copies, concatenated (ES6)

    myInt.toString(2); // '111'
    

To Top

// Numbers


    const biggestNum = Number.MAX_VALUE;
    const smallestNum = Number.MIN_VALUE;
    const infiniteNum = Number.POSITIVE_INFINITY;
    const negInfiniteNum = Number.NEGATIVE_INFINITY;
    const notANum = Number.NaN;
    const biggestInt = Number.MAX_SAFE_INTEGER // (2**53 - 1) =>  9007199254740991
    const smallestInt = Number.MIN_SAFE_INTEGER // -(2**53 - 1) => -9007199254740991

    // Convert numeric strings and null to numbers
    Number('12.00'); // 12
    Number('123e-1'); // 12.3
    Number(''); // 0
    Number(null); // 0
    Number('0x11'); // 17
    Number('-Infinity'); // -Infinity

    parseInt(string, radix);
    parseInt(1111, 2) // 15
    parseInt('3.14 is close to Pi'); // 3
    Number('3.14 is close to Pi'); // NaN
    parseFloat(string);
    parseFloat('3.14 is close to Pi'); // 3.14
    

To Top

// Math.

To Top

// Functions


    // Function declaration
    function myFunction() {
        console.log('myFunction');
    }

    // Function expression
    function someMaths(a, b) {
        return [a + b, a * b];
    }

    // Default function default parameters (ES6)
    function exponential2(num1, num2 = 2) {
        return num1 ** num2;
    }

    // Destructuring (ES6)
    const [sum, multiple] = someMaths(3, 6);

    function printVisit({name, owner, reason = 'a check-up'}) {
        console.log(`${owner}\'s pet ${name} is here for ${reason}.`)
    }

    // Arrow functions (ES6)  
    const add = (num1, num2) => {
        return num1 + num2;
    };

    const add = (num1, num2) => num1 + num2;

    const isEven = num => num % 2 === 0
    

To Top

// Arrays


    .length // (property) Sets or returns number of elements in array
    .toString() // Returns a string representing the object
    .concat() // Merge two or more arrays
    .pop() // Remove and return last element
    .push() // Add to end and return new array length
    .shift() // Remove and return first element
    .unShift() // Add to beginning and return new length
    .slice(begin, end) // Return new array e.g myArray.slice(-3) returns new array containing last 3 elements
    .splice(start, deleteCount, item1, item2, itemN)) // Changes array in place
    .sort() // Sorts array in place (ES6)
    myNumbers.sort(function(a, b) { return a - b });
    myNumbers.sort((a, b) => b - a);
    .reverse() // Sorts array in place
    .map(callback) // Returns a new array after applying a function to each element (ES6)
    const squaredNumbers = myNumbers.map(exponential2);
    .forEach(callback) // Applies a function to each array element (ES6)
    .filter(callback) // Returns a new array(ES6)
    const evenNumbs = myNumbers.filter(num => num % 2 === 0);
    .reduce(callback) // Iterates over array while maintaining an accumulation object (ES6)
    myNumbers.reduce((total, n) => total + n);
    .find(callback) // Returns the value of the first element that satisfies the callback function (ES6)
    const found = myNumbers.find(element => element < 2);
    .includes() // Returns a Boolean based on whether array includes a value among its elements (ES6)
    Array.of() // Returns an array from a variable number of arguments (ES6)
    Array.from(object, mapFunction, thisValue) // Returns array from any object with a length property (ES6)
    const sources = Array.from(images, image => image.src);
    const secureSources = sources.filter(link => link.startsWith('https://'))
    

To Top

// Decision


    if (cookieJar < 1) {
        greeting = 'Who stole the cookie?';
    } else if (cookieJar > 3) {
        greeting = 'The cookies are low!';
    } else {
        greeting = 'Have a cookie.';
    }

    // Ternary operator
    var driverLicense = (age >= 17) ? 'full license' : 'learner permit';

    switch (expression) {
    case 'condition1':
        myProgram();
        break;
    case 'condition2': // Falls through
    case 'condition3':
        myOtherProgram();
    break;
    default:
        myDefaultProgram();
    }
    

To Top

// Loops


    // For
    for (let i = 0; i < myArray.length - 1; i++) {
        numberOfStates++;
    }

    // For...in - loops over enumerable property names of an object
    for (const prop in obj) {
        console.log(`obj.${prop} = ${obj[prop]}`);    
    }

    // forEach (ES6)
    myArray.forEach(state => console.log(`The postal code is ${state}.`));

    // For...of - uses object-specific iterator & loops over values generated by that (ES6)
    for (const element of myIterable) {
        console.log(element);
    }

    // While
    while (condition) {
        runAfterCheck();
    }

    // Do...while
    do {
        alwaysRunOnce();
    }
    while (condition);    
    

To Top

// Try / Catch / Finally


    function myFunction(index) {
        if(index < 0) throw new RangeError('index must be positive');
    }

    try {
        myFunction(-1);
    }
    catch (e) {
        console.error(e);
        if (e instanceof RangeError) console.log(e.message)
    }
    finally {
        console.log('Try again?');
    }
    

To Top

// Callbacks


    function myDisplayer(someText) {
        document.getElementById("demo").innerHTML = someText;
    }
    
    function myCalculator(num1, num2, myCallback) {
        let sum = num1 + num2;
        myCallback(sum);
    }    
    myCalculator(5, 5, myDisplayer);
    

To Top

// Elements / Attributes


    document.createElement(tagName [, options])
    document.querySelector()
    document.getElementById()
    document.getElementsByTagName()
    document.childNodes[0].nodeType
    document.childNodes[1].childNodes[0].nodeName
    document.childNodes[1].childNodes[1].nodeValue
    .appendChild()
    .insertBefore()
    .removeChild()
    .createTextNode()
    .hasAttribute()
    .getAttribute()
    .setAttribute()
    document.getElementsByTagName('p')[0].style.backgroundColor = 'green';
    .backgroundImage 
    .borderWidth 
    .borderColor 
    .focus() 
    

To Top

// Events


    // Event Properties and Methods
    event.which // Returns key or mouse button pressed
    event.currentTarget // Returns element whose event listeners triggered the event
    event.target // Returns the element that triggered the event
    event.preventDefault() // Cancels event if cancelable
    event.stopPropagation() // Prevents further propagation of an event during event flow

    document.body.onmousemove = function(e) { e = e || window.event; event.preventDefault(); console.log(e.clientX, e.clientY); }
    document.body.scrollLeft 
    document.body.scrollTop 

    .onclick
    .onmouseover
    .onmouseout 
    .ondblclick 
    .onblur 
    .onmousedown 
    .onmouseup 
    .onchange 
    .onkeypress 
    .onfocus 
    .onselect 

    window.location.hostname 
    window.location.href 
    window.location.pathName 
    window.location.reload()
    window.history.forward() 
    window.history.back() 
    window.history.go(-2) 
    

To Top

// Key Codes

Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
Key Code
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
Key Code
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

To Top

// Objects

If an object is used as an argument to a function, a reference to the original value is passed. If that argument is mutated the object is also changed.


    // Object Literals are basically singletons with variables / methods that are public
    // Appropriate for when the object is just a container for data/state
    const myContact = {
        fName: 'Joe',
        lName: 'Doe',
        address: '1234 5th Street',
        'home phone': '555-555-5555'
    }
    // Changing Object      
    delete myContact['home phone'];
    myContact.email = 'joedoe@gmail.com';
    myContact['emergency contact'] = 'Merle 555-555-1234';
    myContact.getInfo = function() {
        Object.keys(myContact).forEach(function(key) {
            console.log(`${key}: ${myContact[key]}`);
        });
    }

    // Factory Function
    function automobile(make, model) {
        return {
            make: make,
            model: model,
            tires: 4,
            flatten: function() {
                console.log(`${this.make} ${this.model} just got a flat tire!);
                if (this.wheels > 1) this.wheels--;
            },
            info: function() {
                console.log(`${this.make} ${this.model} with ${this.tires} working wheels.`);
            },
        };
    }

    class Mammal {
        constructor(name) {
            this._name = name;
        }
        get name() {
            return this._name;
        }
        set name(name) {
            this._name = name;
        }
        static makeMammal(name) {
            return new Mammal(name);
        }
        getInfo() {
            return `${this.name} is a mammal`;
        }
    }
    let monkey = new Mammal('Fred');
    monkey.name = 'Mark';
    let chipmunk = Mammal.makeMammal('Chipper');

    // Inheritance
    class Marsupial extends Mammal {
        constructor(name, hasPouch) {
            super(name);
            this._hasPouch = hasPouch;
        }
        get hasPouch() {
            return this._hasPouch;
        }
        set hasPouch(hasPouch) {
            this._hasPouch = hasPouch;
        }
        // Overriding getInfo() method
        getInfo() {
            return `${this.name} is a marsupial`;
        }
    }
    let kangaroo = new Marsupial('Paul', true);

    // Dynamically inherit class
    function getClass(classType) {
        if (classType === 1) {
            return Mammal;
        } else {
            return Marsupial
        }
    }
    class Koala extends getClass(2) {
        constructor(name) {
            super(name);
        }
    }
    let carl - new Koala('Carl');
    
    // Prototyping
    Customer.prototype.isCreditable = true;

    String.prototype.insertAt = function (index, input) {
        return this.slice(0, index) + input + this.slice(index);
    }
    String.prototype.removeAt = function (startPos, endPos) {
        return this.slice(0, startPos) + this.slice(endPos);
    }

    // Object Methods
    Object.create() // Create object with an existing object as prototype
    Object.assign(target, ...sources) // Returns target object after copying properties from sources (shallow copy)
    delete foo.bar;
    Object.defineProperty(object, property, descriptor) // Adding or changing an object property
    Object.defineProperties(object, descriptors) // Adding or changing object properties
    
    Object.getOwnPropertyDescriptor(object, property) // Accessing Properties
    Object.getOwnPropertyNames(object) // Returns an array of all properties
    Object.keys(object) // Returns array of object's property names
    Object.values()
    Object.entries() // Returns array of object's key, value pairs (same as for...in)
    .hasOwnProperty(); // Returns Boolean indicating if the object has the property

    Object.preventExtensions(object) // Prevents adding properties to an object
    Object.isExtensible(object) // Returns true if properties can be added to an object
    Object.seal(object) // Prevents changes of object properties 
    Object.isSealed(object)
    Object.freeze() // Prevents any changes to an object
    Object.isFrozen(object)

    JSON.parse() // Parses JSON into JS object
    JSON.stringify() // Converts object into JSON string
    

To Top

// Symbols


    let capital = Symbol('State Capital');
    let pennsylvania = {};
    pennsylvania[capital] = 'Harrisburg';
    console.log(`Capital of PA: ${pennsylvania[capital]}`);
    console.log(`Symbol Capital: ${capital.toString()}`);

    let employNum = Symbol.for('Employee Number');
    let bobSmith = {};
    bobSmith[employNum] = 10;
    let sallyMarks = {};
    sallyMarks[employNum] = 11;
    console.log(`Bob: ${bobSmith[employNum]}, Sally: ${sallyMarks[employNum]}`);
    

To Top

// Sets

    let mySet = new Set();
    mySet.add(10);
    mySet.add('Word');
    console.log(`Has 10: ${mySet.has(10)}`);
    console.log(`Has \'Word\': ${mySet.has('Word')}`);
    console.log(`Set Size: ${mySet.size}`);
    mySet.delete(10);
    for (let m of mySet) console.log(`Set value: ${m}`);
    

To Top

// Maps

    let myMap = new Map();
    myMap.set('key1', 'Hallo World');
    myMap.set('key2', '3.14');
    console.log(`key1: ${myMap.get('key1')}, key2: ${myMap.get('key2')}`);
    console.log(`Map size: ${myMap.size}`);
    myMap.forEach((value, key) => console.log(key, value));
    

To Top

// Timers

    setTimeout(function, milliseconds) // Executes a function after specified number of milliseconds
    setInterval(function, milliseconds) // Repeats the execution of the function continuously
    clearTimeout(timeoutVar) // Uses the variable returned from setTimeout()
    

To Top

// Promises

    let p1 = Promise.resolve('Resolve Me');
    p1.then((res) => console.log(`${res}`));

    let p2 = new Promise(function(resolve, reject) {
        setTimeout(() => resolve('Resolve Me 2'), 2000);
    });
    p2.then((res) => console.log(`${res}`));

    let myNum = 18;
    let p3 = new Promise(function(resolve, reject) {
        if (myNum === 18) {
            resolve('Good number');
        } else {
            reject('Bad');
        }
    });
    p3.then((val) => console.log(val),
    (err) => console.log(err));

    let p4 = new Promise((resolve, reject) => {
        if (myNum <= 17) { 
            throw new Error('Can\'t vote');
        } else {
            resolve('Can vote')
        }
    });
    p4.then((val) => console.log(val))
    .catch((err) => console.log(err.message));
    

To Top

// Hoisting

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.


    // var is hoisted
    a = 1;
    console.log(a);
    var a; // 1

    // let is not hoisted
    b = 2;
    console.log(b);
    let b; // Error
    
    // Initializations are not hoisted
    console.log(c);
    var c = 3; // undefined
    
    console.log(d);
    const d = 4; // Error

    hallo();
    var hallo = function() {
        console.log('Hi, there.');
    } // Error
    

To Top

HTML/CSS/JS Input

To Top

HTML Output

To Top