Skip to content

Instantly share code, notes, and snippets.

@kzhangkzhang
Last active February 22, 2024 20:50
Show Gist options
  • Save kzhangkzhang/6530f8ab5c8a6985aab51a2884d3beac to your computer and use it in GitHub Desktop.
Save kzhangkzhang/6530f8ab5c8a6985aab51a2884d3beac to your computer and use it in GitHub Desktop.
Modern Javascript (ES6) cheat sheet part B

Modern JavaScript Cheat Sheet - Part B

Support\Web_Cloud\WEB_Javascript_B.md

Classes and Modules

Class Basics

- using CamelCase convention for naming class
- first letter is UPPERCASE
// example
class Cruise {}

let firstCruise = new Cruise();

Constructors and Properties

// example
class Cruise {
  constructor(cruiseDate) {
    this.cruiseDate = cruiseDate; // need use this keyword
  }
}

let cruise2018 = new Cruise("22-DEC-2018");
console.log(cruise2018.cruiseDate);

Methods

- don't need keyword "function" when define class method
class Cruise {
  constructor(cruiseDate, cruiseLine) {
    this.cruiseDate = cruiseDate;
    this.cruiseLine = cruiseLine;
  }

  greeting() {
    return `I will cruise on ${this.cruiseDate} with ${this.cruiseLine}`;
  }
}

let cruise2018 = new Cruise("22-DEC-2018", "NCL Bliss");
console.log(cruise2018.greeting());
// I will cruise on 22-DEC-2018 with NCL Bliss

Inheritance

- use extends (don't forget 's')
- using **super** to refer parent class
class Vacation {
  constructor(vacationType, vacationDate) {
    this.vacationType = vacationType;
    this.vacationDate = vacationDate;
  }

  greeting() {
    return `I will have a ${this.vacationType} vacation on ${
      this.vacationDate
    }`;
  }
}

class CruiseVacation extends Vacation {
  constructor(cruiseDate, cruiseLine, days) {
    super("Cruise", cruiseDate);
    this.cruiseLine = cruiseLine;
    this.days = days;
  }

  greeting() {
    return `${super.greeting()} with ${this.cruiseLine} for ${this.days} days`;
  }
}

let cruise2018 = new CruiseVacation("22-DEC-2018", "NCL Bliss", 7);
console.log(cruise2018.greeting());
// I will have a Cruise vacation on 22-DEC-2018 with NCL Bliss for 7 days

Moduels

- ES6 modules now have strict mode enabled by default (no 'use strict' is required).
// Moduel definition File: src/models/cruise.js
export class Cruise {
  constructor(cruiseDate) {
    this.cruiseDate = cruiseDate; // need use this keyword
  }
}

// Testing file: src/test.js
import { Cruise } from "./models/cruise.js";

let cruise2018 = new Cruise("22-DEC-2018");
console.log(cruise2018.cruiseDate);

BOM and DOM

- BOM: Browser Object Model
- DOM: Document Object Model

The BOM (Browser Object Model) consists of the objects navigator, history, screen, location and document which are children of window. In the document node is the DOM (Document Object Model), the document object model, which represents the contents of the page. You can manipulate it using javascript.

The window Object

- Properties
    - document
    - location
    - console
    - innerHeight
    - innerWidth
    - pageXOffset
    - pageYOffset

- Methods
    - alert()
    - back()
    - confirm()

- Events
    - not commonly used
console.log(window.innerWidth);
console.log(window.innerHeight);

Timers

let intervalId = setInterval(function() {
  console.log("2 seconds passed");
}, 2000);

// to cancel it
clearInterval(intervalId);

location

- Properties
    - href
    - hostname
    - port
    - protocol
    - pathname
    - search

- Methods
    - assign()
    - reload()

  - Events
    - not commonly used
// Example: open www.google.com and try below
console.log(location.href); // https://www.google.com/
console.log(location.hostname); // www.google.com
console.log(location.pathname); // /
console.log(location.protocol); // https:

document Object

- Properties
    - body
    - forms
    - links
- Methods
  - createElement()
  - createEvent()
  - getElementById()
  - getElementByClassName()
  - getElementByTagName()
  - querySelect()
  - querySelectAll()
- Events
  - onload
  - onclick
  - onkeypress

Selecting DOM Elements

document.getElementById("firstName");
document.getElementByClassName("cool");
document.getElementByTagName("a");

Modifying DOM Elements

let el = document.getElementById("elementId");
el.textContext = "new text here";
el.setAttribute("name", "nameValue");
el.classList.add("myClassName");
el.classList.remove("myClassName");
el.style.color = "red";

Promises and Error Handling

try and catch

try {
  let cruise2018 = new cruise();
} catch (error) {
  console.log("something went wrong: ", error);
}
console.log("let's continue executing ...");
// let's continue executing ...

try, catch and finally

try {
  let cruise2018 = "new cruise()";
} catch (error) {
  console.log("something went wrong: ", error);
} finally {
  console.log("this will always executes");
}

User Defined Error

try {
  let salary = -1000;
  if (salary < 0) {
    throw new Error("Salary is negative");
  }
} catch (error) {
  console.log("something went wrong: ", error);
} finally {
  console.log("this will always executes");
}

Creating a Promise

  • function(resolve, reject)
let myPromise = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, "++ promise is resolved");
});

