JavaScript Documentation

Student-friendly JavaScript reference with examples

Sections

Variables & Data Types

const vs let vs var

Normal
#const-let-var

const: can't be reassigned, block-scoped. let: can be reassigned, block-scoped. var: old way, function-scoped (avoid it).

const PI = 3.14;        // Never changes
let score = 0;          // Will change
var oldWay = 'avoid';   // Don't use this

if (true) {
  const x = 1;
  let y = 2;
  var z = 3;
}
// console.log(x);      // ERROR: x not defined
// console.log(y);      // ERROR: y not defined
console.log(z);         // Works but BAD practice

JavaScript Data Types

Normal
#data-types

JavaScript has several data types: string (text), number, boolean (true/false), null, undefined, object, and array.

// Primitive types:
const text = 'Hello';           // string
const age = 25;                 // number
const price = 19.99;            // number (decimals too)
const isActive = true;          // boolean
const nothing = null;           // null (empty on purpose)
let notSet;                     // undefined (not set yet)

// Complex types:
const user = {name: 'Alice'};   // object
const items = [1, 2, 3];        // array

Type Checking in JavaScript

Normal
#type-checking-normal

Use typeof for primitives, Array.isArray() for arrays, and instanceof for objects.

console.log(typeof 'hello');        // 'string'
console.log(typeof 42);             // 'number'
console.log(typeof true);           // 'boolean'
console.log(typeof undefined);      // 'undefined'
console.log(typeof {});              // 'object'
console.log(typeof []);              // 'object' (tricky!)

// Better array check:
console.log(Array.isArray([1,2]));  // true
console.log(Array.isArray({}));     // false

Finding Elements

Find One Element

Normal
#select-normal

Use document.querySelector() to find the first element matching a CSS selector.

// Find element by ID
const title = document.querySelector('#main-title');

// Find element by class
const button = document.querySelector('.submit-btn');

// Find first paragraph
const paragraph = document.querySelector('p');

// Complex selector
const item = document.querySelector('ul.menu > li:first-child');

Find Multiple Elements

Normal
#select-all-normal

Use document.querySelectorAll() to find all matching elements. Returns a NodeList.

// Get all buttons
const buttons = document.querySelectorAll('button');

// Convert NodeList to Array for easier use
const buttonArray = Array.from(buttons);

// Or use forEach (works on NodeList)
buttons.forEach(button => {
  button.style.color = 'blue';
});

Changing Elements

Change Text Content

Normal
#change-text

Use textContent to safely change text without HTML.

const element = document.querySelector('#message');

// Safe text change
element.textContent = 'Hello World';

// This won't create HTML tags:
element.textContent = '<b>Still plain text</b>';

Change HTML Content

Normal
#change-html

Use innerHTML to set HTML content (be careful with user input!).

const container = document.querySelector('#content');

// Set HTML
container.innerHTML = '<h2>Title</h2><p>Paragraph</p>';

// Add to existing
container.innerHTML += '<p>Another paragraph</p>';

// DANGER: Never do this with user input!
// container.innerHTML = userInput; // XSS vulnerability!

Add CSS Classes

Normal
#add-class

Use classList.add() to add CSS classes to elements.

const button = document.querySelector('button');

// Add one class
button.classList.add('active');

// Add multiple classes
button.classList.add('btn', 'btn-primary', 'large');

Remove CSS Classes

Normal
#remove-class

Use classList.remove() to remove CSS classes.

const element = document.querySelector('.card');

// Remove one class
element.classList.remove('hidden');

// Remove multiple
element.classList.remove('active', 'highlighted');

// Remove all classes
element.className = '';

Toggle CSS Classes

Normal
#toggle-class

Use classList.toggle() to switch classes on/off.

const menu = document.querySelector('.menu');
const button = document.querySelector('.menu-btn');

button.addEventListener('click', () => {
  // Adds if missing, removes if present
  menu.classList.toggle('open');
  
  // Returns true if added, false if removed
  const isOpen = menu.classList.toggle('active');
  console.log('Menu is open:', isOpen);
});

Show/Hide Elements

Normal
#show-hide-normal

Control visibility using style.display or classes.

const element = document.querySelector('.modal');

// Hide
element.style.display = 'none';

// Show (restore default)
element.style.display = '';

// Or use classes
element.classList.add('hidden');    // Hide
element.classList.remove('hidden'); // Show

Create Elements

Normal
#create-element-normal

