JavaScript (JS)

JavaScript (JS) is an interpreted programming and scripting language used in web browsers to make websites more interactive and user-friendly. JavaScript enables web pages to dynamically access and modify their content and markup while they are being viewed in the browser.

const header = document.getElementById('headerMain');

header.textContent = 'This is a new header!';

JavaScript Syntax

Comments

Comments can explain what the code is doing, leave instructions for developers using hte code, or add any useful annotations.

// This is a single-line comment
/*

This is a multi-line comment

*/

Data Types

Data types are the classifications we give to different kinds of data that we use in programming.

Primitive data types are the most basic data types in the language. Objects are more complex.

Number

Any number, including numbers with decimals.

BigInt

Any number, greater than 253-1 or less than -(253-1), with n appended to the number: 1234567890123456n.

String

Any grouping of characters on the keyboard (letters, numbers, spaces, symbols, etc.) surrounded by single quotes or double quotes.

Boolean

This data type only has two possible values — either true or false.

Null

This data type represents the intentional absence of a value.

Undefined

This data type represents the complete absence of a value - it does not exist.

Symbol

Symbols are unique identifiers that are useful in more complex coding.

Object

A collection of related data.

Operators

An operator is a character that performs a task.

  • + - Add
  • - - Subtract
  • * - Multiply
  • / - Divide
  • % - Remainder or modulo
3 + 4
5 - 1
4 * 2
9 / 3

Properties & Methods

Data types have access to specific properties that are passed down to each instance.

The . is called the dot operator.

'Hello'.length

Methods are actions we can perform. Data types have access to specific methods that allow us to handle instances of that data type.

We call these methods with the dot operator, the name of the method, and opening and closing parentheses.

'lowercase'.toUpperCase();
'UPPERCASE'.toLowerCase();
'Hey'.startsWith('H');
'  Too much room  '.trim();

Array Methods

arr.filter()
arr.sort()
arr.map()
arr.reduce()
arr.find()

Built-In Objects

Standard built-in objects

Built-in objects are full of useful functionality.

Built-in objects have methods.

console
Math
Number
console.log();
Math.random();
Math.floor(Math.random() * 100); // rounded down whole number
Math.ceil(Math.random() * 100);  // rounded up whole number
Math.ceil(43.8);
Number.isInteger(2017)

Math

Number

JavaScript Basics

Adding JavaScript to an HTML Document

JavaScript code runs where it is found in the document.

Inside an HTML File

<script>
  document.write('<h3>' + Welcome! + '</h3>');
</script>

Linking to an External JavaScript File

<script src="js/add-content.js" type="text/javascript"></script>

JavaScript Syntax

Comments

// This is a single-line comment
/*  This is a
multi-line comment */

Variables & Data Types

  • const - Block-scoped = only accessible within the block it's declared in. Can't be re-assigned or re-declared.
  • let - Block-scoped = only accessible within the block it's declared in. Can be re-assigned but not re-declared.
  • var (not recommended) - Function-scoped = accessible within the entire function or globally. Can be re-assigned and re-declared.
// Creating Variables

const price;  // Declaring the variable
quantity = 5; // Assigning the variable
// Shorthand

const price = 5;
let quantity = 20;
let total = price * quantity;

// Declaring and Assigning Multiple Variables

let price, quantity, total;
let price = 5, quantity = 20, total = price * quantity;

const birthdate = '7-17-1996';
let x = 10;
var isEven = false;
var nope = null;

Arrays

// Array Literals

const colors = ['red', 'white', 'blue'];

// Array Constructors

const colors = new Array('red', 'white', 'blue');
// Accessing items in an array

colors[0];
colors.length;

// Changing items in an array

colors[2] = 'gold';

// Adding items to an array

colors.push('purple');

// Removing items in an array

colors.splice(1, 1); // Removes index 1 and only 1 element

Conditionals

if (x > 5) {
  // Code for only if x is more than 5
}
if (day == 'Tuesday') {
  // Code for only if the day is Tuesday
} else {
  // Code for all other days
}
if (cash > 1000) {
  // This user has more than $1000
} else if (cash > 100) {
  // This user has more than $100 but less than $1000
} else {
  // This user has less than $100
}

Loops

For Loop

userRoutines.forEach(routine => {
  console.log(routine);
})
// For Loop

for (let i = 0; i < 5; i++) {
  console.log(i);
}
for (const [key, value] of Object.entries(json.data.actions)) {
  if (value.cost > 0) {
    console.log(value);
  }
}
const names = ['Grant', 'Rico', 'Bobby'];
const mapped = names.map((name) => name + '2');

Objects

Objects are models of world using data, and are made up of properties and methods.

Properties are variables in an object.

Methods are functions in an object.

// Object Literals

