0% found this document useful (0 votes)
2 views39 pages

java script

JavaScript (JS) is a programming language that enables interactive features on web pages, such as responding to user actions like clicks and input. The document provides examples of using JS to manipulate HTML elements, handle user input, and utilize events, functions, and arrays for dynamic web development. It emphasizes best practices, such as separating HTML and JS, and introduces various JS concepts through practical examples and tasks for the reader.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

java script

JavaScript (JS) is a programming language that enables interactive features on web pages, such as responding to user actions like clicks and input. The document provides examples of using JS to manipulate HTML elements, handle user input, and utilize events, functions, and arrays for dynamic web development. It emphasizes best practices, such as separating HTML and JS, and introduces various JS concepts through practical examples and tasks for the reader.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

🌍 What is JavaScript (JS)?

👉 JavaScript is a language that tells the web page what to do when something happens — like a
click, typing, or moving the mouse.

🧠 You use JavaScript when:

 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>

📌 Nothing happens when you click — it’s just a button.

🧱 With JavaScript:
<h1 id="text">Welcome</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("text").textContent = "Hello Hassan!";
}
</script>

✅ Now when you click the button → The text changes!

🧠 What This Code Does (Simple Words):


Code What it does
id="text" Gives a name to the <h1> so JS can find it
onclick="changeText()" When button is clicked, it runs the changeText function
function changeText() A group of actions (called function)
document.getElementById("text") Find the element with id "text"
.textContent = "Hello Hassan!" Change the text inside it

🧪 Try This Full Code


Copy this and paste into your browser (just save as index.html):

<!DOCTYPE html>
<html>
<head>
<title>My First JS</title>
</head>
<body>

<h1 id="title">Welcome</h1>

<button onclick="sayHello()">Click Me</button>

<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

✅ Task for You:

Make a page with:

 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?

Let me know, and we’ll move slowly, step by step 🤝

Perfect, Hassan! Let’s now move to the next topic in JavaScript for web:

✅ Getting Input from the User (With


External JavaScript)
We will now learn:

 How to take text input from the user (like name)


 How to show that name back on the page
 Using external JavaScript file (best practice)

🧱 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>

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


<button onclick="showName()">Greet Me</button>

<!-- Link to external JS file -->


<script src="script.js"></script>

</body>
</html>

📄 Step 2: script.js
function showName() {
let name = document.getElementById("nameInput").value;

document.getElementById("greeting").textContent = "Hello, " + name + "!";


}

🔍 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!

✅ Want a mini project next (like a name greeter)?


Or move to JavaScript and CSS: changing color, size, style with JS?

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)

🎯 What Are Events?


An event is something that happens in the browser — like:

Event Type Example


click When a user clicks a button
mouseover When the mouse moves over something
keydown When the user types on the keyboard
submit When a form is submitted
load When the page fully loads

🧠 Why Use Events?


Events let JavaScript respond to what the user does.

Instead of using onclick="..." in HTML, we now learn how to handle events using
JavaScript code (better practice).

🧱 Example 1: Click Event Using addEventListener


📄 HTML
<button id="clickBtn">Click Me</button>
<p id="output"></p>

📄 JavaScript
document.getElementById("clickBtn").addEventListener("click", function() {
document.getElementById("output").textContent = "Button was clicked!";
});

🧱 Example 2: Key Press Event


📄 HTML
<input type="text" id="nameInput" placeholder="Type your name">
<p id="message"></p>

📄 JavaScript
document.getElementById("nameInput").addEventListener("keydown", function() {
document.getElementById("message").textContent = "You are typing...";
});

💡 Why Use addEventListener() Instead of onclick?


onclick in HTML addEventListener() in JS
Mixed with HTML Keeps HTML clean
Can only assign one Can assign many listeners
Not reusable Reusable & organized

✅ Try It:
Would you like:

 🎯 A task to practice click and keydown?


 🆕 Or move to JavaScript Conditions and Loops (like if, else, for)?

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.

✅ Next Important Topic: Conditions and


Loops
These help your webpage:

✔ Make decisions → Like: “If name is empty, show a warning”


