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.
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
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
<button onclick="alert('Hello JavaScript!')">
Click Me
</button>
Internal JavaScript
<script>
console.log("Internal JavaScript");
</script>
External JavaScript
<script src="script.js"></script>
3. JavaScript Syntax
Syntax means the rules used to write JavaScript code. JavaScript statements normally perform an operation or instruction.
Comments
// 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
let name = "Kamran";
name = "Ahmed";
console.log(name);
const
const country = "Pakistan";
console.log(country);
5. JavaScript Data Types
JavaScript supports primitive and object data types. Common primitive types include string, number, boolean, undefined, null, bigint and symbol.
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
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
=, +=, -=, *=, /=
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.
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
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
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.
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
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(let i = 1; i <= 5; i++){
console.log(i);
}
while Loop
let i = 1;
while(i <= 5){
console.log(i);
i++;
}
break and 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 add(a, b){
return a + b;
}
let result = add(10, 20);
console.log(result);
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.
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()
let numbers = [10,20,30,40];
let result = numbers.map(number => number * 2);
console.log(result);
filter()
let numbers = [10,15,20,25,30];
let result = numbers.filter(number => number >= 20);
console.log(result);
reduce()
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.
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
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
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.
<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()
<h1 id="heading">Old Heading</h1>
<script>
document.getElementById("heading").innerHTML =
"New Heading";
</script>
querySelector()
const title = document.querySelector("h1");
title.style.color = "cyan";
Creating an 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 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 {
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
{
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.
sayHello();
function sayHello(){
console.log("Hello!");
}
23. JavaScript Closures
A closure occurs when a function retains access to variables from its surrounding lexical environment.
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.
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
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
const student = {
name: "Ali",
age: 20
};
const {name, age} = student;
console.log(name);
console.log(age);
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
let first = [1,2,3];
let second = [...first,4,5];
console.log(second);
Rest Parameter
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
export function add(a,b){
return a + b;
}
Import
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.
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.
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 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("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()
let student = {
name: "Ali",
age: 20
};
let jsonData =
JSON.stringify(student);
console.log(jsonData);
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.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.
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
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.
document
.getElementById("list")
.addEventListener("click", function(event){
if(event.target.matches("li")){
console.log(event.target.textContent);
}
});
38. Advanced Functions
Callback Function
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
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
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.
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
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.
45. JavaScript Projects
The best way to improve programming skills is to build projects. Start small and gradually increase the complexity.
Digital Clock
Practice Date objects, DOM manipulation and timers.
Calculator
Practice operators, functions, events and DOM manipulation.
To-Do List
Practice arrays, objects, DOM and localStorage.
Quiz Application
Practice arrays, conditions, score calculation and events.
Expense Tracker
Practice forms, arrays, localStorage and data calculations.
Weather App
Practice Fetch API, async/await and API data.
Shopping Cart
Practice products, arrays, objects, DOM and calculations.
Student Result System
Practice forms, validation, objects and dynamic tables.
Portfolio Builder
Practice forms, DOM manipulation and localStorage.
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