let hotel = {
  name: 'Marriott',
  rooms: 40,
  booked: 25,
  checkAvailability: function(){
    return this.rooms - this.booked;
  }
}

// Accessing items in an object

hotel.name    // Dot notation
hotel['name'] // Bracket notation

ECMAScript 2015 (ES6)

ECMAScript 2015 (ES6) is a ECMAScript standard which fundamentally transformed JavaScript development. It introduced a vast array of new features, making the language more readable, efficient, and capable of handling modern web development needs.

Destructuring Assignment

A convenient way to extract values from arrays and objects into distinct variables.

// Without destructuring
const name = req.body.name;
const age = req.body.age;

// With destructuring
const { name, age } = req.body;

Modules (Import/Export)

There are two types of importing and exporting: default and named.

Named Exports
export const greeting = "Hello, Grant!";
const greeting = "Hello, Grant!";

export { greeting };
import { greeting } from './named.js';
Default Exports
export default "Hello, Grant!";
const greeting = "Hello, Grant!";

export default greeting;
import greeting from './named.js';

Classes


Promises

A Promise is an object that represents the eventual state of an asynchronous operation - either a success or a failure.

A Promise can be in one of three states:

  • Pending - still waiting
  • Fulfilled (resolved) - completed successfully
  • Rejected - failed with an error

Rest and Spread Operators

JavaScript Functions

Creating a JavaScript Function

// Declaring the function

function doTheThing() {
  console.log('We did the thing!');
}

// Calling the function

doTheThing();

// Parameters & Arguments

// The variables used in the code block (width and height) are called parameters
// The values passed in (5 and 3) are called arguments

function getArea(width, height) {
  return width * height;
}

console.log(area(5, 3));

Function Expression

Functions are hoisted and have their own this context.

const area = function(width, height) {
  return width * height;
}

console.log(area(5, 3));

Arrow Function Expression

Arrow functions are not hoisted, can't be reassigned, this is lexically scoped, and are common in React.js components.

const welcome = () => 'Welcome!';

welcome();
const welcome = (name) => `Welcome, ${name}!`;

welcome('Grant');
const welcome = () => {
  return 'Welcome!';
}

welcome();
const welcome = (name) => {
  return `Welcome, ${name}!`;
}

welcome('Grant');
const area = (width, height) => width * height;

console.log(area(5, 3));
const welcome = (first, last) => {
  return `Welcome, ${first} ${last}!`;
}

welcome('Grant', 'Davis');

Immediately Invoked Function Expression (IIFE)

An Immediately Invoked Function is a function that runs as soon as its defined. It is also known as a self-executing anonymous function.

(function() {
  console.log('This is an immediately invoked function!');
}());
(function() {
  const width = 5;
  const height = 12;
  return width * height;
}());

Arrow Function IIFE

(() => {
  console.log('This is an immediately invoked function!');
})();
(() => console.log('This is an immediately invoked function!'))();

Asynchronous (Async) Functions

Async, or asynchronous, functions happen in the background.

Await functions wait for a response.

A promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.

Await is only valid in async functions and the top level bodies of modules. Await can't exist in a regular function. Async functions with no await will return a promise.

// This will work and return the requested JSON data

async function printData() {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/1');

  console.log(data);
}

printData();

// This will not work and will return a promise pending message

async function printData() {
  const data = fetch('https://jsonplaceholder.typicode.com/posts/1');

  console.log(data);
}

printData();

// This will not work and will return a syntax error

function printData() {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/1');

  console.log(data);
}

printData();
// Put promise stuff here

Document Object Model (DOM) Methods & Properties

document.getElementById('sideNavigationMenu');

The Document Object Model (DOM) provides methods that allow JavaScript to interact with, traverse, and modify HTML or XML documents dynamically.

  • Live Collection - An auto-updating list of elements.
  • Static Collection - Fixed snapshot at the time of the query.

Document Selection Methods