✔ Repeat actions → Like: “Show list of 5 hobbies”
🎯 1. Conditions (If-Else)
📄 Example: Simple Age Check (External JS)
index.html

<h2 id="message"></h2>
<script src="script.js"></script>

script.js

let age = 18;

if (age >= 18) {


document.getElementById("message").textContent = "You are an adult.";
} else {
document.getElementById("message").textContent = "You are a minor.";
}

✔ If age is 18 or more → Show "You are an adult"


✔ Else → Show "You are a minor"

🎯 2. Loops (For Loop)


📄 Example: Show numbers 1 to 5
index.html

<ul id="list"></ul>
<script src="script.js"></script>

script.js

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


document.getElementById("list").innerHTML += `<li>Number: ${i}</li>`;
}

✔ It repeats 5 times and shows:

 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

💡 Want a small task using:


 if-else to check name input?
 loop to print hobbies or numbers?
 Or both together in a mini project?

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:

✅ How Arrays are Used in Real Web Pages


Arrays help store and display multiple values on your website, like:

✔ Lists of hobbies
✔ Lists of products
✔ Names of friends
✔ Anything that repeats

🎯 Simple Example — Showing Array on Web Page


🔧 HTML:
<h2>My Hobbies:</h2>
<ul id="hobbyList"></ul>

🔧 JavaScript:
let hobbies = ["Coding", "Gaming", "Reading"];

let list = document.getElementById("hobbyList");

// Loop to show all hobbies inside <ul>


for (let i = 0; i < hobbies.length; i++) {
list.innerHTML += `<li>${hobbies[i]}</li>`;
}

✔ Array stores multiple hobbies


✔ Loop repeats for each hobby
✔ innerHTML adds each hobby inside <li>

🎯 Where Arrays Are Useful in Web:


Web Situation Example Using Array
Show list of hobbies As shown above
Product listing Store product names in array, loop to show them
User types multiple skills Add each skill to array, show them below
Comments section Store all comments in array

✅ More Practical Example:


<h2>Friends:</h2>
<ul id="friendList"></ul>
<button onclick="showFriends()">Show Friends</button>

JS:

let friends = ["Ali", "Sara", "Hassan"];

function showFriends() {
let list = document.getElementById("friendList");
list.innerHTML = ""; // Clear old list

for (let i = 0; i < friends.length; i++) {


list.innerHTML += `<li>${friends[i]}</li>`;
}
}

✔ Click button → Shows all friends on page


✔ Array holds friend names
✅ Why Arrays Help in Web Projects:
✔ Store and manage multiple values easily
✔ Loop through them to show results
✔ Avoid creating too many separate variables

✅ Want to Practice?
Would you like:

✔ A small web task: show hobbies or products with Arrays?


✔ Or take input from user, add to array, then show it live?

Tell me — step by step, easy project ready for you! 🚀

Perfect Hassan! Let’s move ahead in JavaScript for Web — next logical topic after Arrays is:

✅ Array with User Input (Interactive Web


Example)

🎯 What You’ll Learn Now:


✔ Take input from user
✔ Add that input to Array
✔ Show updated list on web page

🔧 Real Web Example:


HTML:

<input type="text" id="hobbyInput" placeholder="Enter your hobby">


<button onclick="addHobby()">Add Hobby</button>

<h3>Your Hobbies:</h3>
<ul id="hobbyList"></ul>

JavaScript:

let hobbies = []; // Start with empty array

function addHobby() {
let hobby = document.getElementById("hobbyInput").value;
let list = document.getElementById("hobbyList");

if (hobby === "") {


alert("Please enter a hobby!");
return;
}

hobbies.push(hobby); // Add to array


list.innerHTML = ""; // Clear old list

// Show updated hobbies


for (let i = 0; i < hobbies.length; i++) {
list.innerHTML += `<li>${hobbies[i]}</li>`;
}

document.getElementById("hobbyInput").value = ""; // Clear input


}

✅ Why This is Powerful for Web:


✔ You interactively build a list
✔ Array stores all inputs
✔ Page updates every time user adds new hobby

✅ Want to Combine with More?


