Home JavaScript

JavaScript Fundamentals

JavaScript makes websites interactive — responding to user clicks, changing content dynamically, and building rich UI components. Let's learn the essentials step by step.

1. Variables & Data Types

Use const for values that don't change and let for variables that will be reassigned. Avoid var in modern JavaScript.

Variables
// Constants — cannot be reassigned
const siteName = "My Website";
const maxItems = 10;
const isActive = true;

// Let — can be reassigned
let count = 0;
count = count + 1;

// Template literals (backticks)
const greeting = `Welcome to ${siteName}!`;

2. Functions & Arrow Functions

Functions are reusable blocks of code. Arrow functions (=>) are a shorter syntax for writing functions, commonly used with callbacks and event handlers.

Functions
// Traditional function
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrow function (shorter syntax)
const greet = (name) => `Hello, ${name}!`;

// Arrow function with body
const calculate = (a, b) => {
    const result = a + b;
    return result;
};

3. Selecting DOM Elements

The DOM (Document Object Model) represents your HTML as a tree of objects. JavaScript accesses and modifies these objects to change the page dynamically.

DOM selection
// Select by ID — returns one element
const image = document.getElementById('gallery-image');

// Select by CSS selector — returns all matches
const buttons = document.querySelectorAll('.tab-btn');

// Select first match only
const hero = document.querySelector('.hero');

// Access/modify properties
image.src = 'new-photo.jpg';
hero.textContent = 'Updated!';
💡 Tip: querySelectorAll() uses CSS selectors, so you can use .class, #id, or complex selectors like nav ul li a.

4. Event Listeners

Event listeners let you respond to user interactions — clicks, key presses, scrolling, and more. The addEventListener() method attaches a callback function to an event.

Event handling
// Click event
button.addEventListener('click', () => {
    console.log('Button clicked!');
});

// Common events:
// 'click'     — mouse click
// 'mouseover' — cursor enters element
// 'keydown'   — key pressed
// 'submit'    — form submitted
// 'scroll'    — page scrolled

// Wait for DOM to be ready
document.addEventListener('DOMContentLoaded', () => {
    // Safe to access all elements here
});

5. Arrays & Iteration

Arrays store ordered collections of data. The forEach() method loops through each item and runs a function on it.

Working with arrays
const colors = ['red', 'green', 'blue'];

// forEach — run function on each item
colors.forEach(color => {
    console.log(color);
});

// map — transform and return new array
const upper = colors.map(
    c => c.toUpperCase()
);
// ['RED', 'GREEN', 'BLUE']

// filter — keep items that match
const long = colors.filter(
    c => c.length > 3
);
// ['green', 'blue']

6. Modifying CSS Classes

The classList API lets you add, remove, or toggle CSS classes on elements — the most common way to change appearance dynamically.

classList methods
// Remove 'active' from all buttons
buttons.forEach(btn => {
    btn.classList.remove('active');
});

// Add 'active' to the clicked button
button.classList.add('active');

// Toggle a class on/off
menu.classList.toggle('open');

// Check if class exists
if (element.classList.contains('hidden')) {
    element.classList.remove('hidden');
}

7. Data Attributes & Dynamic Content

HTML5 data attributes (data-*) let you store custom information directly in HTML elements. Access them from JavaScript via the dataset object.

Data attributes
// HTML: <button data-image="kitchen">...</button>

// Read data attribute value
const name = button.dataset.image;
// "kitchen"

// Update image source dynamically
image.src = `img/gallery/${name}.jpg`;
// "img/gallery/kitchen.jpg"

// data-user-id becomes dataset.userId
// data-max-count becomes dataset.maxCount
💡 Tip: Template literals (backticks ` `) make string concatenation much cleaner. `img/${name}.jpg` is equivalent to "img/" + name + ".jpg".

8. Complete Example — Image Gallery

Here's a complete, working JavaScript file that implements an interactive image gallery with tab buttons. It demonstrates all the concepts covered in this tutorial — all in just 18 lines.

gallery.js — Complete code
document.addEventListener('DOMContentLoaded', () => {

    const buttons = document.querySelectorAll('.tab-btn');
    const image = document.getElementById('gallery-image');

    buttons.forEach(button => {
        button.addEventListener('click', () => {
            // Remove active state from all
            buttons.forEach(
                b => b.classList.remove('active')
            );
            button.classList.add('active');

            // Update image source
            const name = button.dataset.image;
            image.src = `img/gallery/${name}.jpg`;
        });
    });

});
← Previous CSS Styling