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!';
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 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.
An operator is a character that performs a task.
+ - Add- - Subtract* - Multiply/ - Divide% - Remainder or modulo3 + 4
5 - 1
4 * 2
9 / 3
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();
arr.filter()
arr.sort()
arr.map()
arr.reduce()
arr.find()
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)
JavaScript code runs where it is found in the document.
<script>
document.write('<h3>' + Welcome! + '</h3>');
</script>
<script src="js/add-content.js" type="text/javascript"></script>
// This is a single-line comment
/* This is a
multi-line comment */
// 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;
// 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
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
}
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 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) 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.
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;
There are two types of importing and exporting: default and named.
export const greeting = "Hello, Grant!";
const greeting = "Hello, Grant!";
export { greeting };
import { greeting } from './named.js';
export default "Hello, Grant!";
const greeting = "Hello, Grant!";
export default greeting;
import greeting from './named.js';
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:
// 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));
Functions are hoisted and have their own this context.
const area = function(width, height) {
return width * height;
}
console.log(area(5, 3));
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');
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;
}());
(() => {
console.log('This is an immediately invoked function!');
})();
(() => console.log('This is an immediately invoked function!'))();
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.getElementById('sideNavigationMenu');
The Document Object Model (DOM) provides methods that allow JavaScript to interact with, traverse, and modify HTML or XML documents dynamically.
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 IDdocument.getElementsByClassName(className) — Returns a live collection of elements with the specified classdocument.getElementsByTagName(tagName) — Returns a live collection of elements with the given tag namedocument.querySelector(selector - #id or .class) — Returns the first element matching a CSS selectordocument.querySelectorAll(selector - #id or .class) — Returns all elements matching a CSS selectorNote: 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 selectorelement.querySelectorAll(selector - #id or .class) — Returns all elements matching a CSS selectordocument.createElement(tagName) — Creates a new elementdocument.createTextNode(text) — Creates a text nodeelement.appendChild(child) — Appends a child element to a parentelement.insertBefore(newNode, referenceNode) — Inserts a node before another nodeelement.append(...nodesOrStrings) — Appends multiple nodes or stringselement.prepend(...nodesOrStrings) — Inserts nodes or strings at the beginningelement.insertAdjacentHTML(position, htmlString) — Inserts HTML at positions like 'beforebegin', 'afterbegin', 'beforeend', 'afterend'element.remove() — Removes the element itselfelement.replaceWith(newNodeOrString) — Replaces the element with another node or stringelement.cloneNode(deep) — Clones a node (optionally including children)Note: setAttribute will override if used multiple times. Combine or use classList.add insted.
element.getAttribute(name) — Gets an attribute valueelement.setAttribute(name, value) — Sets an attribute value. Set multiple with (name, val1 val2)element.hasAttribute(name) — Checks if an attribute existselement.removeAttribute(name) — Removes an attributeelement.textContent — Gets/sets all text contentelement.innerHTML — Gets/sets HTML contentelement.innerText — Gets/sets visible text onlyelement.classList — Provides methods: add(), remove(), toggle(), contains(), replace()element.style.propertyName = value — Inline style manipulationelement.addEventListener(event, handler) — Attaches an event handlerelement.removeEventListener(event, handler) — Removes an event handlerelement.dispatchEvent(event) — Manually triggers an eventevent.preventDefault() — Prevents default browser behaviorevent.stopPropagation() — Stops event bubblingevent.target — Element that triggered the eventevent.currentTarget — Element the listener is attached toelement.parentNode / element.parentElement — Gets the parent node/elementelement.childNodes — Returns all child nodes, including text nodeselement.children — Returns only element-type childrenelement.firstChild / element.lastChild — First/last child nodeelement.firstElementChild / element.lastElementChild — First/last child elementelement.nextSibling / element.previousSibling — Adjacent nodeselement.nextElementSibling / element.previousElementSibling — Adjacent element nodeselement.closest(selector) — Finds the nearest ancestor (including itself) matching a selectorelement.matches(selector) — Checks if element matches a selectordocument.createDocumentFragment() — Creates a lightweight container for building DOM structureswindow.getComputedStyle(element) — Reads computed CSS styleselement.scrollIntoView() — Scrolls element into viewdocument.body, document.head, document.documentElement — Core document referencesdocument.write(string) — Writes HTML to the document (not recommended)document.open() / document.close() — Opens/closes document streamdocument.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.
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) keydown — When a key is pressed down keypress (deprecated) — (Old, replaced by keydown/keyup) keyup — When a key is released 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 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 touchstart — Finger touches screen touchmove — Finger moves on screen touchend — Finger lifts off screen pointerdown / pointerup / pointermove — Unified mouse/touch events play — Media starts playing pause — Media is paused ended — Media playback finished timeupdate — Playback time updates volumechange — Volume changes 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) // 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 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';
// 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 specific elements you can individually access by ID or Class name
newFilePathInput.remove();
// Removing all child elements in a parent element
mainHeaderContainer.textContent = '';
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);
// 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);
// Copying content to the clipboard
navigator.clipboard.writeText('This is a copied message!');
navigator.clipboard.writeText(copiedMessage);
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);
}
}
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.')
);
}
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;