✔ I can show how to remove items from list
✔ Or how to use arrays with different input types
✔ Or move to next topic: Functions in JS for web

Tell me — step by step, we’ll make it easy! 🚀

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

🎯 Simple Function Example:


function greetUser() {
alert("Welcome to my website!");
}

To run the function:

greetUser();

✔ function = keyword to create function


✔ greetUser = function name
✔ { ... } = code to run when called

🎯 Function with Parameters (Pass Data):


function greetUser(name) {
alert("Hello " + name + "!");
}

greetUser("Hassan"); // Shows: Hello Hassan!

✔ You pass a value inside ()


✔ Function uses that value

🎯 Real Web Example:


HTML:

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


<button onclick="greet()">Greet Me</button>

JavaScript:

function greet() {
let name = document.getElementById("nameInput").value;
alert("Hello " + name + "!");
}

✔ User types name


✔ Click button → Function runs
✔ Shows greeting with input

✅ Why Functions Help:


Without Function With Function
Code repeats Code is reusable
Hard to manage Easy to update one place
Messy for big projects Clean, readable code

✅ Want to Practice Now?


✔ Small task with Functions + Input?
✔ Or combine Functions with Arrays (next level)?

Tell me — I’ll explain next step easy for you! 🚀

Perfect Hassan! Let’s move ahead to the next logical topic:

✅ Array Methods in JavaScript (Simple for


Web Projects)

🎯 What Are Array Methods?


✔ Special built-in tools for working with Arrays
✔ Help add, remove, check, or update array values

✅ Common Array Methods You Need Now:

1️⃣.push() → Add to End


let hobbies = ["Coding", "Gaming"];
hobbies.push("Reading"); // Adds "Reading"
console.log(hobbies); // ["Coding", "Gaming", "Reading"]

2️⃣.pop() → Remove Last Item


hobbies.pop();
console.log(hobbies); // ["Coding", "Gaming"]

3️⃣.length → Count Items


console.log(hobbies.length); // 2

4️⃣.includes() → Check If Value Exists


console.log(hobbies.includes("Coding")); // true
console.log(hobbies.includes("Dancing")); // false

✅ Simple Web Example with Array Methods


HTML:

<input type="text" id="hobbyInput" placeholder="Enter hobby">


<button onclick="addHobby()">Add Hobby</button>
<button onclick="removeHobby()">Remove Last Hobby</button>

<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 = "";

for (let i = 0; i < hobbies.length; i++) {


list.innerHTML += `<li>${hobbies[i]}</li>`;
}
count.textContent = hobbies.length;
}

Perfect Hassan! Let’s move ahead to the next beginner-friendly topic for Web Development:

✅ Strings in JavaScript (Handling Text


Easily)

🎯 What is a String?
✔ A string is simply text inside quotes
✔ It can be letters, numbers, spaces, symbols

Examples:

let name = "Hassan";


let message = "Welcome to my website!";
✅ Useful String Methods for Web:

1️⃣.length → Total Characters Count


let name = "Hassan";
console.log(name.length); // 6

2️⃣.toUpperCase() → Make Text UPPERCASE


console.log(name.toUpperCase()); // HASSAN

3️⃣.toLowerCase() → Make Text lowercase


console.log(name.toLowerCase()); // hassan

4️⃣.includes() → Check If Text Exists


let msg = "Hello World";
console.log(msg.includes("World")); // true

5️⃣.trim() → Remove Extra Spaces


let input = " Hello ";
console.log(input.trim()); // "Hello"

✅ Real Web Example: Clean User Input


HTML:

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


<button onclick="showGreeting()">Greet Me</button>

<p id="greeting"></p>

JS:

function showGreeting() {
let name = document.getElementById("nameInput").value.trim();
if (name.length === 0) {
alert("Please enter your name!");
return;
}

let message = "Welcome, " + name.toUpperCase() + "!";


document.getElementById("greeting").textContent = message;
}

✔ .trim() removes extra spaces


✔ .toUpperCase() makes name uppercase
✔ Shows greeting in a clean format

✅ Why Strings Are Important in Web:


✔ Handle user names, messages, titles, etc.
✔ Clean, format, or check text
✔ Combine with Arrays or Conditions

