Skip to the content.

← Back to Main Page

Introduction to JavaScript: Programming the Web

Table of Contents

Basics of JavaScript

JavaScript is a powerful, versatile language used for adding interactivity to websites. If you’re just starting with web development, JavaScript is an essential tool in your toolkit. In this post, we’ll cover the basics of JavaScript, including how to add JavaScript to your HTML, basic syntax, variables, data types, functions, and event handling.

1. Adding JavaScript to Your HTML

You can add JavaScript directly into your HTML file. The simplest way is by using the <script> tag.

<!DOCTYPE html>
<head>
    <title>JavaScript Basics</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <script>
        alert("Welcome to JavaScript!");
    </script>
</body>
</html>

In this example, the alert() function will display a pop-up message saying “Welcome to JavaScript!” as soon as the page loads. This method is great for testing simple scripts, but for larger projects, it’s better to link an external JavaScript file.

2. Variables and Data Types

Variables store information that can be used later in the program. In JavaScript, you can declare variables using let, const, or var.

Example: Declaring Variables

let name = "Alice"; // A string
const age = 25; // A number
var isStudent = true; // A boolean

Explanation:

Data Types

JavaScript supports several data types:

3. Basic Operations

You can perform operations like addition, subtraction, and concatenation.

let x = 5;
let y = 10;
let sum = x + y; // 15
let greeting = "Hello" + " " + "World"; // "Hello World"

4. Functions

Functions allow you to define reusable code blocks.

Example: Basic Function

function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("Alice")); // Output: Hello, Alice!

Explanation:

5. Conditional Statements

Conditions allow you to make decisions in your code.

Example: If-Else Statement

let age = 18;

if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}

6. Looping Statements

JavaScript provides several types of loops that allow you to execute code multiple times.

1. for Loop

for (let i = 0; i < 5; i++) {
    console.log("Iteration:", i);
}

2. while Loop

let i = 0;
while (i < 5) {
    console.log("Iteration:", i);
    i++;
}

3. do…while Loop

let i = 0;
do {
    console.log("Iteration:", i);
    i++;
} while (i < 5);

4. for…of Loop

let numbers = [10, 20, 30];
for (let number of numbers) {
    console.log(number);
}

5. for…in Loop

let person = { name: "Alice", age: 25 };
for (let key in person) {
    console.log(key + ": " + person[key]);
}

7. Event Handling

JavaScript is often used to handle events like clicks or key presses.

Example: Button Click Event

<!DOCTYPE html>
<html
<body>
    <button onclick="showMessage()">Click Me</button>
    <script>
        function showMessage() {
            alert("Button was clicked!");
        }
    </script>
</body>
</html>

In this example, clicking the button triggers the showMessage() function, which shows an alert.

Understand and Learn

Example: Adding Two Numbers

<!DOCTYPE html>
<head>
    <title>Add Two Numbers</title>
</head>
<body>

    <h1>Add Two Numbers</h1>
    
    <input type="number" id="num1" placeholder="Enter first number">
    <br>
    <input type="number" id="num2" placeholder="Enter second number">
    <br>
    <button onclick="addNumbers()">Add</button>

    <h2 id="result"></h2>

    <script>
        function addNumbers() {
            // Get the values from the input fields
            let num1 = parseFloat(document.getElementById("num1").value);
            let num2 = parseFloat(document.getElementById("num2").value);
            
            // Check if the inputs are valid numbers
            if (isNaN(num1) || isNaN(num2)) {
                document.getElementById("result").innerText = "Please enter valid numbers.";
            } else {
                // Calculate the sum
                let sum = num1 + num2;
                
                // Display the result
                document.getElementById("result").innerText = "Sum: " + sum;
            }
        }
    </script>

</body>
</html>

Explanation:

HTML Structure:

JavaScript Function addNumbers():


Example: Finding Prime Numbers

<!DOCTYPE html>
<html
<head>
    <title>Prime Numbers</title>
</head>
<body>

    <h1>Prime Number Finder</h1>

    <p>Enter a number:</p>
    <input type="number" id="num" placeholder="Enter N">
    <button onclick="findPrimes()">Show Prime Numbers</button>

    <h2>Prime Numbers:</h2>
    <p id="result"></p>

    <script>
        function isPrime(number) {
            if (number <= 1) return false;
            for (let i = 2; i <= Math.sqrt(number); i++) {
                if (number % i === 0) {
                    return false;
                }
            }
            return true;
        }

        function findPrimes() {
            let num = parseInt(document.getElementById("num").value);
            let primes = [];

            for (let i = 2; i <= num; i++) {
                if (isPrime(i)) {
                    primes.push(i);
                }
            }

            document.getElementById("result").innerText = primes.join(", ");
        }
    </script>

</body>
</html>

Explanation:

HTML Structure:

JavaScript Functions:

Learn JavaScript in 12 Hours

Here’s a video tutorial: