2026-08-15 20:18
Tags: Guide JavaScript Front End Back End Programming Lanuages Full Stack APIs Web Development Websites CheatSheet
# JavaScript Cheat Sheet
IBM Full Stack Software Developer — Module 3: JavaScript Programming for Web Applications
1. JavaScript Fundamentals
Introduction to JavaScript & ES6
JavaScript is a lightweight, interpreted scripting language used to make web pages interactive. It runs in the browser (client-side) and can also run server-side (Node.js).
ES6 (ECMAScript 2015) introduced major upgrades still used constantly today:
// let/const instead of var
let count = 5;
const PI = 3.14159;
// Arrow functions
const add = (a, b) => a + b;
// Template literals
const name = "Sam";
console.log(`Hello, ${name}!`);
// Destructuring
const { title, year } = movie;
const [first, second] = myArray;
// Default parameters
function greet(name = "friend") { console.log(`Hi ${name}`); }
// Spread / rest
const combined = [...arr1, ...arr2];
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
// Classes
class Car {
constructor(make) { this.make = make; }
drive() { console.log(`${this.make} is driving`); }
}
// Modules
export const foo = 1;
import { foo } from './file.js';| var | let | const |
|---|---|---|
| Function-scoped | Block-scoped | Block-scoped |
| Can be redeclared | Cannot be redeclared | Cannot be redeclared |
| Can be reassigned | Can be reassigned | Cannot be reassigned |
Data Types and Variables
Primitive types:
String—"hello"Number—42,3.14Boolean—true/falseUndefined— declared but no value assignedNull— intentional “no value”Symbol— unique identifier (ES6)BigInt— very large integers
Reference type:
Object(includes Arrays, Functions, Dates, etc.)
let str = "hello"; // string
let num = 25; // number
let isActive = true; // boolean
let empty; // undefined
let nothing = null; // null
let obj = { key: "value" }; // object
let arr = [1, 2, 3]; // array (type of object)
typeof str; // "string"
typeof num; // "number"
typeof obj; // "object"Type coercion & comparison:
"5" == 5; // true (loose equality, converts types)
"5" === 5; // false (strict equality, checks type + value)Best practice: always use
===and!==to avoid unexpected coercion bugs.
Introduction to Functions and Types of Functions
// Function declaration (hoisted — can be called before defined)
function add(a, b) {
return a + b;
}
// Function expression (not hoisted)
const subtract = function (a, b) {
return a - b;
};
// Arrow function (shorter syntax, no own `this`)
const multiply = (a, b) => a * b;
// Anonymous function (used as a callback)
setTimeout(function () {
console.log("Runs after delay");
}, 1000);
// Immediately Invoked Function Expression (IIFE)
(function () {
console.log("Runs immediately");
})();Key concepts:
- Parameters vs Arguments — parameters are placeholders in the definition; arguments are actual values passed in.
- Return values — a function without
returnreturnsundefined. - Scope — variables declared inside a function aren’t accessible outside it.
- Hoisting — function declarations move to the top of their scope; function expressions do not.
JavaScript: Functions and Prototypes
- A function can be declared with an arrow like shown above, this puts it into a variable so it can be stored and what not. If the function as no arguments, you declare it with the
(), - if it has one parameter, then you can just put the name of it with no parenthesis. If it has more than one parameter, then you have to use the parenthesis.
- As for the curly braces, if it only has one line of code and does not return anything, then it does not need the curly braces.
- If it does return something or is more than one line, then it needs them
Every JavaScript object has an internal link to another object called its prototype. This is the basis of prototypal inheritance.
function Person(name) {
this.name = name;
}
// Add a method to the prototype (shared by all instances)
Person.prototype.sayHello = function () {
console.log(`Hello, my name is ${this.name}`);
};
const p1 = new Person("Alex");
p1.sayHello(); // "Hello, my name is Alex"
// Checking the prototype chain
console.log(p1.__proto__ === Person.prototype); // truethis keyword — refers to the object that is executing the current function. Its value depends on how a function is called:
const obj = {
name: "Box",
show() { console.log(this.name); } // "this" = obj
};
const arrowShow = () => console.log(this); // "this" = surrounding scope, NOT objClasses (ES6 syntactic sugar over prototypes):
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a noise.`); }
}
class Dog extends Animal {
speak() { console.log(`${this.name} barks.`); }
}
new Dog("Rex").speak(); // "Rex barks."Introduction to Arrays
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits.length; // 3
// Adding/removing
fruits.push("date"); // add to end
fruits.pop(); // remove from end
fruits.unshift("kiwi"); // add to start
fruits.shift(); // remove from start
// Looping
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
for (const fruit of fruits) { console.log(fruit); }
// Multidimensional
const grid = [[1, 2], [3, 4]];
grid[1][0]; // 3Array Methods
| Method | Purpose | Returns |
|---|---|---|
map() | transform each element | new array |
filter() | keep elements matching a condition | new array |
reduce() | accumulate into a single value | single value |
forEach() | run a function per element | undefined |
find() | first element matching condition | element or undefined |
some() | true if any element matches | boolean |
every() | true if all elements match | boolean |
sort() | sort elements (mutates array) | sorted array |
slice() | extract a portion (non-mutating) | new array |
splice() | add/remove elements (mutates array) | removed elements |
includes() | check if a value exists | boolean |
join() | combine into a string | string |
const nums = [1, 2, 3, 4, 5];
nums.map(n => n * 2); // [2, 4, 6, 8, 10]
nums.filter(n => n % 2 === 0); // [2, 4]
nums.reduce((sum, n) => sum + n, 0); // 15
nums.find(n => n > 3); // 4
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true2. Interactive Web Development with JavaScript and the DOM
JavaScript APIs
An API (Application Programming Interface) lets JavaScript communicate with other software, browser features, or external services.
Common built-in browser APIs:
fetch()— make network requestslocalStorage/sessionStorage— store data in the browserGeolocation API— get a user’s locationConsole API—console.log(), etc.
// fetch API example — GET request
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
// async/await version
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}Promises — represent the eventual completion (or failure) of an async operation:
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("It worked!");
else reject("It failed.");
});
promise.then(result => console.log(result))
.catch(error => console.log(error));Client-Side JavaScript: with HTML
JavaScript can be added to an HTML page three ways:
<!-- 1. Inline -->
<button onclick="alert('Hi!')">Click</button>
<!-- 2. Internal -->
<script>
console.log("Hello from internal script");
</script>
<!-- 3. External (best practice) -->
<script src="script.js"></script>Place
<script>tags at the end of<body>(or usedefer) so the HTML loads before JavaScript runs.
<script src="script.js" defer></script>Client-Side JavaScript: with DOM
The DOM (Document Object Model) is a tree-like representation of an HTML page that JavaScript can read and modify.
// Selecting elements
document.getElementById("myId");
document.getElementsByClassName("myClass");
document.getElementsByTagName("p");
document.querySelector(".myClass"); // first match
document.querySelectorAll(".myClass"); // all matches (NodeList)
// Modifying content
const el = document.querySelector("#title");
el.textContent = "New text";
el.innerHTML = "<strong>Bold text</strong>";
// Modifying styles/attributes
el.style.color = "blue";
el.setAttribute("data-active", "true");
el.classList.add("highlight");
el.classList.remove("hidden");
el.classList.toggle("open");
// Creating & inserting elements
const newDiv = document.createElement("div");
newDiv.textContent = "I'm new!";
document.body.appendChild(newDiv);
// Removing elements
el.remove();JavaScript DOM Objects
Events — DOM objects can listen and respond to user actions:
const button = document.querySelector("button");
button.addEventListener("click", function (event) {
console.log("Button clicked!", event.target);
});
// Common events: click, submit, keydown, mouseover, load, change, input
document.querySelector("form").addEventListener("submit", (e) => {
e.preventDefault(); // stop default form submission
console.log("Form submitted");
});Key DOM objects:
| Object | Represents |
|---|---|
window | the browser window (global object) |
document | the loaded web page |
navigator | info about the browser |
location | the current URL |
history | browser session history |
Event bubbling: events travel from the target element up through its ancestors, unless stopped with event.stopPropagation().
3. Quick-Reference Cheat Sheet
// Variables
let x = 1; const y = 2;
// Conditionals
if (x > y) { } else if (x === y) { } else { }
x > y ? "bigger" : "smaller"; // ternary
// Loops
for (let i = 0; i < 5; i++) { }
while (x < 5) { x++; }
// Functions
function fn(a, b) { return a + b; }
const fn2 = (a, b) => a + b;
// Objects
const person = { name: "Jo", age: 30 };
person.name; person["age"];
// Arrays
const arr = [1, 2, 3];
arr.map(n => n * 2);
// DOM
document.querySelector(".x").addEventListener("click", () => {});
// Fetch API
fetch(url).then(res => res.json()).then(data => console.log(data));4. Glossary
- API — a set of rules that lets programs communicate with each other or with system/browser features.
- Argument — the actual value passed into a function when it’s called.
- Array — an ordered, list-like object used to store multiple values.
- Asynchronous — code that runs independently of the main program flow, without blocking it.
- Callback function — a function passed as an argument to another function, to be executed later.
- Class — a template for creating objects, built on top of prototypes.
- DOM — Document Object Model; the browser’s tree-structured representation of a web page.
- ES6 — ECMAScript 2015, a major update to the JavaScript language specification.
- Event — an action (click, keypress, load, etc.) that JavaScript can detect and respond to.
- Event listener — a function that waits for a specific event to occur on an element.
- Hoisting — JavaScript’s behavior of moving declarations to the top of their scope before execution.
- Method — a function that belongs to an object.
- Parameter — a named placeholder in a function definition.
- Promise — an object representing the eventual result of an asynchronous operation.
- Prototype — an object from which other objects inherit properties and methods.
- Scope — the context that determines the accessibility of variables.
- String — a sequence of characters used to represent text.
this— a keyword referring to the object executing the current function.- Type coercion — automatic conversion of values from one data type to another.
5. References & Further Reading
- MDN Web Docs — JavaScript
- MDN Web Docs — DOM Introduction
- MDN Web Docs — Fetch API
- ECMAScript Specification
- IBM Full Stack Software Developer Professional Certificate — Module 3: JavaScript Programming for Web Applications