Note: These methods can ONLY be used on the document model. You can not do something like container.getElementById(id).

  • document.getElementById(id) — Returns the element with the specified ID
  • document.getElementsByClassName(className) — Returns a live collection of elements with the specified class
  • document.getElementsByTagName(tagName) — Returns a live collection of elements with the given tag name
  • document.querySelector(selector - #id or .class) — Returns the first element matching a CSS selector
  • document.querySelectorAll(selector - #id or .class) — Returns all elements matching a CSS selector

Element Selection Methods

Note: These methods ONLY search within an element and NOT the whole document object.

  • element.querySelector(selector - #id or .class) — Returns the first element matching a CSS selector
  • element.querySelectorAll(selector - #id or .class) — Returns all elements matching a CSS selector

Element Creation & Manipulation Methods

  • document.createElement(tagName) — Creates a new element
  • document.createTextNode(text) — Creates a text node
  • element.appendChild(child) — Appends a child element to a parent
  • element.insertBefore(newNode, referenceNode) — Inserts a node before another node
  • element.append(...nodesOrStrings) — Appends multiple nodes or strings
  • element.prepend(...nodesOrStrings) — Inserts nodes or strings at the beginning
  • element.insertAdjacentHTML(position, htmlString) — Inserts HTML at positions like 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
  • element.remove() — Removes the element itself
  • element.replaceWith(newNodeOrString) — Replaces the element with another node or string
  • element.cloneNode(deep) — Clones a node (optionally including children)

Attribute & Property Methods

Note: setAttribute will override if used multiple times. Combine or use classList.add insted.

  • element.getAttribute(name) — Gets an attribute value
  • element.setAttribute(name, value) — Sets an attribute value. Set multiple with (name, val1 val2)
  • element.hasAttribute(name) — Checks if an attribute exists
  • element.removeAttribute(name) — Removes an attribute
  • element.textContent — Gets/sets all text content
  • element.innerHTML — Gets/sets HTML content
  • element.innerText — Gets/sets visible text only
  • element.classList — Provides methods: add(), remove(), toggle(), contains(), replace()
  • element.style.propertyName = value — Inline style manipulation

Event Handling Methods

  • element.addEventListener(event, handler) — Attaches an event handler
  • element.removeEventListener(event, handler) — Removes an event handler
  • element.dispatchEvent(event) — Manually triggers an event
  • event.preventDefault() — Prevents default browser behavior
  • event.stopPropagation() — Stops event bubbling
  • event.target — Element that triggered the event
  • event.currentTarget — Element the listener is attached to

Traversal & Navigation Methods

  • element.parentNode / element.parentElement — Gets the parent node/element
  • element.childNodes — Returns all child nodes, including text nodes
  • element.children — Returns only element-type children
  • element.firstChild / element.lastChild — First/last child node
  • element.firstElementChild / element.lastElementChild — First/last child element
  • element.nextSibling / element.previousSibling — Adjacent nodes
  • element.nextElementSibling / element.previousElementSibling — Adjacent element nodes
  • element.closest(selector) — Finds the nearest ancestor (including itself) matching a selector
  • element.matches(selector) — Checks if element matches a selector

Document Utility Methods

  • document.createDocumentFragment() — Creates a lightweight container for building DOM structures
  • window.getComputedStyle(element) — Reads computed CSS styles
  • element.scrollIntoView() — Scrolls element into view
  • document.body, document.head, document.documentElement — Core document references
  • document.write(string) — Writes HTML to the document (not recommended)
  • document.open() / document.close() — Opens/closes document stream

Document Object Model (DOM) Events

document.addEventListener('DOMContentLoaded', addOpenToggle);

Document Object Model (DOM) events are things JavaScript can listen for and react to, like when a page loads, when the browser is resized, or when a button is clicked.

Mouse Events

  • click — When the element is clicked
  • dblclick — When double-clicked
  • mousedown — When mouse button is pressed down
  • mouseup — When mouse button is released
  • mouseover — When cursor enters the element
  • mouseout — When cursor leaves the element
  • mousemove — When mouse moves over the element
  • contextmenu — Right-click (context menu)

Keyboard Events

  • keydown — When a key is pressed down
  • keypress (deprecated) — (Old, replaced by keydown/keyup)
  • keyup — When a key is released

Form & Input Events

  • input — Whenever input value changes (live)
  • change — When input loses focus and value changed
  • focus — When element gains focus
  • blur — When element loses focus
  • submit — When a form is submitted
  • reset — When a form is reset

Window / Document Events

  • DOMContentLoaded — When DOM is ready (scripts can safely run)
  • load — When entire page (including images) is loaded
  • beforeunload — Before page is closed/refreshed
  • resize — When window is resized
  • scroll — When page or element is scrolled

Touch & Pointer Events (Mobile + Tablets)

  • touchstart — Finger touches screen
  • touchmove — Finger moves on screen
  • touchend — Finger lifts off screen
  • pointerdown / pointerup / pointermove — Unified mouse/touch events

Media Events (Audio/Video)

  • play — Media starts playing
  • pause — Media is paused
  • ended — Media playback finished
  • timeupdate — Playback time updates
  • volumechange — Volume changes

Miscellaneous / Other Useful Events

  • animationstart / animationend — CSS animation start/end
  • transitionend — CSS transition finishes
  • dragstart / dragover / drop — Drag-and-drop interactions
  • error — Error occurs in image, script, etc.
  • visibilitychange — Tab visibility changes (user switches tab)

Manipulating the DOM Examples

Accessing Elements on the Page

// Accessing specific elements on the page by ID

const mainHeader = document.getElementById('mainHeader');

// Accessing specific elements (or groups of elements) by Class name

const allPageSections = document.getElementsByClassName('pageSection');

// Seeing the values of elements

mainHeader.textContent;
dropdownOptions.value;
filePath.value.length;

Changing Elements on the Page

// Changing the content of a specific element

mainHeader.textContent = 'This is an updated header title!';
arrow.src = './assets/down_arrow.svg';

// Removing the content of a specific element

mainHeader.textContent = '';

// Changing the CSS of a specific element

mainHeaderBlock.style.display = 'none';
mainHeaderBlock.style.display = 'block';
mainHeaderBlock.style.backgroundColor = 'blue';

Adding Elements to the Page

// Creating new elements

const newFilePathContainer = document.createElement('div');
const newFilePathInput = document.createElement('input');

// Setting new element attributes

newFilePathContainer.setAttribute('id', `filePathContainer_${addedFilePathsCount}`);
newFilePathInput.setAttribute('name', 'filePath');
newFilePathInput.setAttribute('size', '50');

// Adding elements inside one another

newFilePathContainer.appendChild(newFilePathInput); // Has to be an element, can't be a string

addedFilePaths.append(newFilePathContainer);      // Adds after the last element in the parent div
addedFilePaths.append(newElement1, newElement2);
addedFilePaths.prepend(newFilePathContainer);     // Adds before the first element in the parent div
addedFilePaths.prepend(newElement1, newElement2);

// Adding elements inside one another at a specific location

newElement.insertBefore(referenceElement);

referenceElement.insertAdjacentElement('beforebegin', newElement); // Positions: beforebegin, afterbegin, beforeend, afterend
referenceElement.insertAdjacentHTML('beforebegin', newElement);
referenceElement.insertAdjacentText('beforebegin', newElement);

Removing Elements from the Page

// Removing specific elements you can individually access by ID or Class name

newFilePathInput.remove();

// Removing all child elements in a parent element

mainHeaderContainer.textContent = '';

Listening for Events

const addFilePathButton = document.getElementById("addFilePathButton");

// Adding Event Listeners

addFilePathButton.addEventListener("click", addFilePathContainer);   // Runs the code when clicked
addFilePathButton.addEventListener("click", addFilePathContainer()); // Runs the code right away and when clicked, the return value would be called

addFilePathButton.addEventListener("click", addFilePathContainer() {
  doTheThing();
});

// Removing Event Listeners

title.removeEventListener('click', hideContent);
title.removeEventListener('click', showContent);

Manipulating Time

// Setting a time interval to execute specific code (in milliseconds)

setInterval(generateMessage, 100);

setInterval(() => {
  console.log('Hi there!');
}, 1000);

// Waiting a set amount of time to execute a specific function or code block

setTimeout(printHello, 1000);

setTimeout(() => {
  copiedMessageAlert.textContent = '';
}, 1000);

// Waiting a set amount of time in a loop

setTimeout(() => {
  counter.textContent = i;
}, i * 1000);

Using the Clipboard

// Copying content to the clipboard

navigator.clipboard.writeText('This is a copied message!');

navigator.clipboard.writeText(copiedMessage);

Error Handling (Try/Catch/Finally/Throw)

The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

function getMoney(string) {
  try {
    couldThrowError();
  } catch {
    console.log('An error occurred!');
  }
}

function couldThrowError() {
  let num = Math.random();
  let decider = 0.5;

  if (num > decider) {
    console.log(`The number is above 0.5!`)
  } else {
    throw 'The number is not above 0.5!'
  }
}

getMoney();
async function fetchWeatherData() {
  try {
    console.log('Trying something...');
  } catch (error) {
    console.log('We ran into an error: ', error);
  }
}

Using the Fetch API

Note: You can't fetch local files due to CORS. The files need to be served from a server.

function getWeatherData() {
  const stringParams = {
    "url": "http://api.weatherapi.com",
    "path": "/v1/forecast.json?",
    "alerts": "no",
    "aqi": "no",
    "days": 1,
    "key": "b9e5ea5a01104ae4b0b153407251104" // Need to hide
  }

  const queryParamsString = formatStringParams(stringParams);

  const options = {
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "max-age=60480"
    },
  };

  const url = new Request(queryParamsString, options);

  fetch(url)
    .then(
      (response) => {
        return response.json(); // response.text(); if the content-type is text
      }
    )
    .then(
      (data) => {
        console.log(data);
      }
    )
    .catch(
      () => console.log('We ran into a MF error.')
    );
}

Managing Cookies

Note: Cookies need HTTP to work. They do not work on local files.

// Setting a cookie

document.cookie = "username=grant; max-age=60; Secure"; // Expiry time is in seconds

// Seeing all cookies

allCookies = document.cookie;