Complete JavaScript Tutorial

Table of Contents

1. Introduction to JavaScript

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. It is best known as the scripting language for Web pages, but it's also used in many non-browser environments such as Node.js, mobile apps (React Native), and desktop apps (Electron).

It enables interactive web pages and is an essential part of web applications.

Tip for Practice: Open your browser's Developer Tools (F12 or right-click > Inspect, then go to the "Console" tab) to test JavaScript snippets directly and see their output. For HTML/DOM manipulation, create local HTML files and link external JS.

2. Where to Write JavaScript

JavaScript code can be placed in HTML documents in three ways:

A. Inline JavaScript (Discouraged for maintainability)

Code is written directly within an HTML tag using an event attribute (e.g., `onclick`, `onmouseover`).

<button onclick="alert('Hello from inline JS!');">Click Me</button>

Visual Example:

(Clicking this button will show an alert box.)

B. Internal (Embedded) JavaScript

Code is placed within `<script>` tags inside the HTML document. Common for small scripts or when the script is specific to that page.

<!DOCTYPE html>
<html>
<head>
    <title>Internal JS Example</title>
</head>
<body>
    <h2 id="demo">Original Text</h2>

    <script>
        // Get the element by its ID
        const element = document.getElementById('demo');
        // Change its text content
        element.textContent = 'Text changed by internal JS!';
        // Log to console (check your browser's DevTools Console)
        console.log('Internal JS executed!');
    </script>
</body>
</html>

Visual Example (After page loads):

Original Text

(The text above changes immediately on page load from "Original Text" to "Text changed by internal JS!". Check your browser console for "Internal JS executed!".)

C. External JavaScript (Recommended)

Code is written in a separate `.js` file and linked to the HTML document using the `<script>` tag with the `src` attribute. This is the best practice for larger projects as it improves organization, caching, and maintainability.

<!DOCTYPE html>
<html>
<head>
    <title>External JS Example</title>
</head>
<body>
    <h2 id="extJsDemo">Text from HTML</h2>
    <button id="extJsButton" class="js-example-button">Click for External JS</button>

    <!-- Link to your external JavaScript file -->
    <script src="script.js" defer></script>
</body>
</html>

And in your `script.js` file:

// script.js
document.addEventListener('DOMContentLoaded', function() {
    const heading = document.getElementById('extJsDemo');
    const button = document.getElementById('extJsButton');

    if (button) {
        button.addEventListener('click', function() {
            if (heading) {
                heading.textContent = 'Text changed by external JS!';
                heading.style.color = 'blue';
            }
            console.log('Button clicked! External JS function triggered.');
        });
    }
    console.log('External script.js loaded!');
});

Visual Example:

Text from HTML

(The text above will change and turn blue when you click the button. Check your browser console for log messages.)

`defer` and `async` attributes:

3. Variables and Data Types

Variables are containers for storing data values. JavaScript has three keywords to declare variables: `var`, `let`, and `const`.

var oldVar = "Hello";
oldVar = "World"; // Re-assigned
var oldVar = "New Value"; // Re-declared (can lead to bugs)

let message = "Hi there!";
message = "Goodbye!"; // Re-assigned
// let message = "Another Hi!"; // Error: Cannot re-declare

const PI = 3.14159;
// PI = 3.14; // Error: Cannot re-assign a const
const USER_ID = 101; // Good for constants

Data Types:

JavaScript is a dynamically typed language, meaning you don't declare the type of a variable. It automatically determines the type when a value is assigned.

let greeting = "Hello, JavaScript!"; // String
let year = 2023; // Number
let price = 19.99; // Number
let isActive = true; // Boolean
let myVar; // Undefined
let emptyValue = null; // Null
let person = { name: "Alice", age: 30 }; // Object
let colors = ["red", "green", "blue"]; // Array (which is also an object)

console.log(typeof greeting);     // Output: string
console.log(typeof year);         // Output: number
console.log(typeof isActive);     // Output: boolean
console.log(typeof myVar);        // Output: undefined
console.log(typeof emptyValue);   // Output: object (a quirk in JS)
console.log(typeof person);       // Output: object
console.log(typeof colors);       // Output: object (Arrays are objects)

Visual Example (Output to Browser Console):

Check the browser console (F12 > Console) after loading this page to see the `typeof` outputs.

4. Operators

Operators perform operations on values and variables.

Visual Example (Output to Browser Console):

Check the browser console (F12 > Console) for the output of these operations.

5. Control Flow (Conditionals & Loops)

Control flow statements dictate the order in which instructions are executed.

Conditionals:

Loops:

Visual Example (Output to Browser Console):

Check the browser console (F12 > Console) for the output of these control flow examples.

6. Functions

Functions are reusable blocks of code that perform a specific task. They can take inputs (parameters) and return a value.

Visual Example (Output to Browser Console):

Check the browser console for function outputs.

7. Arrays

Arrays are ordered lists of values. They are zero-indexed, meaning the first element is at index 0.

const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]); // apple
console.log(fruits.length); // 3

// Common Array Methods
fruits.push("date"); // Adds to the end: ["apple", "banana", "cherry", "date"]
fruits.pop(); // Removes from the end: ["apple", "banana", "cherry"]
fruits.unshift("kiwi"); // Adds to the beginning: ["kiwi", "apple", "banana", "cherry"]
fruits.shift(); // Removes from the beginning: ["apple", "banana", "cherry"]

