java script
java script
👉 JavaScript is a language that tells the web page what to do when something happens — like a
click, typing, or moving the mouse.
You want the page to say "Hello" when you click a button ✅
You want to hide or show something ✅
You want to get what someone typed ✅
💡 Real-Life Example:
🧱 HTML only:
<h1>Welcome</h1>
<button>Click Me</button>
🧱 With JavaScript:
<h1 id="text">Welcome</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("text").textContent = "Hello Hassan!";
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>My First JS</title>
</head>
<body>
<h1 id="title">Welcome</h1>
<script>
function sayHello() {
document.getElementById("title").textContent = "Hello Hassan!";
}
</script>
</body>
</html>
🧠 Remember This:
HTML = structure
JavaScript = actions
You write JavaScript in <script>...</script>
Use id="..." in HTML to connect with JavaScript
Use getElementById("...") in JS to control something
A heading (<h1>)
A button that says “Click Me”
When clicked, the heading changes to “You clicked the button!”
Want me to give you that code to copy and try? Or do you want to try yourself?
Perfect, Hassan! Let’s now move to the next topic in JavaScript for web:
🧱 Folder Structure:
project-folder/
├── index.html ← your HTML page
├── script.js ← your JavaScript file
📄 Step 1: index.html
<!DOCTYPE html>
<html>
<head>
<title>Input Example</title>
</head>
<body>
<h1 id="greeting">Hello!</h1>
</body>
</html>
📄 Step 2: script.js
function showName() {
let name = document.getElementById("nameInput").value;
🔍 Easy Explanation
Code What It Does
<input> Lets user type their name
.value Gets what user typed
.textContent Changes the heading text
+ name + Adds the user's name into the message
onclick="showName()" Runs the function when the button is clicked
📘 Like Saying:
"When the button is clicked, read the name from the input box and update the heading to say
Hello, [name]!"
🧠 Example
You type: Hassan
You click: Greet Me
It shows: Hello, Hassan!
Let me know!
Perfect, Hassan! Since you want to move forward in JavaScript, we’ll now go to the next
important topic:
✅ JavaScript Events (after input and output)
Instead of using onclick="..." in HTML, we now learn how to handle events using
JavaScript code (better practice).
📄 JavaScript
document.getElementById("clickBtn").addEventListener("click", function() {
document.getElementById("output").textContent = "Button was clicked!";
});
📄 JavaScript
document.getElementById("nameInput").addEventListener("keydown", function() {
document.getElementById("message").textContent = "You are typing...";
});
✅ Try It:
Would you like:
Let me know what you want next — I’ll keep it super simple!
Perfect Hassan! Let’s move forward in JavaScript — step by step, simple and clear.
<h2 id="message"></h2>
<script src="script.js"></script>
script.js
<ul id="list"></ul>
<script src="script.js"></script>
script.js
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
✅ Where You’ll Use This in Web:
Example Use If / Loops
Show message based on age if-else
Show list of hobbies for loop
Hide form if input is empty if
Repeat cards or items loop
Let me know what we should do next — I’ll keep it easy and external!
Excellent clarification, Hassan! You want to know how to use Arrays in Web Projects, not just
console practice — let me explain this in very simple, web-based examples:
✔ Lists of hobbies
✔ Lists of products
✔ Names of friends
✔ Anything that repeats
🔧 JavaScript:
let hobbies = ["Coding", "Gaming", "Reading"];
JS:
function showFriends() {
let list = document.getElementById("friendList");
list.innerHTML = ""; // Clear old list
✅ Want to Practice?
Would you like:
Perfect Hassan! Let’s move ahead in JavaScript for Web — next logical topic after Arrays is:
<h3>Your Hobbies:</h3>
<ul id="hobbyList"></ul>
JavaScript:
function addHobby() {
let hobby = document.getElementById("hobbyInput").value;
let list = document.getElementById("hobbyList");
Perfect Hassan! Let’s move to Functions in JavaScript, step by step, easy and clear for Web
Development:
✅ Functions in JavaScript (For Web Projects)
🎯 What is a Function?
✔ A block of code you write once, but can run many times
✔ Makes your code clean, reusable, and organized
greetUser();
JavaScript:
function greet() {
let name = document.getElementById("nameInput").value;
alert("Hello " + name + "!");
}
<ul id="hobbyList"></ul>
<p>Total Hobbies: <span id="count"></span></p>
JS:
let hobbies = [];
function addHobby() {
let hobby = document.getElementById("hobbyInput").value;
if (hobby === "") {
alert("Please enter a hobby!");
return;
}
hobbies.push(hobby);
showHobbies();
}
function removeHobby() {
hobbies.pop();
showHobbies();
}
function showHobbies() {
let list = document.getElementById("hobbyList");
let count = document.getElementById("count");
list.innerHTML = "";
Perfect Hassan! Let’s move ahead to the next beginner-friendly topic for Web Development:
🎯 What is a String?
✔ A string is simply text inside quotes
✔ It can be letters, numbers, spaces, symbols
Examples:
<p id="greeting"></p>
JS:
function showGreeting() {
let name = document.getElementById("nameInput").value.trim();
if (name.length === 0) {
alert("Please enter your name!");
return;
}
✅ Next Step:
✔ Do practice task with String methods?
✔ Or move to next topic: DOM Styling with JS (change colors, size)?
Perfect Hassan! Let’s move ahead to the next topic — very useful for Web Development:
JS:
function changeColor() {
document.getElementById("title").style.color = "red";
}
border
Add border around element.style.border = "2px solid
element black";
function hideText() {
document.getElementById("message").style.display = "none";
}
function showText() {
document.getElementById("message").style.display = "block";
}
✅ Next Step:
✔ Want to practice styling with a small task?
✔ Or move to Forms Validation basics (check user input properly)?
Perfect Hassan! Let’s move ahead to the next essential Web Development topic:
JS:
function validateForm() {
let name = document.getElementById("nameInput").value.trim();
✅ Next Step:
✔ Want small project with multiple validations?
✔ Or move to final: Combine JS + HTML + CSS mini project?
Tell me — your choice, I’ll guide easy and step by step! 🚀Excellent Hassan! Let’s start learning
JSON (JavaScript Object Notation) step by step, in very simple language — no confusion.
✅ What is JSON?
✔ JSON = Format to store and send data
✔ Looks like an object but used for communication between systems
✔ Most websites, apps, and APIs use JSON to send/receive data
{
"name": "Hassan",
"age": 20
}
let person = {
name: "Hassan",
age: 20
};
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
});
Perfect Hassan! Here's a complete, deep, clear explanation of both JSON and API from start to
next-level — no confusion, explained step by step in simple words:
JSON Example:
{
"name": "Hassan",
"age": 20,
"hobbies": ["Coding", "Reading", "Gaming"]
}
{
"name": "Ali",
"age": 22
}
let person = {
name: "Ali",
age: 22
};
✅ 2️⃣JSON Methods in JavaScript
✔ JSON.parse()
✔ JSON.stringify()
Access in JS:
let person = {
name: "Hassan",
address: {
city: "Lahore",
country: "Pakistan"
},
hobbies: ["Coding", "Reading"]
};
console.log(person.address.city); // Lahore
console.log(person.hobbies[0]); // Coding
Excellent Hassan! Let me explain JSON, JSON.parse(), and JSON.stringify() very simply, step
by step — like a beginner but with professional understanding:
✅ What is JSON?
JSON = JavaScript Object Notation
✅ What is JSON.stringify()?
Converts a JavaScript Object → JSON Text String
Example:
Example:
✅ Quick Recap
Function Meaning
JSON.stringify() Object → JSON text string
JSON.parse() JSON text string → Usable JS Object
Example:
✔ You visit weather website
✔ It calls weather API in the background
✔ API sends JSON like:
{
"city": "Lahore",
"temperature": "35°C",
"condition": "Sunny"
}
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => {
console.log(data.name);
});
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => res.json())
.then(data => {
document.getElementById("status").textContent = "Hello " + data.name;
})
.catch(() => {
document.getElementById("status").textContent = "Error loading data";
});
Perfect Hassan! Let me explain API deeply but in very simple language — beginner-friendly,
professional style. You’ll fully understand!
✅ What is an API?
API = Application Programming Interface
➡️It's a way for different apps, websites, or servers to "talk" to each other.
➡️You send a request → API gives back information (usually in JSON).
🎯 Easy Real-Life Example
Think of an API like a Waiter at a restaurant:
In Websites:
➡️Link: https://dog.ceo/api/breeds/image/random
{
"message": "https://images.dog.ceo/breeds/hound-afghan/n02088094_1007.jpg",
"status": "success"
}
<script>
function getDog() {
fetch("https://dog.ceo/api/breeds/image/random")
.then(res => res.json())
.then(data => {
document.getElementById("dogPic").src = data.message;
});
}
</script>
✅ Summary
✔ API = A system that gives you data on request
✔ You can fetch API using JS
✔ API gives JSON data
✔ You show that data using DOM methods
Excellent Hassan! Let's move to the next topic after API, which is very important for modern
JavaScript:
fetch("https://api.example.com")
.then(res => res.json())
.then(data => console.log(data));
<script>
async function getDog() {
let res = await fetch("https://dog.ceo/api/breeds/image/random");
let data = await res.json();
document.getElementById("dogPic").src = data.message;
}
</script>
Excellent Hassan! Let’s move to the next beginner-friendly important topic: Promises, which
connects with API and Async concepts.
🎯 What is a Promise?
➡️A Promise is like a future "guarantee" that your code will:
✔ API calls
✔ Loading files
✔ Any delayed task
if (success) {
resolve("Task completed!");
} else {
reject("Task failed.");
}
});
promise.then(function(message) {
console.log(message); // Runs if successful
}).catch(function(error) {
console.log(error); // Runs if failed
});
✅ Quick Recap
✔ Promise = Future result (success or fail)
✔ resolve() = Success
✔ reject() = Failure
✔ .then() handles success
✔ .catch() handles errors
Perfect Hassan! Let’s do a Small Project using Promises + API, super easy, clear for practice.
<script>
function getJoke() {
fetch("https://official-joke-api.appspot.com/random_joke")
.then(res => res.json()) // Convert to JSON
.then(data => {
document.getElementById("jokeText").textContent = data.setup + " - " +
data.punchline;
})
.catch(err => {
document.getElementById("jokeText").textContent = "Failed to fetch
joke!";
console.log(err);
});
}
</script>
</body>
</html>
✅ Project Breakdown
✔ fetch() returns a Promise
✔ .then(res => res.json()) converts response
✔ .then(data => show joke) displays joke
✔ .catch(err) handles errors if API fails
✔ .setItem() → Save
✔ .getItem() → Retrieve
✔ .removeItem() → Delete
<script>
function saveName() {
let name = document.getElementById("nameInput").value;
localStorage.setItem("username", name);
showGreeting();
}
function showGreeting() {
let name = localStorage.getItem("username");
if (name) {
document.getElementById("greeting").textContent = "Welcome back, " + name
+ "!";
}
}
✅ Quick Recap
✔ Data stays even after refresh
✔ Local Storage only stores strings
✔ You can store JSON using JSON.stringify()