console.log(myPromise);

Settling a Promise

  • then(fullfilledFn, rejectedFn)
let myPromise1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, "++ promise is resolved");
});

let myPromise2 = new Promise(function(resolve, reject) {
  setTimeout(reject, 200, "*** promise is rejected");
});

myPromise1.then(
  value => console.log("resolved: ", value),
  error => console.log("rejected: ", error)
);

myPromise2.then(
  value => console.log("resolved: ", value),
  error => console.log("rejected: ", error)
);

Data Access Using HTTP

HTTP Requests using XHR

// Method A: old syntax
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (this.readyStatus === 4 && this.status === 200) {
    console.log(this.responseText);
  }
};

xhr.open(
  "GET",
  "http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
  true
);

xhr.send();

// Method B: preferred
// Source: BradTraversy - Udemy: ModernJSFromBeginning|Section7
document.getElementById('button').addEventListener('click', loadData);

function loadData() {
    // Create an XHR Object
    const xhr = new XMLHttpRequest();

    // Open
    xhr.open('GET', 'test.txt', true);

    console.log('READYSTATE', xhr.readyState);

    // Optional - Used for spinners/loaders
    xhr.onprogress = function () {
        console.log('READYSTATE', xhr.readyState);
    }

    // Method A: onload property is fairly new
    // this is preferred over method A
    xhr.onload = function () {
        console.log('READYSTATE', xhr.readyState);
        if (this.status === 200) {
            document.getElementById('output').innerHTML =
                `<h1>${this.responseText}</h1>`
        }
    }

    // readyState Values
    // 0: request not initialized
    // 1: serer connection established
    // 2: request received
    // 3: processing request
    // 4: request finished and response is ready


    // HTTP Status
    // 200: "OK"
    // 403: "Forbidden"
    // 404: "Not Found"

    // error handling
    xhr.onerror = function () {
        console.log('request error ...');
    }

    xhr.send();
}

HTTP Requests Using jQuery

  • let promise = $.get(url);
<!-- npm install jquery -->
import $ from "jquery";

let myPromise = $.get(
  "http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users"
);

myPromise.then(
  data => console.log("+++success: ", data),
  error => console.log("***error: ", error)
);

HTTP POST Using jQuery

  • let promise = $.post(url, data)
<!-- npm install jquery -->
import $ from "jquery";

let kevin = {
  name: "Kevin Zhang",
  avatar: "kevin.jpg"
};
let myPromise = $.post(
  "http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
  kevin
);

myPromise.then(
  data => console.log("+++success: ", data),
  error => console.log("***error: ", error)
);

Forms

Prevent Form Submission

let myForm = document.getElementById("my-form");

myForm.addEventListener("submit", event => {
  // prevent the browser from submitting the form
  event.preventDefault();
});

Accessing Form Fields

let myForm = document.getElementById("my-form");

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

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

  // prevent the browser from submitting the form
  event.preventDefault();
});

Showing Validation Errors

Form Field

let myForm = document.getElementById("my-form");

myForm.addEventListener("submit", event => {
  let user = myForm.elements["user"];
  let userError = document.getElementById("user-error");

  if (user.value.length < 4) {
    userError.textContent = "Invalid Entry";
    userError.style.color = "red";
    userError.style.borderColor = "red";
    user.focus();

    // prevent the browser from submitting the form
    event.preventDefault();
  }
});

Posting from JavaScript

Instead of posting name-value-pair, somethings, we just want to post data as object literal (e.g. JSON) to the server. In below, because we are posting data ourselves (via jQuery), make sure you call preventDefault()

import $ from "jquery";

let myForm = document.getElementById("my-form");

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

  let postingData = {
    user: user.value,
    avatarFile: avatarFile.value
  };

  let myPromise = $.post(
    "http://5bf87814c480680013bc7d9b.mockapi.io/api/v1/users",
    postingData
  );

  myPromise.then(
    data => console.log("+++success: ", data),
    error => console.log("***error: ", error)
  );

  // prevent the browser from submitting the form
  event.preventDefault();
});

Security and Production Build

eval() function

Read this in more details

let inputString = "console.log('we will go cruise');";

eval(inputString); // we will go cruise

Prevent Man-in-the-middle Attack

  • use SSL
  • use HTTP Header: Strict-Transport-Security
  • Use cookie attributes: Secure and HttpOnly

Addressing Cross-site Scripting (XSS) Attack

  • CSP: Content Security Policy
    • Use HTTP Header: Content-Security-Policy

CORS: Cross Origin Resource Sharing

  • Use HTTP Header: Access-Control-Allow-Origin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment