Back Back

JavaScript Programming

Master JavaScript for building interactive web applications, from core concepts to advanced integrations with HTML and React.

Introduction to JavaScript

What is JavaScript?

JavaScript is a high-level, interpreted programming language primarily used for adding interactivity to web pages. It runs in browsers and on servers (via Node.js), supporting dynamic content, event handling, and asynchronous operations.

Key Features:

  • Client-Side Interactivity: Enhances web pages with dynamic behavior.
  • Versatile: Used for web, mobile apps, and server-side development.
  • Event-Driven: Responds to user actions like clicks and keypresses.
  • Asynchronous: Supports non-blocking operations with promises and async/await.
  • Cross-Platform: Runs in browsers and on servers with Node.js.

Java vs. JavaScript

Despite similar names, Java and JavaScript are distinct languages with different purposes:

  • Java: A compiled, object-oriented language for platform-independent applications, used in enterprise systems, Android apps, and more.
  • JavaScript: An interpreted language for web development, focusing on client-side interactivity and server-side scripting (Node.js).
  • Syntax: Java is strongly typed with strict syntax; JavaScript is loosely typed with flexible syntax.
  • Execution: Java runs on the JVM; JavaScript runs in browsers or Node.js.

Example showcasing syntax differences (Run in respective environments):


// Java (Run in a Java IDE or compiler)
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); // Output: Hello, World!
    }
}

// JavaScript (Run in browser console or Node.js)
console.log("Hello, World!"); // Output: Hello, World!
                    

Types of JavaScript

JavaScript can be included in HTML in three ways: inline, internal, and external.

  • Inline JavaScript: Code written directly in HTML event attributes.
  • Internal JavaScript: Code placed within a <script> tag in the HTML file.
  • External JavaScript: Code in a separate .js file linked via the <script> tag.

Examples (Save as HTML file or test in browser):


<!DOCTYPE html>
<html>
<body>
    <!-- Inline JavaScript -->
    <button onclick="alert('Clicked!')">Click Me</button> <!-- Output: Alert box with "Clicked!" -->

    <!-- Internal JavaScript -->
    <script>
        console.log("This is internal JavaScript"); // Output: This is internal JavaScript (in console)
    </script>

    <!-- External JavaScript (save as script.js and link) -->
    <script src="script.js"></script>
</body>
</html>

// script.js
console.log("This is external JavaScript"); // Output: This is external JavaScript (in console)
                    

Core Concepts

Variables

Definition: Variables store data values, declared using var, let, or const.

Types of Variables:

  • var: Function-scoped, can be redeclared and updated (older syntax).
  • let: Block-scoped, can be updated but not redeclared in the same scope.
  • const: Block-scoped, cannot be updated or redeclared.

Naming Rules:

  • Must start with a letter, underscore (_), or dollar sign ($).
  • Cannot use reserved keywords (e.g., if, for).
  • Case-sensitive (e.g., Namename).

// Run in browser console or Node.js
// Input: age = 25, name = "Alice", PI = 3.14
var age = 25; // Function-scoped
let name = "Alice"; // Block-scoped
const PI = 3.14; // Constant
name = "Bob"; // Valid
// PI = 3.1415; // Error: Assignment to constant
console.log(name + " is " + age); // Output: Bob is 25
                    

Printing in JavaScript

Definition: Printing in JavaScript refers to outputting data to the console, browser, or user interface for debugging or display purposes.

Methods to Print:

  • console.log(): Outputs messages to the console for debugging (general purpose).
  • console.warn(): Outputs warnings to the console with a yellow highlight.
  • console.error(): Outputs errors to the console with a red highlight.
  • alert(): Displays a simple dialog box with a message.
  • document.write(): Writes directly to the HTML document (not recommended for modern apps).
  • DOM Manipulation: Updates HTML elements using methods like innerHTML or textContent.

<!DOCTYPE html>
<html>
<head>
    <title>Printing in JavaScript</title>
</head>
<body>
    <div id="output"></div>
    <script>
        // Run in browser (save as HTML file)
        // Input: message = "Hello, World!", number = 42

        // console.log
        console.log("Hello, World!"); // Output: Hello, World! (in console)

        // console.warn
        console.warn("This is a warning!"); // Output: This is a warning! (yellow in console)

        // console.error
        console.error("This is an error!"); // Output: This is an error! (red in console)

        // alert
        alert("Hello, World!"); // Output: Browser alert box with "Hello, World!"

        // document.write (avoid in production)
        document.write("Hello, World!"); // Output: Writes "Hello, World!" to the HTML document

        // DOM Manipulation
        const output = document.getElementById("output");
        output.textContent = "Number: " + 42; // Output: Number: 42 (displayed in HTML)
    </script>
</body>
</html>
                    

Operators

Definition: Operators perform operations on variables and values.

Arithmetic Operators

Perform mathematical operations.

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulus
  • ++: Increment
  • --: Decrement

// Run in browser console or Node.js
// Input: x = 10, y = 3
let x = 10, y = 3;
console.log(x + y); // Output: 13
console.log(x % y); // Output: 1
console.log(x++); // Output: 10 (post-increment, x becomes 11)
                            

Comparison Operators

Compare values, return boolean.

  • ==: Equal (loose)
  • ===: Strict equal
  • !=: Not equal (loose)
  • !==: Strict not equal
  • >, <, >=, <=

// Run in browser console or Node.js
// Input: a = 5, b = "5"
let a = 5, b = "5";
console.log(a == b); // Output: true (loose equality)
console.log(a === b); // Output: false (strict equality)
console.log(a > 3); // Output: true
                            

Logical Operators

Combine boolean expressions.

  • &&: AND
  • ||: OR
  • !: NOT

// Run in browser console or Node.js
// Input: x = true, y = false
let x = true, y = false;
console.log(x && y); // Output: false
console.log(x || y); // Output: true
console.log(!x); // Output: false
                            

Assignment Operators

Assign values to variables.

  • =: Assign
  • +=, -=, *=, /=, %=

// Run in browser console or Node.js
// Input: x = 10
let x = 10;
x += 5; // x = x + 5
console.log(x); // Output: 15
                            

Conditional Statements

Definition: Conditional statements control program flow based on conditions.

Types:

  • if: Executes if condition is true.
  • else if: Checks additional conditions.
  • else: Executes if no conditions are true.
  • switch: Selects a block of code based on a value.
  • ?: (Ternary): Shorthand for if-else.

// Run in browser console or Node.js
// Input: age = 20, day = 1
// If-Else
let age = 20;
if (age >= 18) {
    console.log("Adult"); // Output: Adult
} else if (age >= 13) {
    console.log("Teen");
} else {
    console.log("Child");
}

// Switch
let day = 1;
switch (day) {
    case 1:
        console.log("Monday"); // Output: Monday
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Invalid day");
}

// Ternary
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Output: Adult
                    

Loops

Definition: Loops execute code repeatedly based on a condition.

Types:

  • for: Iterates a set number of times.
  • while: Runs while a condition is true.
  • do-while: Runs at least once, then checks condition.
  • forEach: Iterates over arrays.
  • for...in: Iterates over object properties.
  • for...of: Iterates over iterable objects.

// Run in browser console or Node.js
// Input: arr = [1, 2, 3], obj = { a: 1, b: 2 }, str = "Hi"
// For Loop
for (let i = 1; i <= 3; i++) {
    console.log(i); // Output: 1, 2, 3
}

// While Loop
let j = 1;
while (j <= 3) {
    console.log(j); // Output: 1, 2, 3
    j++;
}

// Do-While Loop
let k = 1;
do {
    console.log(k); // Output: 1, 2, 3
    k++;
} while (k <= 3);

// forEach
let arr = [1, 2, 3];
arr.forEach(num => console.log(num)); // Output: 1, 2, 3

// for...in (Object)
let obj = { a: 1, b: 2 };
for (let key in obj) {
    console.log(key); // Output: a, b
}

// for...of (Iterable)
let str = "Hi";
for (let char of str) {
    console.log(char); // Output: H, i
}
                    

Functions

Definition: Functions are reusable blocks of code that perform specific tasks, accepting parameters and returning values.

Types:

  • Function Declaration: Named function with hoisting.
  • Function Expression: Anonymous function assigned to a variable.
  • Arrow Function: Concise syntax, no own this.
  • IIFE: Immediately Invoked Function Expression.