✅ Next Step:
✔ Do practice task with String methods?
✔ Or move to next topic: DOM Styling with JS (change colors, size)?

Tell me — step by step, I’ll explain easy for you! 🚀

Perfect Hassan! Let’s move ahead to the next topic — very useful for Web Development:

✅ DOM Styling with JavaScript (Change CSS


with JS)

🎯 What is DOM Styling?


✔ You can use JavaScript to change the style (color, size, background, etc.) of any element on
your webpage
✔ Allows interactive, dynamic designs without touching CSS file

✅ Example: Change Text Color with JS


HTML:

<h1 id="title">Welcome to My Page</h1>


<button onclick="changeColor()">Change Color</button>

JS:

function changeColor() {
document.getElementById("title").style.color = "red";
}

✔ .style.color changes the text color


✔ Runs when you click the button

✅ More Style Properties You Can Change:


Property What it Does Example
color Text color element.style.color = "blue";
element.style.backgroundColor =
backgroundColor Background color "yellow";
fontSize Text size element.style.fontSize = "24px";

display Show or hide element element.style.display = "none"; or


"block"

border
Add border around element.style.border = "2px solid
element black";

✅ Example: Hide and Show Element


HTML:

<p id="message">Hello World</p>


<button onclick="hideText()">Hide</button>
<button onclick="showText()">Show</button>
JS:

function hideText() {
document.getElementById("message").style.display = "none";
}

function showText() {
document.getElementById("message").style.display = "block";
}

✅ Why DOM Styling with JS is Useful:


✔ Make pages interactive
✔ Change colors, fonts, layouts on events
✔ Hide or show elements dynamically

✅ Next Step:
✔ Want to practice styling with a small task?
✔ Or move to Forms Validation basics (check user input properly)?

Tell me — easy step by step, your choice! 🚀

Perfect Hassan! Let’s move ahead to the next essential Web Development topic:

✅ Forms Validation in JavaScript (Check


User Input Correctly)

🎯 What is Forms Validation?


✔ Before accepting input, you check if it's valid:
➡️Is name filled?
➡️Is age a number?
➡️Is email correct format?
If wrong → Show warning
If correct → Continue the process

✅ Simple Example: Required Name Check


HTML:

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


<button onclick="validateForm()">Submit</button>
<p id="message"></p>

JS:

function validateForm() {
let name = document.getElementById("nameInput").value.trim();

if (name === "") {


document.getElementById("message").textContent = "Name is required!";
return;
}

document.getElementById("message").textContent = "Thank you, " + name;


}

✔ Checks if name is empty


✔ Shows message below input

✅ Common Validations for Web:


Check For Example Code
Empty Field if (value === "")
Minimum Length if (value.length < 3)
Age as Number if (isNaN(age))
Email Pattern Use .includes("@") (basic)

✅ Example: Check Age is a Number


function checkAge() {
let age = document.getElementById("ageInput").value;
if (isNaN(age) || age === "") {
alert("Please enter a valid age!");
return;
}

alert("Your age is " + age);


}

✅ Why Forms Validation is Important:


✔ Prevents empty or wrong data
✔ Improves user experience
✔ Required for real websites (login, signup, etc.)

✅ 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

🎯 1️⃣JSON Looks Like This


{
"name": "Hassan",
"age": 20,
"hobby": "Web Development"
}
✔ Data is inside { }
✔ Uses key-value pairs
✔ Keys are in double quotes
✔ Values can be text, number, list, etc.

🎯 2️⃣Difference: JSON vs JavaScript Object


✔ JSON (used to send data):

{
"name": "Hassan",
"age": 20
}

✔ JS Object (used in code):

let person = {
name: "Hassan",
age: 20
};

🎯 3️⃣How to Use JSON in JS


JSON String Example:
let jsonData = '{"name":"Hassan", "age":20}';

✔ JSON data is string format

Convert JSON to Object:


let obj = JSON.parse(jsonData);
console.log(obj.name); // Hassan

✔ JSON.parse() converts JSON string to usable JS object

Convert Object to JSON:


let student = {
name: "Ali",
age: 22
};

