Back to Web Development

Module 2: JavaScript Basics

Make your websites come alive with interactivity, animations, and dynamic content

⚡ What is JavaScript?

Remember our house analogy? If HTML is the structure and CSS is the interior design, then JavaScript is the electricity, plumbing, and smart home system! JavaScript makes websites interactive - it handles clicks, animations, form validation, and everything that happens when you interact with a page.

Simple Definition

JavaScript is a programming language that runs in web browsers. It lets you create dynamic, interactive experiences - from simple button clicks to complex web applications like Gmail or Facebook. It's the only programming language that works natively in all web browsers!

// Make a button show an alert

document.querySelector('button')

.addEventListener('click', function() {

alert('Hello, World!');

});

Why Learn JavaScript?

Most Popular Language

Used by 98% of websites - it's everywhere!

Full-Stack Capable

Works on frontend (React) and backend (Node.js)

Huge Job Market

Highest demand for developers worldwide

Beginner Friendly

See results immediately in your browser

📚 Learn More:

📦 Variables - Storing Data

Variables are like labeled boxes where you store information. You can put data in them, take it out, and change it. Think of them as containers with names!

Three Ways to Declare Variables

let - Modern, Changeable (Use This!)

Use let for variables that can change. This is what you'll use 90% of the time!

let age = 25;

age = 26; // Can change it

let name = "John";

let isStudent = true;

const - Modern, Constant (Can't Change)

Use const for values that should never change. Good for configuration values, API keys, etc.

const PI = 3.14159;

const API_KEY = "abc123";

// PI = 3.14; // ERROR! Can't change const

var - Old Way (Avoid!)

The old way to declare variables. Has confusing scoping rules. Don't use it in new code!

var oldWay = "Don't use this";

Data Types

// Numbers (integers and decimals)

let age = 25;

let price = 19.99;

// Strings (text in quotes)

let name = "Alice";

let message = 'Hello World';

let template = `Hello, ${name}`; // Template literal

// Booleans (true or false)

let isLoggedIn = true;

let hasPermission = false;

// Arrays (lists of items)

let colors = ["red", "blue", "green"];

let numbers = [1, 2, 3, 4, 5];

// Objects (key-value pairs)

let person = {

name: "John",

age: 30,

city: "New York"

};

💡 Naming Rules:

  • • Use camelCase: firstName, userAge, isLoggedIn
  • • Start with letter, $, or _ (not numbers)
  • • No spaces or special characters
  • • Use descriptive names: age not a, userName not un

🔧 Functions - Reusable Code Blocks

Functions are like recipes - you write the instructions once, then use them whenever you need! They help you organize code and avoid repetition.

// Function declaration

function greet(name) {

return `Hello, ${name}!`;

}

greet("Alice"); // "Hello, Alice!"

// Arrow function (modern way)

const add = (a, b) => a + b;

add(5, 3); // 8

// Function with multiple parameters

function calculateTotal(price, quantity, tax) {

const subtotal = price * quantity;

const total = subtotal + (subtotal * tax);

return total;

}

🌳 DOM Manipulation - Changing the Page

The DOM (Document Object Model) is how JavaScript sees your HTML. It's like a family tree of all elements on your page. JavaScript can read and change any part of it!

Selecting Elements

// Select by ID

const header = document.getElementById('header');

// Select by class (first match)

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

// Select all matching elements

const items = document.querySelectorAll('.item');

Changing Content & Styles

// Change text content

header.textContent = 'New Title';

// Change HTML

header.innerHTML = '<h1>New Title</h1>';

// Change styles

header.style.color = 'blue';

header.style.fontSize = '24px';

// Add/remove classes

button.classList.add('active');

button.classList.remove('disabled');

button.classList.toggle('hidden');

Event Listeners - Responding to User Actions

// Click event

button.addEventListener('click', function() {

alert('Button clicked!');

});

// Input event (when typing)

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

input.addEventListener('input', (e) => {

console.log(e.target.value);

});

// Mouse hover

button.addEventListener('mouseenter', () => {

button.style.backgroundColor = 'lightblue';

});

🎯 Practice Project: Interactive Counter

Let's build a simple counter with increment, decrement, and reset buttons!

HTML:

<div class="counter">

<h1 id="count">0</h1>

<button id="decrease">Decrease</button>

<button id="reset">Reset</button>

<button id="increase">Increase</button>

</div>

JavaScript:

// Get elements

const countEl = document.getElementById('count');

const decreaseBtn = document.getElementById('decrease');

const resetBtn = document.getElementById('reset');

const increaseBtn = document.getElementById('increase');

// Initialize counter

let count = 0;

// Update display

function updateDisplay() {

countEl.textContent = count;

// Change color based on value

if (count > 0) {

countEl.style.color = 'green';

} else if (count < 0) {

countEl.style.color = 'red';

} else {

countEl.style.color = 'black';

}

}

// Event listeners

decreaseBtn.addEventListener('click', () => {

count--;

updateDisplay();

});

resetBtn.addEventListener('click', () => {

count = 0;

updateDisplay();

});

increaseBtn.addEventListener('click', () => {

count++;

updateDisplay();

});

🎨 Try Adding:

  • • Buttons to increase/decrease by 5 or 10
  • • A maximum and minimum limit
  • • Sound effects on button clicks
  • • Animations when the number changes

📚 Learning Resources

Documentation

Practice

🎯 What's Next?

Great job! You now know the basics of JavaScript. Next, we'll learn React - a powerful library for building modern, interactive user interfaces. Get ready to level up!