Use document.createElement() to create new elements.

// Create element
const button = document.createElement('button');
button.textContent = 'Click me';
button.className = 'btn';
button.id = 'submit-btn';

// Add to page
document.body.appendChild(button);

// Or insert at specific position
const container = document.querySelector('.container');
container.insertBefore(button, container.firstChild);

User Interactions

Event Listeners

Normal
#event-listener-normal

Use addEventListener() to respond to user interactions.

const button = document.querySelector('button');

// Add event listener
button.addEventListener('click', (event) => {
  console.log('Clicked!');
  console.log('Target:', event.target);
});

// With named function (can remove later)
function handleClick(event) {
  console.log('Clicked!');
}
button.addEventListener('click', handleClick);

// Remove listener
button.removeEventListener('click', handleClick);

Common Event Types

Normal
#event-types

Different events you can listen for.

// Mouse events
element.addEventListener('click', handler);
element.addEventListener('dblclick', handler);
element.addEventListener('mouseenter', handler);
element.addEventListener('mouseleave', handler);

// Keyboard events
input.addEventListener('keydown', handler);
input.addEventListener('keyup', handler);

// Form events
form.addEventListener('submit', handler);
input.addEventListener('input', handler);
input.addEventListener('change', handler);
field.addEventListener('focus', handler);
field.addEventListener('blur', handler);

// Window events
window.addEventListener('load', handler);
window.addEventListener('resize', handler);
window.addEventListener('scroll', handler);

The Event Object

Normal
#event-object

Every event handler receives an event object with useful information.

button.addEventListener('click', (event) => {
  // Useful properties
  console.log(event.type);        // 'click'
  console.log(event.target);      // Element clicked
  console.log(event.currentTarget); // Element with listener
  console.log(event.timeStamp);   // When it happened
  
  // For mouse events
  console.log(event.clientX, event.clientY); // Position
  
  // For keyboard events
  console.log(event.key);         // 'Enter', 'a', etc.
  console.log(event.keyCode);     // Numeric code
  console.log(event.shiftKey);    // Was shift pressed?
});

Prevent Default Actions

Normal
#prevent-default

Stop browser's default behavior for events.

// Prevent form submission
form.addEventListener('submit', (event) => {
  event.preventDefault();
  // Handle submission with JavaScript instead
  const data = new FormData(form);
  // Send with fetch...
});

// Prevent link navigation
link.addEventListener('click', (event) => {
  event.preventDefault();
  // Do something else instead
});

// Prevent right-click menu
element.addEventListener('contextmenu', (event) => {
  event.preventDefault();
});

Working with Arrays

Loop Through Arrays

Normal
#array-loop-normal

Different ways to iterate through arrays.

const items = ['a', 'b', 'c'];

// forEach method
items.forEach((item, index) => {
  console.log(index, item);
});

// Traditional for loop
for (let i = 0; i < items.length; i++) {
  console.log(i, items[i]);
}

// for...of (no index)
for (const item of items) {
  console.log(item);
}

// for...in (avoid for arrays!)
for (const index in items) {
  console.log(index, items[index]);
}

Get First/Last Item

Normal
#array-first-last-normal

Access array items by index.

const items = ['a', 'b', 'c', 'd'];

// First item
const first = items[0];  // 'a'

// Last item
const last = items[items.length - 1];  // 'd'

// Safe access with optional chaining
const maybe = items?.[0] ?? 'default';  // 'a'

// Destructuring
const [firstItem, secondItem] = items;  // 'a', 'b'

Add/Remove Array Items

Normal
#array-add-remove

Methods to modify arrays.

const items = ['a', 'b', 'c'];

// Add to end
items.push('d');        // ['a','b','c','d']

// Add to beginning
items.unshift('z');     // ['z','a','b','c','d']

// Remove from end
const last = items.pop();     // 'd'

// Remove from beginning
const first = items.shift();  // 'z'

// Add/remove at position
items.splice(1, 1);     // Remove 1 at index 1
items.splice(1, 0, 'x'); // Insert 'x' at index 1

Find Items in Arrays

Normal
#array-find

Search for items in arrays.

const users = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 3, name: 'Charlie'}
];

// Find first matching item
const user = users.find(u => u.name === 'Bob');
// {id: 2, name: 'Bob'}

// Find index
const index = users.findIndex(u => u.id === 2);
// 1

