JavaScript Complete Tutorial

JavaScript
Beginner to Advanced

Learn JavaScript step by step with detailed explanations, syntax, practical examples, DOM manipulation, events, arrays, objects, APIs, asynchronous programming, modern ES6+ features and real-world projects.

1. What is JavaScript?

JavaScript is a high-level programming language commonly used to make websites interactive and dynamic. HTML provides the structure of a webpage, CSS controls its appearance, and JavaScript adds behavior and functionality.

Simple definition: JavaScript allows a webpage to respond to user actions, change content, validate forms, communicate with servers, create animations and build complete web applications.

Why Learn JavaScript?

  • It makes websites interactive.
  • It works directly in modern browsers.
  • It can communicate with APIs and servers.
  • It is used by many modern web applications.
  • It can be used for frontend and backend development.
  • It is an important foundation for learning modern JavaScript frameworks.

Your First JavaScript Program

JavaScript Example
console.log("Hello JavaScript!");

2. Adding JavaScript to HTML

JavaScript can be added to an HTML document in several ways. The most common approaches are inline, internal and external JavaScript.

Inline JavaScript

HTML
<button onclick="alert('Hello JavaScript!')">
    Click Me
</button>

Internal JavaScript

HTML + JavaScript
<script>

console.log("Internal JavaScript");

</script>

External JavaScript

HTML
<script src="script.js"></script>
Best practice: For larger projects, keep JavaScript in external .js files.

3. JavaScript Syntax

Syntax means the rules used to write JavaScript code. JavaScript statements normally perform an operation or instruction.

Comments

JavaScript
// Single-line comment

/*
   Multi-line comment
*/

console.log("Hello");

Case Sensitivity

JavaScript is case-sensitive. For example, name and Name are different identifiers.

4. JavaScript Variables

Variables are containers used to store data. Modern JavaScript mainly uses let and const.

let

JavaScript
let name = "Kamran";

name = "Ahmed";

console.log(name);

const

JavaScript
const country = "Pakistan";

console.log(country);
Avoid using var in new code unless you specifically need its older function-scoping behavior.

5. JavaScript Data Types

JavaScript supports primitive and object data types. Common primitive types include string, number, boolean, undefined, null, bigint and symbol.

Data Types Example
let name = "Kamran";       // String
let age = 30;              // Number
let student = true;        // Boolean
let city;                  // Undefined
let value = null;          // Null

console.log(typeof name);
console.log(typeof age);
console.log(typeof student);

Objects

Object Example
let student = {
    name: "Ali",
    age: 20,
    course: "Web Development"
};

console.log(student.name);

6. JavaScript Operators

Operators perform calculations, comparisons and logical operations.

Arithmetic

+, -, *, /, %, **

Comparison

==, ===, !=, !==, >, <, >=, <=

Logical

&&, ||, !

Assignment

=, +=, -=, *=, /=

Operators Example
let a = 10;
let b = 5;

console.log(a + b);
console.log(a > b);
console.log(a === b);
console.log(a && b);

7. JavaScript Strings

Strings are sequences of characters used to represent text.

String Methods
let name = "Kamran Anjum";

console.log(name.length);

console.log(name.toUpperCase());

console.log(name.toLowerCase());

console.log(name.includes("Anjum"));

console.log(name.slice(0, 6));

Template Literals

Template Literal
let name = "Ali";
let age = 20;

let message = `My name is ${name} and I am ${age} years old.`;

console.log(message);

8. Numbers and Math

Math Methods
let number = 5.7;

console.log(Math.round(number));

console.log(Math.floor(number));

console.log(Math.ceil(number));

console.log(Math.max(10, 20, 30));

console.log(Math.min(10, 20, 30));

console.log(Math.random());

9. Conditional Statements

Conditional statements allow a program to make decisions.

if / else Example
let marks = 75;

if (marks >= 80) {

    console.log("A Grade");

} else if (marks >= 60) {

    console.log("B Grade");

} else {

    console.log("Needs Improvement");

}

switch Statement

Switch Example
let day = 2;

switch(day){

    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    default:
        console.log("Unknown day");
}

10. JavaScript Loops

Loops are used when you need to execute code repeatedly.

for Loop

for Loop
for(let i = 1; i <= 5; i++){

    console.log(i);

}

while Loop

while Loop
let i = 1;

while(i <= 5){

    console.log(i);

    i++;
}

break and continue

