Codeloft
0 0 XP

JavaScript reference

Short entries with an example for each. When you need every detail, each entry links to the official documentation.

JavaScript

console.log()

Prints values to the console for checking your work.

console.log("Total:", 42);

let and const

Declare variables. Use const when the value never changes.

const tax = 0.08;
let total = 0;
total = 100 + 100 * tax;
console.log(total);

function

Defines reusable code that can take inputs and return a result.

function area(w, h) {
  return w * h;
}
console.log(area(3, 4));

if...else

Runs code only when a condition is true, with an optional fallback.

let age = 15;
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Not yet");
}

Arrays

Ordered lists of values. Indexes start at 0.

const colors = ["red", "green"];
colors.push("blue");
console.log(colors.length, colors[0]);

for...of

Loops over every item in an array.

for (const fruit of ["apple", "pear"]) {
  console.log(fruit);
}

Objects

Group related values under names (properties).

const pet = { name: "Milo", age: 3 };
pet.age = 4;
console.log(pet.name, pet.age);

Template literals

Strings in backticks that can include values with a dollar sign and braces.

const name = "Ada";
console.log(`Hi, ${name}!`);

querySelector()

Finds the first element that matches a CSS selector.

const title = document.querySelector("h1");
title.textContent = "Found it!";

addEventListener()

Runs a function when something happens, like a click.

button.addEventListener("click", () => {
  button.textContent = "Clicked!";
});

textContent

Reads or replaces the text inside an element.

document.querySelector("#msg").textContent = "Saved";

createElement() and append()

Make a new element, then add it to the page.

const li = document.createElement("li");
li.textContent = "New item";
list.append(li);