JavaScript Tutorial

Learn JavaScript step by step with easy examples

What is JavaScript?

JavaScript is a programming language that makes websites interactive. While HTML creates the structure and CSS makes it look good, JavaScript makes things happen when users click buttons, fill out forms, or interact with the page.

JavaScript can:

  • Change HTML content and CSS styles
  • Respond to user clicks, keyboard input, and mouse movements
  • Validate form data before sending it
  • Create animations and interactive effects
  • Load new content without refreshing the page

How to Add JavaScript to HTML

There are three ways to add JavaScript to your webpage:

1. Inline JavaScript
Directly in HTML elements
html

Quick but not recommended for complex code

2. Internal JavaScript
In script tags
html
1

Good for small scripts

3. External JavaScript
Separate JS file
html
1
2
3 
4// In script.js file
5function sayHello() {
6 alert("Hello from external file!");
7}
8 
9console.log("External script loaded!");

Best for larger projects

Variables

Variables store data that you can use later. Think of them as labeled boxes that hold information:

javascript
1// Creating variables
2text-[#569cd6]">let name = "John"; // Text (string)
3text-[#569cd6]">let age = 25; // Number
4text-[#569cd6]">let isStudent = text-[#569cd6]">true; // True or text-[#569cd6]">false (boolean)
5text-[#569cd6]">let hobbies = ["reading", "gaming", "cooking"]; // List (array)
6 
7// Using variables
8text-[#4ec9b0]">console.log("Hello, " + name);
9text-[#4ec9b0]">console.log("You are " + age + " years old");
10 
11// Changing variables
12age = 26;
13name = "Jane";
14 
15// Constants (can't be changed)
16text-[#569cd6]">const PI = 3.14159;
17text-[#569cd6]">const WEBSITE_NAME = "Learn Web Dev";

Variable Rules:

  • • Use let for variables that can change
  • • Use const for variables that stay the same
  • • Variable names can contain letters, numbers, and underscores
  • • Variable names cannot start with a number
  • • Variable names are case-sensitive (age and Age are different)

Functions

Functions are reusable blocks of code. They're like recipes - you write them once and use them many times:

Basic Functions
Simple functions that do tasks
javascript
1// Function that says hello
2text-[#569cd6]">function sayHello() {
3 text-[#4ec9b0]">alert("Hello there!");
4}
5 
6// Function that adds two numbers
7text-[#569cd6]">function addNumbers(a, b) {
8 text-[#569cd6]">return a + b;
9}
10 
11// Using functions
12sayHello(); // Shows text-[#4ec9b0]">alert
13text-[#569cd6]">let result = addNumbers(5, 3); // result = 8
14text-[#4ec9b0]">console.log(result); // Shows 8
Functions with Parameters
Functions that accept input
javascript
1// Function with one parameter
2text-[#569cd6]">function greetPerson(name) {
3 text-[#4ec9b0]">alert("Hello, " + name + "!");
4}
5 
6// Function with multiple parameters
7text-[#569cd6]">function calculateArea(width, height) {
8 text-[#569cd6]">let area = width * height;
9 text-[#569cd6]">return area;
10}
11 
12// Using the functions
13greetPerson("Alice"); // Shows "Hello, Alice!"
14text-[#569cd6]">let roomArea = calculateArea(10, 12); // roomArea = 120

Function Tips:

  • • Give functions descriptive names (calculateTotal, not calc)
  • • Use return to send a value back
  • • Functions can call other functions
  • • Test your functions with different inputs

Events

Events happen when users interact with your webpage. JavaScript can "listen" for these events and respond:

Click Events
Respond to button clicks
javascript
1// HTML
2
3

message">

4 
5// JavaScript
6text-[#569cd6]">let button = text-[#4ec9b0]">document.getElementById("myButton");
7text-[#569cd6]">let message = text-[#4ec9b0]">document.getElementById("message");
8 
9button.addEventListener("click", text-[#569cd6]">function() {
10 message.textContent = "Button was clicked!";
11});
12 
13// Shorter way
14button.onclick = text-[#569cd6]">function() {
15 text-[#4ec9b0]">alert("Hello!");
16};
Form Events
Handle form input and submission
javascript
1// HTML
2text" id="nameInput" placeholder="Enter your name" />
3
myForm">
4 submit" value="Submit" />
5
6 
7// JavaScript
8text-[#569cd6]">let input = text-[#4ec9b0]">document.getElementById("nameInput");
9text-[#569cd6]">let form = text-[#4ec9b0]">document.getElementById("myForm");
10 
11// When user types
12input.addEventListener("input", text-[#569cd6]">function() {
13 text-[#4ec9b0]">console.log("User typed: " + input.value);
14});
15 
16// When form is submitted
17form.addEventListener("submit", text-[#569cd6]">function(event) {
18 event.preventDefault(); // Stop form from submitting
19 text-[#4ec9b0]">alert("Form submitted!");
20});

Changing HTML with JavaScript

JavaScript can find HTML elements and change their content, style, and attributes:

Finding Elements
Select HTML elements to work with
javascript
1// Find element by ID
2text-[#569cd6]">let title = text-[#4ec9b0]">document.getElementById("main-title");
3 
4// Find elements by class name
5text-[#569cd6]">let buttons = text-[#4ec9b0]">document.getElementsByClassName("btn");
6 
7// Find elements by tag name
8text-[#569cd6]">let paragraphs = text-[#4ec9b0]">document.getElementsByTagName("p");
9 
10// Modern way (recommended)
11text-[#569cd6]">let firstButton = text-[#4ec9b0]">document.querySelector(".btn");
12text-[#569cd6]">let allButtons = text-[#4ec9b0]">document.querySelectorAll(".btn");
13 
14// Find by any CSS selector
15text-[#569cd6]">let redText = text-[#4ec9b0]">document.querySelector(".red-text");
16text-[#569cd6]">let allLinks = text-[#4ec9b0]">document.querySelectorAll("a");
Changing Content
Modify text and HTML
javascript
1// Change text content
2text-[#569cd6]">let heading = text-[#4ec9b0]">document.getElementById("title");
3heading.textContent = "New Title";
4 
5// Change HTML content
6text-[#569cd6]">let container = text-[#4ec9b0]">document.getElementById("content");
7container.innerHTML = "

New paragraph

";
8 
9// Change attributes
10text-[#569cd6]">let image = text-[#4ec9b0]">document.getElementById("photo");
11image.src = "new-photo.jpg";
12image.alt = "A new photo";
13 
14// Change CSS styles
15heading.style.color = "blue";
16heading.style.fontSize = "24px";
17heading.style.backgroundColor = "yellow";

Conditions (If Statements)

Conditions let your code make decisions. Use them to do different things based on different situations:

javascript
1text-[#569cd6]">let age = 18;
2text-[#569cd6]">let hasLicense = text-[#569cd6]">true;
3 
4// Simple text-[#569cd6]">if statement
5text-[#569cd6]">if (age >= 18) {
6 text-[#4ec9b0]">console.log("You are an adult");
7}
8 
9// If-text-[#569cd6]">else statement
10text-[#569cd6]">if (age >= 18) {
11 text-[#4ec9b0]">console.log("You can vote");
12} text-[#569cd6]">else {
13 text-[#4ec9b0]">console.log("You cannot vote yet");
14}
15 
16// Multiple conditions
17text-[#569cd6]">if (age >= 18 && hasLicense) {
18 text-[#4ec9b0]">console.log("You can drive");
19} text-[#569cd6]">else text-[#569cd6]">if (age >= 18) {
20 text-[#4ec9b0]">console.log("You can get a license");
21} text-[#569cd6]">else {
22 text-[#4ec9b0]">console.log("You're too young to drive");
23}
24 
25// Checking user input
26text-[#569cd6]">let userName = text-[#4ec9b0]">prompt("What's your name?");
27text-[#569cd6]">if (userName === "") {
28 text-[#4ec9b0]">alert("Please enter your name");
29} text-[#569cd6]">else {
30 text-[#4ec9b0]">alert("Hello, " + userName + "!");
31}

Comparison Operators:

=== Equal to

!== Not equal to

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

Loops

Loops repeat code multiple times. They're useful when you need to do the same thing over and over:

For Loops
Repeat a specific number of times
javascript
1// Count from 1 to 5
2text-[#569cd6]">for (text-[#569cd6]">let i = 1; i <= 5; i++) {
3 text-[#4ec9b0]">console.log("Count: " + i);
4}
5 
6// Loop through an array
7text-[#569cd6]">let fruits = ["apple", "banana", "orange"];
8text-[#569cd6]">for (text-[#569cd6]">let i = 0; i < fruits.length; i++) {
9 text-[#4ec9b0]">console.log("Fruit: " + fruits[i]);
10}
11 
12// Create a list in HTML
13text-[#569cd6]">let list = text-[#4ec9b0]">document.getElementById("fruit-list");
14text-[#569cd6]">for (text-[#569cd6]">let i = 0; i < fruits.length; i++) {
15 list.innerHTML += "
  • " + fruits[i] + "
  • ";
    16}
    While Loops
    Repeat while a condition is true
    javascript
    1// Count down from 5
    2text-[#569cd6]">let count = 5;
    3text-[#569cd6]">while (count > 0) {
    4 text-[#4ec9b0]">console.log("Countdown: " + count);
    5 count = count - 1; // or count--
    6}
    7 
    8// Keep asking until user enters something
    9text-[#569cd6]">let userInput = "";
    10text-[#569cd6]">while (userInput === "") {
    11 userInput = text-[#4ec9b0]">prompt("Please enter your name:");
    12}
    13text-[#4ec9b0]">alert("Hello, " + userInput + "!");
    14 
    15// Simple guessing game
    16text-[#569cd6]">let secretNumber = 7;
    17text-[#569cd6]">let guess = 0;
    18text-[#569cd6]">while (guess !== secretNumber) {
    19 guess = parseInt(text-[#4ec9b0]">prompt("Guess a number 1-10:"));
    20 text-[#569cd6]">if (guess === secretNumber) {
    21 text-[#4ec9b0]">alert("Correct!");
    22 } text-[#569cd6]">else {
    23 text-[#4ec9b0]">alert("Try again!");
    24 }
    25}

    Arrays (Lists)

    Arrays store multiple values in a single variable. Think of them as lists:

    javascript
    1// Creating arrays
    2text-[#569cd6]">let colors = ["red", "green", "blue"];
    3text-[#569cd6]">let numbers = [1, 2, 3, 4, 5];
    4text-[#569cd6]">let mixed = ["hello", 42, text-[#569cd6]">true, "world"];
    5 
    6// Accessing array items (starts at 0)
    7text-[#4ec9b0]">console.log(colors[0]); // "red"
    8text-[#4ec9b0]">console.log(colors[1]); // "green"
    9text-[#4ec9b0]">console.log(colors[2]); // "blue"
    10 
    11// Array properties and methods
    12text-[#4ec9b0]">console.log(colors.length); // 3 (number of items)
    13colors.push("yellow"); // Add to end
    14colors.pop(); // Remove from end
    15colors.unshift("purple"); // Add to beginning
    16colors.shift(); // Remove from beginning
    17 
    18// Loop through array
    19text-[#569cd6]">for (text-[#569cd6]">let i = 0; i < colors.length; i++) {
    20 text-[#4ec9b0]">console.log("Color " + (i + 1) + ": " + colors[i]);
    21}
    22 
    23// Modern way to loop through array
    24colors.forEach(text-[#569cd6]">function(color, index) {
    25 text-[#4ec9b0]">console.log("Color " + (index + 1) + ": " + color);
    26});

    Array Tips:

    • • Array indexes start at 0, not 1
    • • Use length to get the number of items
    • • Arrays can hold different types of data
    • • Use push() to add items

    Objects

    Objects store related information together. They're like real-world objects with properties:

    javascript
    1// Creating an object
    2text-[#569cd6]">let person = {
    3 name: "John",
    4 age: 25,
    5 city: "New York",
    6 isStudent: text-[#569cd6]">false
    7};
    8 
    9// Accessing object properties
    10text-[#4ec9b0]">console.log(person.name); // "John"
    11text-[#4ec9b0]">console.log(person["age"]); // 25
    12 
    13// Changing object properties
    14person.age = 26;
    15person.job = "Developer"; // Add new property
    16 
    17// Object with methods (functions)
    18text-[#569cd6]">let calculator = {
    19 add: text-[#569cd6]">function(a, b) {
    20 text-[#569cd6]">return a + b;
    21 },
    22 subtract: text-[#569cd6]">function(a, b) {
    23 text-[#569cd6]">return a - b;
    24 }
    25};
    26 
    27// Using object methods
    28text-[#569cd6]">let sum = calculator.add(5, 3); // 8
    29text-[#569cd6]">let difference = calculator.subtract(10, 4); // 6
    30 
    31// Array of objects
    32text-[#569cd6]">let students = [
    33 {name: "Alice", grade: 85},
    34 {name: "Bob", grade: 92},
    35 {name: "Charlie", grade: 78}
    36];
    37 
    38// Loop through array of objects
    39text-[#569cd6]">for (text-[#569cd6]">let i = 0; i < students.length; i++) {
    40 text-[#4ec9b0]">console.log(students[i].name + " got " + students[i].grade);
    41}

    Practical Examples

    Here are some real-world examples you can try in your own projects:

    Image Gallery
    Click to change images
    javascript
    1// HTML
    2gallery" src="image1.jpg" alt="Gallery" />
    3
    4
    5 
    6// JavaScript
    7text-[#569cd6]">let images = ["image1.jpg", "image2.jpg", "image3.jpg"];
    8text-[#569cd6]">let currentImage = 0;
    9 
    10text-[#569cd6]">function nextImage() {
    11 currentImage++;
    12 text-[#569cd6]">if (currentImage >= images.length) {
    13 currentImage = 0; // Go back to first image
    14 }
    15 text-[#4ec9b0]">document.getElementById("gallery").src = images[currentImage];
    16}
    17 
    18text-[#569cd6]">function previousImage() {
    19 currentImage--;
    20 text-[#569cd6]">if (currentImage < 0) {
    21 currentImage = images.length - 1; // Go to last image
    22 }
    23 text-[#4ec9b0]">document.getElementById("gallery").src = images[currentImage];
    24}
    Simple Calculator
    Basic math operations
    javascript
    1// HTML
    2number" id="num1" placeholder="First number" />
    3number" id="num2" placeholder="Second number" />
    4
    5
    6
    7
    8

    result">

    9 
    10// JavaScript
    11text-[#569cd6]">function calculate(operation) {
    12 text-[#569cd6]">let num1 = parseFloat(text-[#4ec9b0]">document.getElementById("num1").value);
    13 text-[#569cd6]">let num2 = parseFloat(text-[#4ec9b0]">document.getElementById("num2").value);
    14 text-[#569cd6]">let result;
    15
    16 text-[#569cd6]">if (operation === "add") {
    17 result = num1 + num2;
    18 } text-[#569cd6]">else text-[#569cd6]">if (operation === "subtract") {
    19 result = num1 - num2;
    20 } text-[#569cd6]">else text-[#569cd6]">if (operation === "multiply") {
    21 result = num1 * num2;
    22 } text-[#569cd6]">else text-[#569cd6]">if (operation === "divide") {
    23 result = num1 / num2;
    24 }
    25
    26 text-[#4ec9b0]">document.getElementById("result").textContent = "Result: " + result;
    27}
    To-Do List
    Add and remove tasks
    javascript
    1// HTML
    2text" id="taskInput" placeholder="Enter a task" />
    3
    4
      taskList">
    5 
    6// JavaScript
    7text-[#569cd6]">let tasks = [];
    8 
    9text-[#569cd6]">function addTask() {
    10 text-[#569cd6]">let input = text-[#4ec9b0]">document.getElementById("taskInput");
    11 text-[#569cd6]">let task = input.value.trim();
    12
    13 text-[#569cd6]">if (task !== "") {
    14 tasks.push(task);
    15 input.value = ""; // Clear input
    16 displayTasks();
    17 }
    18}
    19 
    20text-[#569cd6]">function removeTask(index) {
    21 tasks.splice(index, 1); // Remove task at index
    22 displayTasks();
    23}
    24 
    25text-[#569cd6]">function displayTasks() {
    26 text-[#569cd6]">let list = text-[#4ec9b0]">document.getElementById("taskList");
    27 list.innerHTML = ""; // Clear list
    28
    29 text-[#569cd6]">for (text-[#569cd6]">let i = 0; i < tasks.length; i++) {
    30 list.innerHTML +=
    31 "
  • " + tasks[i] +
  • 32 " ";
    33 }
    34}
    Form Validation
    Check form input before submitting
    javascript
    1// HTML
    2
    signupForm" onsubmit=""text-[#569cd6]">return validateForm()">
    3 text" id="username" placeholder="Username" required />
    4 email" id="email" placeholder="Email" required />
    5 password" id="password" placeholder="Password" required />
    6
    7
    8
    errors">
    9 
    10// JavaScript
    11text-[#569cd6]">function validateForm() {
    12 text-[#569cd6]">let username = text-[#4ec9b0]">document.getElementById("username").value;
    13 text-[#569cd6]">let email = text-[#4ec9b0]">document.getElementById("email").value;
    14 text-[#569cd6]">let password = text-[#4ec9b0]">document.getElementById("password").value;
    15 text-[#569cd6]">let errors = [];
    16
    17 text-[#569cd6]">if (username.length < 3) {
    18 errors.push("Username must be at least 3 characters");
    19 }
    20
    21 text-[#569cd6]">if (!email.includes("@")) {
    22 errors.push("Please enter a valid email");
    23 }
    24
    25 text-[#569cd6]">if (password.length < 6) {
    26 errors.push("Password must be at least 6 characters");
    27 }
    28
    29 text-[#569cd6]">if (errors.length > 0) {
    30 text-[#4ec9b0]">document.getElementById("errors").innerHTML =
    31 "

    " + errors.join("
    ") + "

    ";
    32 text-[#569cd6]">return text-[#569cd6]">false; // Don't submit form
    33 }
    34
    35 text-[#4ec9b0]">alert("Form submitted successfully!");
    36 text-[#569cd6]">return text-[#569cd6]">true; // Submit form
    37}

    Practice Exercise

    Create an interactive webpage with JavaScript that includes:

    • A button that changes the page background color when clicked
    • A text input where users can enter their name
    • A greeting that appears when they click a "Greet Me" button
    • A simple counter that increases when you click a button
    • A list where you can add new items

    Use our code editor to practice! Start with HTML structure, add CSS styling, then make it interactive with JavaScript.