break / continue
for(let i = 1; i <= 10; i++){

    if(i === 5){
        break;
    }

    console.log(i);
}

11. JavaScript Functions

A function is a reusable block of code designed to perform a specific task.

Function Example
function add(a, b){

    return a + b;

}

let result = add(10, 20);

console.log(result);

Arrow Function

Arrow Function
const add = (a, b) => {

    return a + b;

};

console.log(add(10, 20));

12. JavaScript Arrays

Arrays store multiple values in a single variable.

Array Example
let students = [
    "Ali",
    "Sara",
    "Ahmed"
];

console.log(students[0]);

students.push("Kamran");

console.log(students);

Common Array Methods

  • push() — adds an item to the end.
  • pop() — removes the last item.
  • shift() — removes the first item.
  • unshift() — adds an item to the beginning.
  • slice() — returns part of an array.
  • splice() — adds/removes array elements.

13. Advanced Array Methods

map()

map Example
let numbers = [10,20,30,40];

let result = numbers.map(number => number * 2);

console.log(result);

filter()

filter Example
let numbers = [10,15,20,25,30];

let result = numbers.filter(number => number >= 20);

console.log(result);

reduce()

reduce Example
let numbers = [10,20,30];

let total = numbers.reduce(
    (sum, number) => sum + number,
    0
);

console.log(total);

14. JavaScript Objects

Objects store related data using key-value pairs.

Object Example
let student = {

    name: "Ali",
    age: 20,
    course: "Web Development",

    introduce: function(){

        return "Hello " + this.name;

    }

};

console.log(student.name);

console.log(student.introduce());

15. Object Methods

Object.keys / values / entries
let student = {
    name: "Ali",
    age: 20,
    course: "JavaScript"
};

console.log(Object.keys(student));

console.log(Object.values(student));

console.log(Object.entries(student));

16. Date and Time

Date Example
let today = new Date();

console.log(today);

console.log(today.getFullYear());

console.log(today.getMonth());

console.log(today.getDate());

console.log(today.getHours());

console.log(today.getMinutes());

17. JavaScript Events

Events occur when users interact with a webpage. Examples include clicking, typing, submitting forms and moving the mouse.

Event Listener
<button id="btn">Click Me</button>

<script>

document
    .getElementById("btn")
    .addEventListener("click", function(){

        alert("Button clicked!");

    });

</script>

18. DOM — Document Object Model

The DOM represents an HTML document as objects that JavaScript can access and modify.

getElementById()

DOM Example
<h1 id="heading">Old Heading</h1>

<script>

document.getElementById("heading").innerHTML =
    "New Heading";

</script>

querySelector()

querySelector Example
const title = document.querySelector("h1");

title.style.color = "cyan";

Creating an Element

Create Element
let paragraph = document.createElement("p");

paragraph.textContent = "Hello JavaScript";

document.body.appendChild(paragraph);

19. Forms and Validation

JavaScript can validate user input before sending data to a server.

Form Validation
<form id="myForm">

    <input type="text" id="name"
           placeholder="Enter your name">

    <button type="submit">
        Submit
    </button>

</form>

<script>

document.getElementById("myForm")
.addEventListener("submit", function(event){

    event.preventDefault();

    let name =
        document.getElementById("name").value.trim();

    if(name === ""){

        alert("Please enter your name");

    }else{

        alert("Form submitted successfully");

    }

});

</script>

20. Error Handling

Error handling helps applications respond gracefully when something goes wrong.

try / catch
try {

    let result = unknownVariable + 10;

} catch(error) {

    console.log("An error occurred:");

    console.log(error.message);

} finally {

    console.log("Finished");

}

21. JavaScript Scope

Scope determines where a variable can be accessed.

Block Scope

Scope Example
{

    let message = "Hello";

    console.log(message);

}

// message is not available here.

22. JavaScript Hoisting

Hoisting describes JavaScript's handling of certain declarations during the creation of an execution context.

Function Hoisting
sayHello();

function sayHello(){

    console.log("Hello!");

}
Do not rely on hoisting to write confusing code. Declare variables and functions before using them whenever practical.

23. JavaScript Closures

A closure occurs when a function retains access to variables from its surrounding lexical environment.

Closure Example
function counter(){

    let count = 0;

    return function(){

        count++;

        return count;

    };

}

let myCounter = counter();

console.log(myCounter());
console.log(myCounter());
console.log(myCounter());

24. The this Keyword

The meaning of this depends on how a function is called. Arrow functions handle this differently because they do not create their own this binding.