let jsonString = JSON.stringify(student);


console.log(jsonString);
// {"name":"Ali","age":22}

✔ JSON.stringify() converts JS object to JSON string

🎯 4️⃣Why We Use JSON


✔ When sending data to server
✔ When receiving data from API
✔ To store structured data

Example in real projects:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
});

✔ API sends data in JSON


✔ We parse it, use in website

✅ Quick Summary Table:


Concept Use
JSON Data format for sharing
JSON.parse() Convert JSON string to object
JSON.stringify() Convert object to JSON string

✅ Would You Like:


✔ Practice JSON conversion tasks?
✔ Mini project using JSON?
✔ Start learning API basics next?
Tell me — I’ll guide step by step, no confusion 🚀

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:

✅ 1️⃣What is JSON? (Deep Explanation)


JSON = JavaScript Object Notation

✔ Format to store and share data between websites, apps, servers


✔ Very popular for APIs, databases, mobile apps

JSON Example:

{
"name": "Hassan",
"age": 20,
"hobbies": ["Coding", "Reading", "Gaming"]
}

✔ Data stored as key-value pairs


✔ Keys always in double quotes
✔ Values can be string, number, array, or even another object

🎯 Difference Between JSON and JavaScript


Object
JSON (used to send/store data)

{
"name": "Ali",
"age": 22
}

JavaScript Object (used inside your JS code)

let person = {
name: "Ali",
age: 22
};
✅ 2️⃣JSON Methods in JavaScript
✔ JSON.parse()

Converts JSON string to usable JS Object:

let jsonString = '{"name": "Hassan", "age": 20}';


let obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Hassan

✔ JSON.stringify()

Converts JS Object to JSON string:

let user = { name: "Hassan", age: 20 };


let jsonData = JSON.stringify(user);
console.log(jsonData);
// Output: {"name":"Hassan","age":20}

✅ 3️⃣Nested JSON (Real-World Example)


{
"name": "Hassan",
"address": {
"city": "Lahore",
"country": "Pakistan"
},
"hobbies": ["Coding", "Reading"]
}

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

➡️It's a lightweight, standard format to store and send data


➡️Looks like key-value pairs inside {}
➡️Commonly used for sending data between website and server, or between apps

🎯 Example JSON Data


{
"name": "Hassan",
"age": 20,
"hobby": "Web Development"
}

✔ "name" = key (must be in quotes)


✔ "Hassan" = value (string, must be in quotes)
✔ Numbers like 20 don't need quotes

✅ What is JSON.stringify()?
Converts a JavaScript Object → JSON Text String

✔ When sending data to a server or storing it as plain text


✔ Makes the object readable as plain text

Example:

let person = { name: "Hassan", age: 20 };

let jsonString = JSON.stringify(person);

console.log(jsonString); // Output: {"name":"Hassan","age":20}

➡️Now jsonString is just plain text


✅ What is JSON.parse()?
Converts JSON Text String → JavaScript Object

✔ After receiving JSON from API or reading it from storage


✔ Makes the text usable as an object

Example:

let jsonText = '{"name":"Hassan","age":20}'; // JSON as text

let person = JSON.parse(jsonText); // Converts to object

console.log(person.name); // Output: Hassan

✅ Quick Recap
Function Meaning
JSON.stringify() Object → JSON text string
JSON.parse() JSON text string → Usable JS Object

✅ Simple Real Example


let data = { name: "Hassan", city: "Lahore" };

let textData = JSON.stringify(data); // Object to text

let usableData = JSON.parse(textData); // Text to object

console.log(usableData.name); // Output: Hassan

✅ Would You Like?


✔ Full webpage example to practice this?
✔ Combine with API example next?
✔ Small tasks to test your understanding?

Tell me — I'll guide step by step 🚀

✅ 4️⃣What is an API? (Deep Explanation)


✔ API = Application Programming Interface
✔ Allows websites or apps to communicate with each other
✔ Sends or receives data — often in JSON format

Example:
✔ You visit weather website
✔ It calls weather API in the background
✔ API sends JSON like:

{
"city": "Lahore",
"temperature": "35°C",
"condition": "Sunny"
}

Your webpage shows this info to user.

✅ 5️⃣How to Call API Using fetch()


Basic GET Request:

fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => {
console.log(data.name);
});

✔ fetch() → Calls the API


✔ .json() → Converts JSON to JS Object
✔ You use the data

✅ 6️⃣API with Dynamic Data (Change URL)


function getUser(userId) {
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(res => res.json())
.then(data => console.log(data.name));
}

getUser(2); // Shows User 2's name


✅ 7️⃣Error Handling with API
fetch("https://wrong-api-link.com")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log("API Error:", err));

✔ .catch() handles errors safely

✅ 8️⃣Showing Loading Message During API


document.getElementById("status").textContent = "Loading...";

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";
});

✅ 9️⃣API POST Request (Send Data to Server)


fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify({
title: "My Post",
body: "This is test content",
userId: 1
}),
headers: {
"Content-type": "application/json"
}
})
.then(res => res.json())
.then(data => console.log(data));

✔ Sends data to server


✔ Server responds with confirmation JSON

✅ 10️⃣Working with Complex JSON


fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => res.json())
.then(user => {
console.log(user.address.city);
});

✔ JSON can be nested


✔ You access inner values with dot notation

✅ Quick Summary Table


Concept Use
JSON.parse() Convert JSON string to Object
JSON.stringify() Convert Object to JSON string
fetch() Call API
.then() / .catch() Handle response or errors
Nested JSON JSON inside JSON
API POST Send data to API

✅ Would You Like Now?


✔ Mini project using JSON + API?
✔ Practice task step by step?
✔ Or I guide how to make small API-based application?

Tell me — I’ll help you build confidence with easy practice 🚀

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:

✔ You tell the waiter your order (Request)


✔ Waiter brings your food from the kitchen (Response)

In Websites:

✔ Your website sends a request to API


✔ API gives back data (like images, weather, news)
✔ Your website shows that data

✅ Types of APIs You See in Web


✔ Public APIs (Free to use, no account needed)
✔ Private APIs (Need login or key)
✔ Local APIs (On your own computer)

✅ Example Public API


Dog API: Gives random dog image

➡️Link: https://dog.ceo/api/breeds/image/random

If you open this in browser, you get JSON like:

{
"message": "https://images.dog.ceo/breeds/hound-afghan/n02088094_1007.jpg",
"status": "success"
}

✔ "message" = Dog image URL


✔ "status" = Shows request was successful

✅ How to Use API with JavaScript


fetch("https://dog.ceo/api/breeds/image/random")
.then(response => response.json()) // Convert to usable JSON
.then(data => {
console.log(data.message); // Show dog image link
});

✅ Terms You Must Know


Term Meaning
Request You ask the API for something
Response API gives you back data (usually JSON)
fetch() JS method to connect to API
.json() Converts API text to usable object

✅ Quick Full Example for Web Page


<button onclick="getDog()">Show Dog</button>
<img id="dogPic" width="200">

<script>
function getDog() {
fetch("https://dog.ceo/api/breeds/image/random")
.then(res => res.json())
.then(data => {
document.getElementById("dogPic").src = data.message;
});
}
</script>

✔ Click button → fetch API → show dog image

✅ 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

✅ Would You Like?


✔ Practice tasks using API?
✔ Combine JSON and API in a mini-project?
✔ Explanation of different types of API requests (POST, GET)?

Tell me — I'll guide next step clearly 🚀

Excellent Hassan! Let's move to the next topic after API, which is very important for modern
JavaScript:

✅ Next Topic: Async / Await

🎯 Why Learn Async/Await?


✔ Makes API calls easier to read
✔ Avoids messy .then() chains
✔ Used for writing clean, modern JS

✅ Understanding Async/Await (Simple Way)


➡️Normally, you use .then() to handle API:

fetch("https://api.example.com")
.then(res => res.json())
.then(data => console.log(data));

➡️With async and await, same thing looks clean:

async function getData() {


let res = await fetch("https://api.example.com");
let data = await res.json();
console.log(data);
}

✔ async makes function asynchronous


