JavaScript Reference

A practical guide to the JavaScript concepts, syntax, and methods used in modern web development.

Variables & Data Types

let & const

Declare variables using modern JavaScript syntax.

let trailLength = 12.4;
const MAX_HIKERS = 8;

var

Older variable declaration kept for compatibility with existing code.

var currentWeather = "Sunny";

typeof

Returns the type of a value.

typeof "Mountain" // "string"
typeof 42         // "number"

Boolean, null, undefined

Frequently used primitive values in JavaScript.

true / false
null
undefined

Output & Debugging

console.log()

Displays information in the browser’s developer console.

console.log("Trail difficulty:", difficulty, "km");

alert(), prompt(), confirm()

Shows built-in browser dialog boxes for user interaction.

alert("Trail closed due to rain!");
const name = prompt("What is your trail name?");
confirm("Ready to start the hike?");

Strings

Template Literals

Create strings that include variables and expressions.

`Welcome back, ${hikerName}! You hiked ${distance}km today.`

.length, .toUpperCase(), .toLowerCase()

Common properties and methods for working with text.

"Eagle Peak".length
"sunrise".toUpperCase()

.includes(), .slice(), .trim()

Search, extract, or clean string values.

"waterfall".includes("fall")
"  muddy trail  ".trim()

Numbers & Math

Basic Operators

Perform arithmetic calculations.

elevationGain + 450
totalDistance % 5

Math Methods

Built-in functions for mathematical operations.

Math.random() * 10
Math.floor(8.7)
Math.max(1200, 2450, 890)

Conditions

if / else / else if

Runs different code depending on whether a condition is true or false.

if (elevation > 2000) {
  console.log("High altitude!");
} else if (weather === "Rain") {
  console.log("Trail slippery");
}

Comparison Operators

Compare two values and return true or false.

temp === 15
battery > 20

Ternary Operator

Compact alternative to an if…else statement.

const status = isOpen ? "Trail Open" : "Closed";

Loops

for Loop

Repeats code a specific number of times.

for (let i = 0; i < checkpoints.length; i++) {
  console.log("Checkpoint", i);
}

for...of & for...in

Iterate through arrays or object properties.

for (let animal of wildlife) {}
for (let key in trailData) {}

while / do...while

Repeats code while a condition remains true.

while (energy > 0) {}

Functions

Function Declaration

Creates a reusable block of code.

function calculateDistance(start, end) {
  return end - start;
}

Arrow Function

Shorter function syntax introduced in ES6.

const isSteep = (slope) => slope > 25;

Parameters & Default Values

Pass values into a function when it is called.

function greetHiker(name = "Explorer") {
  return `Happy trails, ${name}!`;
}

Arrays

Array Methods

Common methods for adding, removing, and transforming array data.

trails.push("New Route");
difficultTrails = trails.filter(t => t.difficulty > 7);

Spread Operator

Copies or combines arrays and objects.

const allTrails = [...summerTrails, ...winterTrails];

Objects

Object Basics

Store related data as key-value pairs.

const bearSighting = {
  location: "Pine Ridge",
  time: "Morning",
  count: 1
};

Destructuring

Extract values from objects or arrays into variables.

const {location, difficulty} = trailInfo;

Object.keys() / Object.values()

Returns an array of an object’s keys or values.

Object.keys(gearList)

DOM Manipulation

Selecting Elements

Find HTML elements so they can be accessed with JavaScript.

document.querySelector(".trail-card")
document.getElementById("map")

Modifying Content

Update an element’s content, appearance, or styles.

statusEl.textContent = "Trail is open!";
card.style.backgroundColor = "#ecfdf5";

Class & Attribute Control

Add, remove, or update classes and HTML attributes.

mapEl.classList.add("loaded")
button.setAttribute("data-trail", "eagle-peak")

Creating Elements

Create and insert new HTML elements with JavaScript.

const notification = document.createElement("div");
trailList.appendChild(notification);

Events

addEventListener()

Runs code when a specific event occurs.

startBtn.addEventListener("click", () => {
  startHike();
});

Common Events

Frequently used browser events.

"click", "submit", "mousemove"

Event Object

Provides information about the event that occurred.

form.addEventListener("submit", e => {
  e.preventDefault();
  saveTrailData();
});

Modern JavaScript

Promises & async/await

Manage operations that complete in the future.

async function getWeather() {
  const data = await fetch("/api/weather");
}

Arrow Functions + this

Shorter syntax and inherit this from their surrounding scope.

setTimeout(() => console.log("Hike complete!"), 3000);

setTimeout / setInterval

Run code after a delay or at repeated intervals.

setInterval(updateElevation, 5000);
clearInterval(timer);