Object this Example
const student = {

    name: "Ali",

    introduce(){

        console.log("My name is " + this.name);

    }

};

student.introduce();

25. Object-Oriented JavaScript

JavaScript supports object-oriented programming through objects, classes, prototypes and inheritance.

Class Example

JavaScript Class
class Student {

    constructor(name, age){

        this.name = name;
        this.age = age;

    }

    introduce(){

        return `My name is ${this.name}`;

    }

}

let student = new Student("Ali", 20);

console.log(student.introduce());

26. Destructuring

Object Destructuring

Destructuring Example
const student = {

    name: "Ali",
    age: 20

};

const {name, age} = student;

console.log(name);
console.log(age);

Array Destructuring

Array Destructuring
const colors = ["red", "green", "blue"];

const [first, second, third] = colors;

console.log(first);
console.log(second);
console.log(third);

27. Spread and Rest Operators

Spread Operator

Spread Example
let first = [1,2,3];

let second = [...first,4,5];

console.log(second);

Rest Parameter

Rest Example
function sum(...numbers){

    return numbers.reduce(
        (total, number) => total + number,
        0
    );

}

console.log(sum(10,20,30));

28. JavaScript Modules

Modules allow large applications to divide JavaScript code into reusable files.

Export

math.js
export function add(a,b){

    return a + b;

}

Import

app.js
import { add } from "./math.js";

console.log(add(10,20));

29. Asynchronous JavaScript

Asynchronous programming allows JavaScript applications to handle operations such as timers and network requests without blocking the entire user interface.

setTimeout Example
console.log("Start");

setTimeout(function(){

    console.log("This runs later");

}, 2000);

console.log("End");

30. JavaScript Promises

A Promise represents the eventual completion or failure of an asynchronous operation.

Promise Example
const promise = new Promise(function(resolve, reject){

    let success = true;

    if(success){

        resolve("Operation successful");

    }else{

        reject("Operation failed");

    }

});

promise
.then(result => console.log(result))
.catch(error => console.log(error));

31. Async and Await

The async and await syntax provides a convenient way to work with Promises.

Async/Await Example
async function getData(){

    try{

        const response =
            await fetch("https://jsonplaceholder.typicode.com/users");

        const data =
            await response.json();

        console.log(data);

    }catch(error){

        console.log(error);

    }

}

getData();

32. Fetch API

The Fetch API allows JavaScript to make HTTP requests.

GET Request

Fetch Example
fetch("https://jsonplaceholder.typicode.com/users")

.then(response => response.json())

.then(data => {

    console.log(data);

})

.catch(error => {

    console.log(error);

});

33. JSON

JSON is commonly used for exchanging structured data between applications.

JSON.stringify()

JSON.stringify
let student = {

    name: "Ali",
    age: 20

};

let jsonData =
    JSON.stringify(student);

console.log(jsonData);

JSON.parse()

JSON.parse
let jsonData =
    '{"name":"Ali","age":20}';

let student =
    JSON.parse(jsonData);

console.log(student.name);

34. Local Storage

Local Storage allows a browser to store string data that persists across browser sessions for the same origin.

localStorage Example
localStorage.setItem(
    "username",
    "Kamran"
);

let username =
    localStorage.getItem("username");

console.log(username);

localStorage.removeItem("username");

35. Regular Expressions

Regular expressions are patterns used to search, match and validate text.

Regex Example
let pattern = /^[A-Za-z]+$/;

console.log(
    pattern.test("Kamran")
);

console.log(
    pattern.test("Kamran123")
);

36. Browser APIs

Browsers provide APIs that allow JavaScript applications to interact with browser features.

  • Window API
  • Location API
  • History API
  • Navigator API
  • Clipboard API
  • Geolocation API
  • Web Storage API
  • Timers
Location Example
console.log(window.location.href);

37. Event Propagation

DOM events can propagate through the document using bubbling and capturing phases. Event delegation can be used to efficiently handle events from multiple child elements.

Event Delegation
document
.getElementById("list")
.addEventListener("click", function(event){

    if(event.target.matches("li")){

        console.log(event.target.textContent);

    }

});

38. Advanced Functions

Callback Function

Callback Example
function processUser(name, callback){

    console.log("User: " + name);

    callback();

}

processUser("Ali", function(){

    console.log("Finished");

});

Higher-Order Function

A higher-order function takes a function as an argument, returns a function, or both.