✔ await pauses code until fetch finishes
✔ No need for multiple .then()
✅ Mini Example: Dog Image with
Async/Await
<button onclick="getDog()">Get Dog</button>
<img id="dogPic" width="300">

<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>

✅ Why Use Async/Await?


✔ Easy to read
✔ Easy to debug
✔ Avoid callback hell
✔ Standard in modern JS

✅ Next Step for You


✔ Want practice tasks for Async/Await?
✔ Combine with API mini project?
✔ Or move to next advanced topics like Promises or JSON deep?

Tell me — I’ll guide you clearly, step by step 🚀

Excellent Hassan! Let’s move to the next beginner-friendly important topic: Promises, which
connects with API and Async concepts.

✅ Promises in JavaScript — Super Simple

🎯 What is a Promise?
➡️A Promise is like a future "guarantee" that your code will:

✔ Succeed (resolve) — gives result


✔ Fail (reject) — gives error

It handles things like:

✔ API calls
✔ Loading files
✔ Any delayed task

✅ Simple Promise Example


let promise = new Promise(function(resolve, reject) {
let success = true;

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
});

🎯 Where You Use Promises


✔ Behind the scenes, fetch() uses Promises
✔ You can create your own Promises
✔ Async/Await works with Promises

✅ Example with fetch (Promise style)


fetch("https://dog.ceo/api/breeds/image/random")
.then(res => res.json())
.then(data => console.log(data.message))
.catch(err => console.log("Error:", err));
✔ .then() = Promise successful
✔ .catch() = Promise failed

✅ Quick Recap
✔ Promise = Future result (success or fail)
✔ resolve() = Success
✔ reject() = Failure
✔ .then() handles success
✔ .catch() handles errors

✅ Would You Like?


✔ Practice Promise tasks?
✔ Small project using Promises?
✔ Or move to the next topic — JSON deep, Local Storage, or DOM events?

Tell me — I’ll guide step by step 🚀

Perfect Hassan! Let’s do a Small Project using Promises + API, super easy, clear for practice.

✅ Mini Project: Joke Generator with


Promises
✔ Get random joke from API
✔ Handle success with .then()
✔ Handle error with .catch()

🎯 Full Working Example


<!DOCTYPE html>
<html>
<head>
<title>Joke Generator</title>
<style>
body { font-family: Arial; text-align: center; margin-top: 50px; }
button { padding: 10px 20px; }
p { font-size: 20px; margin-top: 20px; }
</style>
</head>
<body>

<h2>Random Joke Generator 😂</h2>


<button onclick="getJoke()">Get Joke</button>
<p id="jokeText"></p>

<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

✅ Would You Like?


✔ Another mini project with Promises?
✔ Convert this to Async/Await version?
✔ Or move next to Local Storage or JSON practice?

Tell me — I’ll guide next part simply 🚀


Great Hassan! Let’s move to the next important topic: Local Storage for websites —
explained very simply.

✅ What is Local Storage?


✔ Local Storage lets your website save small data inside the browser
✔ Even if you close the page, data stays
✔ Stored as key-value pairs
✔ Only works on the same device & browser

🎯 Where Local Storage is Useful


✔ Save user name
✔ Save dark/light mode choice
✔ Save form inputs
✔ Save small settings

✅ Simple Example: Store and Get Name


// Save to Local Storage
localStorage.setItem("username", "Hassan");

// Get from Local Storage


let name = localStorage.getItem("username");
console.log(name); // Shows: Hassan

// Remove from Local Storage


localStorage.removeItem("username");

✔ .setItem() → Save
✔ .getItem() → Retrieve
✔ .removeItem() → Delete

✅ Mini Practice: Web Example


<h2 id="greeting"></h2>
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="saveName()">Save</button>

<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
+ "!";
}
}

showGreeting(); // Run on page load


</script>

✅ Quick Recap
✔ Data stays even after refresh
✔ Local Storage only stores strings
✔ You can store JSON using JSON.stringify()

✅ Would You Like?


✔ Practice tasks for Local Storage?
✔ Mini project combining API + Local Storage?
✔ Or move next to JSON deep practice?

Tell me — I’ll guide you clearly, step by step 🚀

You might also like