Javascript

Usage and History


Language Features

Constants - variable that cannot change

Variable Declarations

Rest Parameters

Destructuring Arrays

let carIds = [1, 2, 5];
let [car1, car2, car3] = carIds;
// with rest parameters:
let car1, remainingCars;
[car1, ...remainingCars] = carIds
// log
// 1 [2, 5]

Destructuring Objects

let car = { id: 5000, style: "convertible" }
let { id, style } = car;
// log
// 5000, convertible
let id, style;
({id, style} = car);

Spread Syntax

let carIds = [100, 300, 500];
startCars(...carIds);

typeof()

typeof(1);              // 'number'
typeof(true);           // 'boolean'
typeof('Hello')         // 'string'
typeof(function() {});  // 'function'
typeof({});             // 'object'
typeof(null);           // 'object'
typeof(undefined)       // 'undefined'
typeof(NaN);            // 'number'
// NaN - not a number

Common Type Conversions

Controlling Loops


Operators

Equality operators

Unary operators

Logical (Boolean) operators

Relational Operators

Conditional Operators

Assignment Operators

Operator Precendence

Full Chart


Functions and Scope

Function scope

Block scope

(function () {
    console.log('in function');
})();
// can return values this way
let app = (function () {
    let carId = 123;
    console.log('in function');
    return {};
})();

console.log(app);
// [Function: app]

Closures

let app = (function() {
    let carId = 123;
    let getId = function() {
        return carId;
    };
    return {
        getId: getId    //  reference
    };
})();
console.log(app.getId());
// 123

The this keyword

let o = {
    carId: 123,
    getId: function() {
        return this.carId;
    }
};
console.log(o.getId());
// 123

Call and apply

// call ex:
let newCar = { carId: 456 };
console.log(o.getId.call(newCar)); //456
// apply ex
/*
getId: function (prefix) {
    return prefix + this.carId;
}
*/
console.log(o.getId.apply(newCar, ['id: ']))
// ID: 456

Bind

Arrow Functions

let getId = prefix => prefix + 123;
console.log(getId('ID: '));         // ID: 123

let getId = (prefix, suffix) => prefix + 123 + suffix;
console.log(getId('ID: ', '!'));    // ID: 123!

// with braces / return keyword required
let getId = (prefix, suffix) => {
    return prefix + 123 + suffix;
};
// same result as previous

// use with underscore:
let getId = _ => 123;

Arrow functions do NOT have their own this value. this refers to enclosing context

Default Parameters

let trackCar = function(carId, city='NY') {
    // using backticks for interpreting variables
    console.log(`Tracking ${carId} in ${city}.`);
}

Objects and Arrays

Constructor Functions

function Car() { }          // capitalized name as convention`
let car = new Car();
function Car(id) {
    this.carId = id;
}
let car = new Car(123);
console.log(car.carId);     // 123
function Car(id) {
    this.carId = id;
    this.start = function () {
        console.log('Start: ' + this.carId);
    };
}
let vehicle = new Car(123);
vehicle.start();            // Start: 123

Prototypes

// using previous example
Car.prototype.start = function() {
    console.log('Start: ' + this.carId);
}   // single copy, instead of one function for each object
String.prototype.hello = function() {
    return this.toString() + ' Hello';
};
console.log('foo'.hello());     // foo Hello

Javascript Object Notation (JSON)

let car = {
    id: 123,
    style: 'convertible'
};
console.log(JSON.stringify(car));
// { "id": 123, "style": "convertible" }
// Array to JSON
let carIds = [
    { carId: 123 },
    { carId: 456 },
    { carId: 789 }
];
console.log(JSON.stringify(carIds));
//  [{ "carId": 123 }, { "carId": 456 }, ...]
// Parsing JSON:
let jsonIn = [{ "carId": 123 }, { "carId": 456 }, { "carId": 789 }];
let carIds = JSON.parse(jsonIn);
// log: [ { carId: 123 }, { carId: 456 }, { carId: 789 } ]

Array Iteration

Examples:

carIds.foreach(car => console.log(car));
carIds.foreach((car, index) => console.log(car, index));

//  only some elements
let convertibles = carIds.filter(car => car.style === 'convertible');

// every case. find, condition, T/F, all elements
let result = carIds.every(car => car.carId > 0);    // true

// retrieve first instance matching condition
let car = carIds.find(car => car.carId > 500);

Classes and Modules

class Car { };
let car = new Car();

Constructors and properties

Methods

Inheritance

class Car extends Vehicle {
    constructor() {
        super();    // refers back to parent Vehicle
    }
    start() {
        return 'In Car Start' + super.start();
    }
}

Creating and Importing a Module


Programming the BOM and DOM

Window Object

Timers


Location object


Document Object


Selecting DOM Elements

Modifying DOM Elements


Promises and Error Handling

Errors in Javascript


Data Access Using HTTP

HTTP Requests using XHR


Forms

Preventing Form Submission

Accessing Form Fields

form.addEventListener('submit', event => {
    let user = form.elements['user'];
    let avatarFile = form.elements['avatar-file'];

    console.log(user.value, avatarFile.value);
});

Showing Validation Errors

javascript let userError = document.getElementById('user-error'); userError.textContent = 'Invalid Entry'; userError.style.color = 'red'; user.style.borderColor = 'red'; user.focus();

Posting from Javascript

post, data to object levels from form


Chrome Dev Tools and Security

Security and the eval() function

Preventing Man-in-the-Middle Attacks

Cross-site Scripting (XSS)

Building Your Application for Production