const index = fruits.indexOf("banana"); // 1
fruits.splice(index, 1); // Removes "banana": ["apple", "cherry"]

const citrus = fruits.slice(0, 1); // Creates a new array: ["apple"] (non-destructive)

fruits.forEach(fruit => console.log("I like " + fruit));
const newFruits = fruits.map(fruit => fruit.toUpperCase()); // ["APPLE", "CHERRY"]
const filteredFruits = fruits.filter(fruit => fruit.startsWith("a")); // ["apple"]

Visual Example (Output to Browser Console):

Check the browser console for array manipulation outputs.

8. Objects

Objects are collections of key-value pairs. They are fundamental for representing complex data.

const person = {
    firstName: "Jane",
    lastName: "Doe",
    age: 28,
    isStudent: false,
    hobbies: ["reading", "hiking", "cooking"],
    address: {
        street: "123 Main St",
        city: "Anytown"
    },
    // Method within an object
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

// Accessing properties
console.log(person.firstName); // Jane
console.log(person["age"]); // 28
console.log(person.hobbies[1]); // hiking
console.log(person.address.city); // Anytown
console.log(person.fullName()); // Jane Doe

// Modifying properties
person.age = 29;
person.email = "jane.doe@example.com"; // Add new property

// Deleting properties
delete person.isStudent;

// Iterating over object properties
for (const key in person) {
    if (typeof person[key] !== 'function') { // Exclude methods
        console.log(`${key}: ${person[key]}`);
    }
}

Visual Example (Output to Browser Console):

Check the browser console for object property access and iteration.

9. DOM Manipulation

The Document Object Model (DOM) is a programming interface for web documents. It represents the page structure as a tree of objects. JavaScript can access and change all the elements on an HTML page.

<div id="domDemo" style="border: 1px solid #ccc; padding: 10px;">
    <p>Original DOM content.</p>
</div>
<button id="changeDomBtn" class="js-example-button">Change DOM</button>
<button id="addRemoveBtn" class="js-example-button">Add/Remove Item</button>

<style>
    .highlighted {
        background-color: yellow;
        font-weight: bold;
    }
</style>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const domDemoDiv = document.getElementById('domDemo');
        const changeBtn = document.getElementById('changeDomBtn');
        const addRemoveBtn = document.getElementById('addRemoveBtn');
        let itemCount = 0;

        changeBtn.addEventListener('click', function() {
            domDemoDiv.innerHTML = '<h3>DOM Changed!</h3><p class="highlighted">New content with a highlight.</p>';
            domDemoDiv.style.backgroundColor = '#e0f7fa'; // Change background style
        });

        addRemoveBtn.addEventListener('click', function() {
            if (itemCount % 2 === 0) {
                const newItem = document.createElement('p');
                newItem.textContent = `Dynamically added item ${++itemCount}`;
                newItem.style.color = 'blue';
                domDemoDiv.appendChild(newItem);
            } else {
                if (domDemoDiv.lastChild && domDemoDiv.lastChild.nodeName === 'P') { // Ensure it's a paragraph
                     domDemoDiv.removeChild(domDemoDiv.lastChild);
                     itemCount--;
                }
            }
        });
    });
</script>

Visual Example:

Original DOM content.

(Click "Change DOM" to replace content. Click "Add/Remove Item" to dynamically add/remove paragraphs.)

10. Event Handling

JavaScript allows you to react to user actions or browser events (e.g., clicks, key presses, page load). This is done using event listeners.

<button id="myButton">Click me!</button>
<input type="text" id="myInput" placeholder="Type here...">
<p id="outputArea">Watch output here.</p>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const button = document.getElementById('myButton');
        const input = document.getElementById('myInput');
        const output = document.getElementById('outputArea');

        // Add a click event listener
        button.addEventListener('click', function() {
            output.textContent = 'Button was clicked!';
        });

        // Add a keyup event listener
        input.addEventListener('keyup', function() {
            output.textContent = 'You typed: ' + input.value;
        });

        // Event object provides details about the event
        input.addEventListener('keydown', function(event) {
            console.log('Key pressed:', event.key, 'Code:', event.code);
        });
    });
</script>

Visual Example:

Watch output here.

(Click the button or type in the input field to see the output change.)

11. Error Handling

JavaScript provides mechanisms to handle errors gracefully, preventing your script from crashing.

Visual Example (Output to Browser Console):

Check the browser console to see how errors are caught and logged.

12. Asynchronous JavaScript

JavaScript is single-threaded, but it can handle operations that take time (like fetching data from a server) without blocking the main thread, using asynchronous patterns.

Visual Example (Output to Browser Console with delays):

Check the browser console (F12 > Console) to observe the sequence of logs for asynchronous operations.

(You'll see "Callback/Promise/Async function called immediately" logs first, followed by "Data fetched..." logs after their respective delays.)

13. ES6+ Features

ECMAScript 2015 (ES6) introduced many significant features that revolutionized JavaScript development. Subsequent versions (ES7, ES8, etc.) continue to add improvements.

Visual Example (Output to Browser Console):

Check the browser console for ES6+ feature outputs.

14. Best Practices

The Journey Continues!

JavaScript is a dynamic and powerful language that is constantly evolving. Mastering these fundamentals is the first step. From here, you can dive into advanced topics like Web APIs (Fetch API, Web Storage), advanced array/object methods, design patterns, and explore popular frameworks/libraries like React, Angular, or Vue.js to build complex and interactive web applications.