Back to JavaScript
2026-01-255 min read

JavaScript Examples

Learn JavaScript Examples step by step with clear examples and exercises.

Why This Matters

In this guide, we'll delve into JavaScript examples, focusing on practical applications and real-world scenarios that set us apart from other tutorials. Learning from well-explained JavaScript examples can help you:

  1. Ace coding interviews by demonstrating your understanding of the language and its capabilities.
  2. Solve real-world bugs more efficiently by recognizing common patterns and solutions.
  3. Create engaging user experiences through interactive web pages and dynamic content.
  4. Gain a deeper understanding of JavaScript concepts by applying them in various contexts.

Prerequisites

Before diving into JavaScript examples, ensure you have a basic understanding of HTML and CSS. Familiarize yourself with web browsers, web development tools, and the Document Object Model (DOM). A good grasp of data structures like arrays and objects is also beneficial.

HTML and CSS Basics

Learn the fundamental structure of an HTML document, including tags, attributes, and CSS for styling.

Web Browsers and Development Tools

Familiarize yourself with popular web browsers such as Google Chrome, Mozilla Firefox, and Microsoft Edge. Learn how to use their built-in developer tools for debugging JavaScript code.

Document Object Model (DOM)

Understand the DOM, which represents an HTML document as a tree-like structure that can be manipulated using JavaScript.

Core Concept

JavaScript is primarily used to make web pages interactive. It can manipulate HTML elements, handle user events, validate forms, and communicate with servers. To start writing JavaScript code, you'll need to understand variables, functions, loops, conditional statements, and objects.

Variables (100 words)

Variables are used to store values in your JavaScript code. You declare a variable using the let or const keyword followed by the variable name:

let myVariable = "Hello World";
const PI = 3.14;

Functions (100 words)

Functions are reusable blocks of code that perform specific tasks. You can define a function using the function keyword, followed by the function name and parentheses:

function greet(name) {
console.log("Hello, " + name);
}

Loops (100 words)

Loops allow you to repeat a block of code multiple times. JavaScript has two main types of loops: for and while.

For loop (100 words)

A for loop iterates over a specified range of values:

for (let i = 0; i < 10; i++) {
console.log(i);
}

Conditional Statements (100 words)

Conditional statements allow your code to make decisions based on certain conditions. JavaScript has three main conditional structures: if, else if, and else.

let num = 5;
if (num > 0) {
console.log("The number is positive.");
} else if (num < 0) {
console.log("The number is negative.");
} else {
console.log("The number is zero.");
}

Objects (100 words)

Objects are collections of key-value pairs that help organize data and functions in JavaScript. You can create an object using curly braces {}, followed by a comma-separated list of properties:

let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello!");
}
};

Worked Example

Let's create a simple JavaScript calculator that performs addition, subtraction, multiplication, and division using the DOM.

HTML Markup

First, we need an HTML file with input fields and buttons for our calculator:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Calculator</title>
<script src="calculator.js"></script>
</head>
<body>
<h1>JavaScript Calculator</h1>
<input type="text" id="num1" placeholder="Number 1">
<input type="text" id="num2" placeholder="Number 2">
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
</body>
</html>

JavaScript Code

Next, we'll write the JavaScript code to handle the calculator functionality using the DOM:

function calculate() {
let num1 = parseFloat(document.getElementById("num1").value);
let num2 = parseFloat(document.getElementById("num2").value);
let result;

if (isNaN(num1) || isNaN(num2)) {
alert("Please enter valid numbers.");
return;
}

result = num1 + num2;
document.getElementById("result").innerText = "Result: " + result;
}

Common Mistakes

Forgetting Semicolons

JavaScript automatically inserts semicolons at the end of statements, but it's still a good practice to include them. Leaving out semicolons can lead to syntax errors.

// Incorrect: Missing semicolon after function declaration
function greet(name)
console.log("Hello, " + name);
}

// Correct: Including semicolon after function declaration
function greet(name) {
console.log("Hello, " + name);
}

Incorrect Variable Declaration

Using var instead of let or const can lead to global variable pollution and unexpected behavior.

// Incorrect: Using var for variable declaration
var myVariable = "Hello World";
console.log(myVariable); // Outputs "Hello World"

function test() {
var myVariable = "Test";
console.log(myVariable); // Outputs "Test"
console.log(myVariable); // Outputs "Test" (global variable)
}
test();
console.log(myVariable); // Outputs "Test" (global variable)

Incorrect Comparison Operators

Using == instead of === can lead to unexpected results due to type coercion.

let num1 = 5;
let num2 = "5";

// Incorrect: Using == for comparison
if (num1 == num2) {
console.log("Numbers are equal."); // Outputs "Numbers are equal."
}

// Correct: Using === for strict equality comparison
if (num1 === num2) {
console.log("Numbers are strictly equal."); // Outputs nothing
}

Practice Questions

  1. Write a JavaScript function that checks if a given year is a leap year.
function isLeapYear(year) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return true;
} else {
return false;
}
}
  1. Create a JavaScript program that generates Fibonacci numbers up to a specified number.
function fibonacci(n) {
let num1 = 0, num2 = 1, nextNum;
let fibArray = [num1, num2];

for (let i = 2; i < n; i++) {
nextNum = num1 + num2;
fibArray.push(nextNum);
num1 = num2;
num2 = nextNum;
}
return fibArray;
}
  1. Implement a JavaScript function that reverses an array.
function reverseArray(arr) {
let reversedArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversedArr.push(arr[i]);
}
return reversedArr;
}
  1. Write a JavaScript code snippet that creates a simple counter and displays it on the screen.
let counter = 0;
function incrementCounter() {
counter++;
document.getElementById("counter").innerText = counter;
}

FAQ

What is the difference between let and const in JavaScript?

let allows you to declare variables that can be reassigned, while const creates immutable variables that cannot be changed once initialized.

How do I handle user events in JavaScript?

You can handle user events using event listeners such as addEventListener. Bind a function to an event by specifying the event type and callback function:

document.getElementById("myButton").addEventListener("click", function() {
console.log("Button clicked!");
});

What is the Document Object Model (DOM)?

The DOM is a programming interface for web documents. It represents an HTML document as a tree-like structure that can be manipulated using JavaScript.

JavaScript Examples | JavaScript | XQA Learn