39. JavaScript Performance

Performance becomes increasingly important as applications become larger.

  • Avoid unnecessary DOM operations.
  • Use efficient loops and array operations.
  • Debounce frequently triggered events such as search input.
  • Throttle events such as scrolling when appropriate.
  • Load scripts efficiently.
  • Avoid unnecessary memory retention.
  • Split large applications into manageable modules.

Debouncing Concept

Debounce Example
function debounce(callback, delay){

    let timer;

    return function(){

        clearTimeout(timer);

        timer = setTimeout(
            callback,
            delay
        );

    };

}

40. JavaScript Debugging

Browser developer tools are essential for finding JavaScript problems.

  • Console
  • Sources
  • Breakpoints
  • Network
  • Elements
  • Application
Debugger Example
let price = 500;
let quantity = 2;

debugger;

let total = price * quantity;

console.log(total);

41. Modern JavaScript ES6+

Modern JavaScript includes many features that make code easier to write, read and maintain.

let & const

Block-scoped variable declarations.

Arrow Functions

Shorter function syntax.

Template Literals

Convenient string interpolation.

Destructuring

Extract values from arrays and objects.

Spread / Rest

Work conveniently with collections and function arguments.

Modules

Organize applications into reusable files.

42. JavaScript Security Basics

Client-side JavaScript should never be treated as a replacement for server-side security.

  • Validate input on the server as well as the client.
  • Avoid unsafe HTML insertion when possible.
  • Be careful with user-generated content.
  • Do not expose secret API keys in frontend JavaScript.
  • Avoid using eval() for ordinary application logic.
  • Use HTTPS for production applications.
Important: Client-side validation improves user experience, but sensitive validation and authorization must also be enforced on the server.

43. Working With APIs

APIs allow applications to exchange data with external or backend services. A common architecture is a frontend application communicating with a REST API.

CRUD Operations

  • Create — POST
  • Read — GET
  • Update — PUT / PATCH
  • Delete — DELETE
POST Example
fetch("/api/students", {

    method: "POST",

    headers: {
        "Content-Type": "application/json"
    },

    body: JSON.stringify({
        name: "Ali",
        age: 20
    })

})
.then(response => response.json())
.then(data => console.log(data));

44. JavaScript Frameworks and Libraries

After learning core JavaScript, developers can explore tools and frameworks for building larger applications.

React

A popular library for building user interfaces.

Vue

A progressive framework for building web interfaces.

Angular

A comprehensive framework for application development.

Node.js

A JavaScript runtime commonly used for server-side development.

Learn core JavaScript first. Understanding variables, functions, objects, arrays, DOM, events, asynchronous programming and modules will make learning frameworks much easier.

45. JavaScript Projects

The best way to improve programming skills is to build projects. Start small and gradually increase the complexity.

PROJECT 01

Digital Clock

Practice Date objects, DOM manipulation and timers.

PROJECT 02

Calculator

Practice operators, functions, events and DOM manipulation.

PROJECT 03

To-Do List

Practice arrays, objects, DOM and localStorage.

PROJECT 04

Quiz Application

Practice arrays, conditions, score calculation and events.

PROJECT 05

Expense Tracker

Practice forms, arrays, localStorage and data calculations.

PROJECT 06

Weather App

Practice Fetch API, async/await and API data.

PROJECT 07

Shopping Cart

Practice products, arrays, objects, DOM and calculations.

PROJECT 08

Student Result System

Practice forms, validation, objects and dynamic tables.

PROJECT 09

Portfolio Builder

Practice forms, DOM manipulation and localStorage.

PROJECT 10

API Dashboard

Practice Fetch API, JSON, asynchronous JavaScript and dynamic UI.

Learn. Build. Earn.

Don't stop after reading the tutorial. Build projects, create a portfolio, solve real problems and continuously improve your JavaScript skills.

🚀 Join Kamran Anjum Community

46. JavaScript FAQ

JavaScript is a programming language widely used to create interactive and dynamic web experiences.
JavaScript can be learned gradually. Start with variables, data types, conditions, loops and functions before moving to DOM, asynchronous programming and advanced concepts.
You can learn JavaScript independently, but understanding HTML and CSS first makes frontend JavaScript development much easier.
Start with a calculator, to-do list or quiz application. Then move to projects involving APIs, authentication, dashboards, shopping carts and complete web applications.
Yes. A strong understanding of JavaScript fundamentals makes React and other JavaScript tools much easier to understand.