// Run in browser console or Node.js
// Input: name = "Alice", a = 2, b = 3
// Function Declaration
function greet(name) {
    return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice

// Function Expression
const add = function(a, b) {
    return a + b;
};
console.log(add(2, 3)); // Output: 5

// Arrow Function
const multiply = (a, b) => a * b;
console.log(multiply(2, 3)); // Output: 6

// IIFE
(function() {
    console.log("Runs immediately!"); // Output: Runs immediately!
})();
                    

JavaScript with HTML and React

JavaScript with HTML

Definition: JavaScript interacts with HTML via the Document Object Model (DOM) to manipulate elements dynamically.

Common DOM Methods:

  • getElementById(): Selects an element by ID.
  • querySelector(): Selects the first matching element.
  • innerHTML: Sets or gets element content.
  • addEventListener(): Attaches event handlers.

<!DOCTYPE html>
<html>
<head>
   <title>DOM Manipulation</title>
</head>
<body>
    <h1 id="title">Hello</h1>
    <button id="btn">Click Me</button>

    <script>
        // Run in browser (save as HTML file)
        // Input: Click event on button
        const title = document.getElementById("title");
        title.innerHTML = "Hello, World!"; // Output: Updates h1 to "Hello, World!"
        
        const btn = document.querySelector("#btn");
        btn.addEventListener("click", () => {
            alert("Button clicked!"); // Output: Alert box with "Button clicked!"
        });
    </script>
</body>
</html>
                    

JavaScript with React

Definition: React is a JavaScript library for building user interfaces using components. JavaScript powers React's logic, state, and event handling.

Key Concepts:

  • Components: Reusable UI blocks.
  • State: Manages dynamic data.
  • Props: Passes data to components.
  • Hooks: Functions like useState for state management.

<!DOCTYPE html>
<html>
<head>
    <title>React Counter</title>
    <script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.20.15/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">
        // Run in browser (save as HTML file)
        // Input: Click event on button
        const Counter = () => {
            const [count, setCount] = React.useState(0);
            return (
                <div>
                    <h1>Count: {count}</h1>
                    <button onClick={() => setCount(count + 1)}>Increment</button>
                </div>
            );
        };
        ReactDOM.render(<Counter />, document.getElementById("root"));
        // Output: Displays "Count: 0" initially, increments on button click
    </script>
</body>
</html>
                    

Explanation:

  • useState: Hook to manage state (count).
  • onClick: Event handler for button clicks.
  • ReactDOM.render: Renders the component to the DOM.

Test Your Knowledge

1. Which keyword is used to declare a constant in JavaScript?

A) let
B) var
C) const
D) static

2. What is the output of console.log(5 == '5');?

A) false
B) true
C) undefined
D) null

3. What is the output of this code?


// Run in browser console or Node.js
let x = 3;
console.log(x++ + ++x); // Output: 8
                
A) 6
B) 7
C) 8
D) 9

4. Which method selects an HTML element by its ID?

A) querySelector()
B) getElementById()
C) getElementsByClass()
D) selectElement()

5. What is the output of this code?


// Run in browser console or Node.js
const arr = [1, 2, 3];
arr.forEach(num => console.log(num * 2)); // Output: 2, 4, 6
                
A) [2, 4, 6]
B) 2, 4, 6
C) [1, 2, 3]
D) undefined

Try It Yourself

Practice Online

Try these exercises in an online JavaScript compiler like Programiz:

Exercise 1: Simple Calculator

Create a function that adds two numbers and displays the result.


// Run in browser console or Node.js
// Input: a = 5, b = 3
function add(a, b) {
    return a + b;
}
console.log(add(5, 3)); // Output: 8
                        

Exercise 2: DOM Manipulation

Change the text of an HTML element when a button is clicked.


<!DOCTYPE html>
<html>
<head>
    <title>DOM Manipulation</title>
</head>
<body>
    <h1 id="title">Hello</h1>
    <button id="btn">Change Text</button>
    <script>
        // Run in browser (save as HTML file)
        // Input: Click event on button
        const title = document.getElementById("title");
        const btn = document.getElementById("btn");
        btn.addEventListener("click", () => {
            title.textContent = "Text Changed!"; // Output: Updates h1 to "Text Changed!"
        });
    </script>
</body>
</html>
                        

Exercise 3: Array Filter

Filter even numbers from an array and log them.


// Run in browser console or Node.js
// Input: numbers = [1, 2, 3, 4, 5]
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
                        

Exercise 4: React Counter

Create a React component with a counter that increments on button click.


<!DOCTYPE html>
<html>
<head>
    <title>React Counter</title>
    <script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.20.15/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">
        // Run in browser (save as HTML file)
        // Input: Click event on button
        const Counter = () => {
            const [count, setCount] = React.useState(0);
            return (
                <div>
                    <h1>Count: {count}</h1>
                    <button onClick={() => setCount(count + 1)}>Increment</button>
                </div>
            );
        };
        ReactDOM.render(<Counter />, document.getElementById("root"));
        // Output: Displays "Count: 0" initially, increments on button click
    </script>
</body>
</html>
                        

Try our recommended online JavaScript compiler:

Open Programiz JavaScript Compiler

Download Basic JavaScript Notes

View PDF Notes Download PDF Notes