// Check if exists
const hasAlice = users.some(u => u.name === 'Alice');
// true

// Check if all match
const allHaveNames = users.every(u => u.name);
// true

Filter Arrays

Normal
#array-filter

Create new array with items that pass a test.

const numbers = [1, 2, 3, 4, 5, 6];

// Get even numbers
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]

const users = [
  {name: 'Alice', age: 25},
  {name: 'Bob', age: 17},
  {name: 'Charlie', age: 30}
];

// Get adults only
const adults = users.filter(u => u.age >= 18);
// [{name: 'Alice', ...}, {name: 'Charlie', ...}]

Getting Data from APIs

Fetch Data from API

Normal
#fetch-normal

Use fetch() to get data from servers.

// Basic fetch
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

// With async/await
async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

// Check status
async function fetchSafely(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}

Send Data with POST

Normal
#post-normal

Send data to servers using POST requests.

// Send JSON
const data = { name: 'Alice', age: 25 };

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log(result));

// Send form data
const formData = new FormData();
formData.append('name', 'Alice');
formData.append('file', fileInput.files[0]);

fetch('/upload', {
  method: 'POST',
  body: formData  // No Content-Type needed!
});

Handle Fetch Errors

Normal
#handle-errors

Properly handle network and API errors.

// With try/catch
async function fetchData() {
  try {
    const response = await fetch('/api/data');
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    const data = await response.json();
    return data;
    
  } catch (error) {
    if (error.message.includes('Failed to fetch')) {
      console.error('Network error');
    } else {
      console.error('API error:', error);
    }
    // Show user-friendly message
    alert('Something went wrong. Please try again.');
  }
}

Saving Data Locally

Use Local Storage

Normal
#storage-normal

Save data that persists even after closing the browser.

// Save string
localStorage.setItem('username', 'Alice');

// Save object (must stringify)
const user = { name: 'Alice', score: 100 };
localStorage.setItem('user', JSON.stringify(user));

// Get string
const username = localStorage.getItem('username');

// Get object (must parse)
const userData = localStorage.getItem('user');
const userObj = JSON.parse(userData);

// Remove item
localStorage.removeItem('username');

// Clear everything
localStorage.clear();

Timing & Delays

Delay Code Execution

Normal
#timeout

Use setTimeout to run code after a delay.

// Run after 2 seconds
setTimeout(() => {
  console.log('2 seconds passed!');
}, 2000);

// With function reference
function showMessage() {
  alert('Time is up!');
}
setTimeout(showMessage, 3000);

// Cancel timeout
const timerId = setTimeout(() => {
  console.log('This might not run');
}, 5000);

// Cancel it
clearTimeout(timerId);

Repeat Code Periodically

Normal
#interval

Use setInterval to run code repeatedly.

// Run every second
const intervalId = setInterval(() => {
  console.log('Tick!');
}, 1000);

// Stop after 5 seconds
setTimeout(() => {
  clearInterval(intervalId);
  console.log('Stopped!');
}, 5000);

// Update clock
setInterval(() => {
  const now = new Date();
  const time = now.toLocaleTimeString();
  document.querySelector('#clock').textContent = time;
}, 1000);

Helpful Functions

Random Numbers

Normal
#random-normal

Generate random numbers with Math.random().

// Random 0 to 1
const decimal = Math.random();  // 0.7234...

// Random integer between min and max
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const dice = randomInt(1, 6);

// Random array item
const items = ['a', 'b', 'c'];
const random = items[Math.floor(Math.random() * items.length)];

// Random boolean
const coinFlip = Math.random() < 0.5;

Shuffle Arrays

Normal
#shuffle-normal

Randomize array order with Fisher-Yates algorithm.

function shuffle(array) {
  // Create copy to avoid modifying original
  const shuffled = [...array];
  
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  
  return shuffled;
}

const cards = ['A', 'K', 'Q', 'J'];
const shuffled = shuffle(cards);
console.log(shuffled);  // Random order

Remove Duplicates

Normal
#unique-normal

Get unique values using Set.

// Using Set
const numbers = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(numbers)];
console.log(unique);  // [1, 2, 3, 4]

// Filter method
const unique2 = numbers.filter((item, index) => {
  return numbers.indexOf(item) === index;
});

// For objects (by property)
const users = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 1, name: 'Alice'}  // Duplicate
];

const uniqueUsers = users.filter((user, index, self) =>
  index === self.findIndex(u => u.id === user.id)
);