Land the job you want — prepare
with Real interviews Q&A
Curated interview questions, company-wise guides and coding rounds. Practice mock interviews, improve with feedback, and track your progress.
JavaScript JavaScript is a programming language used to make websites interactive and dynamic. It’s one of the core technologies of the web, alongside HTML (structure) and CSS (style).
With JavaScript, you can:- Update content on a page without reloading it
- Respond to user actions (clicks, typing, scrolling)
- Create animations, games, and interactive forms
- Communicate with servers (e.g., loading data from APIs)
JavaScript is both interpreted and compiled—depending on how you look at it.
- Traditionally: Interpreted language
- Modern reality: Just-In-Time (JIT) compiled
How it actually works today
Modern JavaScript engines like V8 JavaScript engine (used in Google Chrome and Node.js) do this:- Parse the code → convert it into an internal structure
- Interpret it initially → runs line by line
- Compile it using JIT → frequently used code is converted into optimized machine code
Variables store data values using var, let, or const.
A variable is like a named box where you keep data.let x = 10; // number
x = "Hello"; // stringvar is function-scoped, let and const are block-scoped.const cannot be reassigned.
The difference between var, let, and const in JavaScript mainly comes down to scope, re-declaration, re-assignment, and hoisting behavior.
Difference Between var, let, and const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block {} | Block {} |
| Re-declare | ✔ Yes | ✖ No | ✖ No |
| Re-assign | ✔ Yes | ✔ Yes | ✖ No |
| Hoisting | ✔ Yes (undefined) | ✔ Yes (TDZ) | ✔ Yes (TDZ) |
| Use in Modern JS | ✖ Avoid | ✔ Preferred | ✔ Preferred |
Data types in JavaScript define what kind of value a variable can hold—like a number, text, or more complex structures.
Two main categoriesPrimitive (basic, immutable)
let age = 25; // Number
let price = 99.99; // Number
let name = "John"; // String
let isLoggedIn = true; // Boolean
let x; // Undefined
let data = null; // Null
let big = 123456789012345678901234567890n; // BigInt
let id = Symbol("id"); // SymbolNon-Primitive (Reference types)
let user = { name: "John", age: 25 }; // Object
let colors = ["red", "blue", "green"];
function greet() {
console.log("Hello");
}
console.log(typeof "Hello"); // string
console.log(typeof 10); // number
console.log(typeof true); // boolean
A function in JavaScript is a reusable block of code designed to perform a specific task.
A function is like a machine:
- You give it input (parameters)
- It processes something
- It gives you output (return value)
function greet() {
console.log("Hello!");
}
greet(); // Output: Hello!
An array is like a list where items are stored in order.
let fruits = ["apple", "banana", "mango"];
//Accessing elements
console.log(fruits[0]); // apple
console.log(fruits[2]); // mangoAn object in JavaScript is a collection of key–value pairs used to store related data and functionality together.
An object is like a real-world entity with:- Properties (data)
- Methods (actions/functions)
let user = {
name: "John",
age: 25,
isLoggedIn: true
};
//Accessing value
console.log(user.name); // John
console.log(user["age"]); // 25
//Adding / updating properties
user.city = "Delhi"; // add
user.age = 30; // update
//Deleting properties
delete user.isLoggedIn;
//Object with function (method)
let person = {
name: "Alex",
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet(); // Hello Alex
The DOM (Document Object Model) is a programming interface for web pages that represents your HTML as a structured tree of objects.
The DOM lets JavaScript read, modify, and interact with HTML elements on a webpage.<html>
<body>
<h1>Hello</h1>
<p>Welcome</p>
</body>
</html>An event in JavaScript is an action or occurrence that happens in the browser, which your code can detect and respond to.
An event is something that happens on a webpage, like:- A user clicks a button
- Types in an input field
- Moves the mouse
- A page finishes loading
<button id="btn">Click Me</button>
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
- click → user clicks
- mouseover → mouse hovers
- keydown → key pressed
- submit → form submitted
- load → page loaded
null in JavaScript is a special value that represents an intentional absence of any value.
null means: “This variable has no value on purpose.”
let data = null; //Here, data is empty intentionally.undefined in JavaScript is a value that means a variable has been declared but not assigned any value yet.
A value is not assigned yetlet x;
console.log(x); // undefinedThe typeof operator in JavaScript is used to check the data type of a value or variable.
typeof tells you: “What kind of data is this?”typeof "Hello"; // "string"
typeof 10; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"NaN stands for “Not-a-Number” in JavaScript.
NaN is a special value that means:
“This is supposed to be a number, but it’s not a valid one.”let result = 0 / 0;
console.log(result); // NaN
// When do you get NaN?
"hello" * 5; // NaN
Number("abc"); // NaN
undefined + 10; // NaN
Strict mode usually refers to a feature in programming languages that enforces stricter rules for writing code, helping catch errors early and prevent bad practices.
In JavaScript (most common meaning)
“Strict mode” is a special mode you enable with:"use strict"; //When enabled, JavaScript behaves more strictly. For example:
x = 10; // Error in strict modeHoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their scope during compilation, before the code actually runs.
JavaScript “lifts” declarations, not values.console.log(x); // undefined
var x = 10;
var x;
console.log(x); // undefined
x = 10;
console.log(a); // ❌ Error
let a = 5;
greet(); // Works
function greet() {
console.log("Hello!");
}
sayHi(); // ❌ Error
var sayHi = function() {
console.log("Hi!");
};A closure in JavaScript is when a function remembers and can access variables from its outer (parent) scope even after that outer function has finished executing.
A closure is a function + its lexical environment (the variables it was created with).function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3 //Even though outer() has finished, inner() still remembers count.
//Even though outer() has finished, inner() still remembers count.
//When inner() is created, it captures the variable count.
//That captured memory stays alive → this is called a closure.
Scope in JavaScript means where a variable or function is accessible in your code.
Scope defines the visibility and lifetime of variables.//Global Scope
let name = "AK";
function greet() {
console.log(name); // Accessible here
}
//Function Scope
function test() {
let x = 10;
console.log(x); // Works
}
console.log(x); // ❌ Error
//Block Scope (let & const)
if (true) {
let a = 5;
const b = 10;
}
console.log(a); // ❌ Error
console.log(b); // ❌ Error
//Special Case: var (No Block Scope)
if (true) {
var x = 20;
}
console.log(x); // ✅ Works
The difference between == and === in JavaScript is about type checking.
5 == "5" // true
0 == false // true
null == undefined // true
//=== (Strict Equality)
5 === "5" // false
0 === false // false
null === undefined // false
//Both value and type must match
A callback function in JavaScript is a function that is passed as an argument to another function and executed later.
A callback is a function you give to another function so it can call it when needed.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("AK", sayBye);
//Output
//Hello AK
//Goodbye!
//Anonymous Callback
setTimeout(function() {
console.log("Runs after 2 seconds");
}, 2000);
Why Callbacks are Used
- Handle asynchronous operations (like API calls, timers)
- Execute code after a task finishes
- Make functions more flexible
JSON stands for JavaScript Object Notation. It is a lightweight data format used to store and exchange data between systems (like a server and a browser).
JSON is a text-based format that represents data as key–value pairs, similar to JavaScript objects.- Easy to read and write
- Language-independent (not just JavaScript)
- Used in APIs and web applications
- Data is in string format
// JavaScript Object
let obj = { name: "AK", age: 25 };
// JSON (string format)
let json = '{"name": "AK", "age": 25}';A Promise in JavaScript is an object that represents the result of an asynchronous operation—either it will complete successfully or fail in the future.
A Promise is a placeholder for a value that will be available later.States of a Promise- Pending → still working
- Fulfilled → completed successfully
- Rejected → failed
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
//Consuming a promises
myPromise
.then((result) => {
console.log(result); // success
})
.catch((error) => {
console.log(error); // failure
});
//Realworld example
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
fetchData().then(data => console.log(data));
Why Promises?
- Handle asynchronous operations (API calls, timers)
- Avoid callback hell
- Make code cleaner and easier to manage
async/await is a modern way to handle asynchronous code in JavaScript that makes it look and behave more like synchronous (normal) code.
async/await is syntax built on top of Promises that lets you write cleaner and easier-to-read async code.
async Keyword- Used before a function
- Makes the function always return a Promise
- Used inside an async function
- Waits for a Promise to resolve before moving forward
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data received"), 2000);
});
}
async function getData() {
let data = await fetchData();
console.log(data);
}
getData();Event bubbling in JavaScript is a behavior where an event starts from the target element and then propagates (bubbles up) to its parent elements in the DOM tree.
Event bubbling means an event moves from the child element → up to parent elements.
<div id="parent">
<button id="child">Click Me</button>
</div>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
//Output
Child clicked
Parent clicked
//First child runs
//Then event bubbles up to parent
//How to Stop Bubbling
document.getElementById("child").addEventListener("click", (e) => {
e.stopPropagation();
console.log("Child clicked only");
});
//Now parent will NOT be triggered
Event delegation is a technique in JavaScript where you attach a single event listener to a parent element instead of adding listeners to multiple child elements. The parent handles events for its children using event bubbling.
Event delegation means handling child element events using a single parent event listener.
document.querySelectorAll("button").forEach(btn => {
btn.addEventListener("click", () => {
console.log("Button clicked");
});
});
//Problem: Adds many event listeners (bad for performance)
document.getElementById("parent").addEventListener("click", (e) => {
if (e.target.tagName === "BUTTON") {
console.log("Button clicked");
}
});
//Example (With Delegation)
//Only one listener on parent handles all buttons
The this keyword in JavaScript refers to the object that is currently executing the function.
this points to the object that is calling the function.
console.log(this);
//In a browser → this refers to the window object
function test() {
console.log(this);
}
test();
const user = {
name: "AK",
greet() {
console.log(this.name);
}
};
user.greet(); // AK
//this refers to the object (user)
An arrow function is a shorter way to write functions in JavaScript using the = syntax. It was introduced in ES6 and is often used for cleaner and more concise code.
An arrow function is a compact way to write a function, and it does not have its own this.
// Normal function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => {
return a + b;
};map() is an array method in JavaScript used to transform each element of an array and return a new array.
map() loops through an array, applies a function to each item, and returns a new array.
array.map((element, index, array) => {
return newValue;
});
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
//Each element is transformed → new array is returned
//Example with Objects
const users = [
{ name: "A" },
{ name: "B" }
];
const names = users.map(user => user.name);
console.log(names); // ["A", "B"]
Important Behavior
- Returns a new array
- Does not modify original array
- Always same length as original
filter() is an array method in JavaScript used to select elements from an array based on a condition.
filter() loops through an array and returns a new array containing only the elements that pass a condition.
array.filter((element, index, array) => {
return condition; // true or false
});
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
//Example with Object
const users = [
{ name: "A", age: 20 },
{ name: "B", age: 30 }
];
const adults = users.filter(user => user.age >= 25);
console.log(adults);
// [{ name: "B", age: 30 }]reduce() is an array method in JavaScript used to reduce an array to a single value (like a sum, object, or result).
reduce() takes all elements of an array and combines them into one final result.
array.reduce((accumulator, currentValue, index, array) => {
return updatedAccumulator;
}, initialValue);
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
In JavaScript, a prototype is a mechanism that allows objects to inherit properties and methods from other objects. Mechanism to share properties between objects.
A prototype is an object from which other objects can inherit features.
Every JavaScript object has a hidden property called [[Prototype]] (accessible via __proto__), which links it to another object.
function Person(name) {
this.name = name;
}
// Adding method to prototype
Person.prototype.greet = function() {
console.log("Hello " + this.name);
};
const p1 = new Person("AK");
p1.greet(); // Hello AK
// greet() is not inside the object
// It is shared via the prototype
Prototypal inheritance in JavaScript is a mechanism where one object can inherit properties and methods from another object through the prototype chain.
Prototypal inheritance means objects inherit directly from other objects.
Instead of classes (like in other languages), JavaScript uses prototypes to share behavior.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a sound");
};
function Dog(name) {
Animal.call(this, name); // inherit properties
}
// inherit methods
Dog.prototype = Object.create(Animal.prototype);
const d = new Dog("Tommy");
d.speak(); // Tommy makes a soundWhy It’s Useful
- Code reuse
- Memory efficiency
- Dynamic inheritance
Currying in JavaScript is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking one argument at a time.
Currying converts a function like f(a, b, c) into f(a)(b)(c).
function add(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
console.log(add(1)(2)(3));
//Arrow Function
const add = a => b => c => a + b + c;
console.log(add(1)(2)(3)); // 6Why Use Currying?
- Creates reusable functions
- Helps with function composition
- Allows partial application (fix some arguments early)
Debouncing is a technique used to limit how often a function runs by delaying its execution until a certain amount of time has passed since the last event.
Debouncing ensures a function runs only after the user stops triggering an event for a specific time.
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// Usage
const handleSearch = debounce(() => {
console.log("API call");
}, 500);Real-life Use Cases
- Search box (API calls)
- Window resize events
- Button click prevention (double-click)
- Auto-save features
Throttling is a technique used to limit how often a function runs by ensuring it executes at most once in a specified time interval, no matter how many times the event fires.
Throttling makes a function run at a fixed rate, even if events happen continuously.
function throttle(fn, limit) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
// Usage
const handleScroll = throttle(() => {
console.log("Scroll event");
}, 1000);Real-life Use Cases
- Scroll events
- Window resize tracking
- Mouse movement tracking
- Rate-limiting button clicks
The event loop is a core concept in JavaScript that allows it to handle asynchronous operations even though it is single-threaded.
The event loop is a mechanism that manages execution of code, callbacks, and async tasks in JavaScript.
How JavaScript Works- Call Stack → executes functions (synchronous code)
- Web APIs → handle async tasks (like setTimeout, DOM events)
- Callback Queue → stores completed async callbacks
- Event Loop → moves tasks to the call stack
How Event Loop Works (Step-by-Step)
- Code runs in call stack
- Async tasks go to Web APIs
- When done → callbacks go to queue
- Event loop checks:If call stack is empty → pushes callback to stack
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
//output
Start
End
Timeout call(), apply(), and bind() are JavaScript methods used to control what this refers to inside a function.
These methods let you manually set the value of this.
//call()
//Calls the function immediately
//Arguments are passed one by one
function greet(city) {
console.log(this.name + " from " + city);
}
const user = { name: "AK" };
greet.call(user, "Delhi"); // AK from Delhi
//apply()
//Calls the function immediately
//Arguments are passed as an array
greet.apply(user, ["Mumbai"]); // AK from Mumbai
//bind()
//Does NOT call immediately
//Returns a new function with this fixed
const boundFunc = greet.bind(user, "Punjab");
boundFunc(); // AK from Punjab
A memory leak in JavaScript happens when memory that is no longer needed is not released, causing the application to use more and more memory over time.
A memory leak is when your program keeps holding memory it doesn’t need anymore.
Why It’s a Problem- Slows down the application
- Increases memory usage
- Can crash the app/browser
name = "AK"; // accidentally global Never gets cleaned up
let data = { big: "data" };
data = null; // ✔ should remove reference
function outer() {
let largeData = new Array(1000000);
return function() {
console.log("Using data");
};
}
//largeData stays in memory because of closure
button.addEventListener("click", handler);
// if not removed → memory leak
setInterval(() => {
console.log("Running");
}, 1000);
//If never cleared → keeps running forever
To create reusable functionality using import / export (ES Modules) in JavaScript, you split your code into separate files (modules) and share functions, variables, or classes between them.
Write code once → export it → reuse it anywhere using import.
//math.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
//app.js
import { add, multiply } from "./math.js";
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
An IIFE stands for Immediately Invoked Function Expression.
An IIFE is a function that runs immediately after it is defined.
(function() {
console.log("I run immediately!");
})();
//Wrapped in ()
//Invoked with ()
//Arrow Function IIFE
(() => {
console.log("Arrow IIFE");
})();
(function(name) {
console.log("Hello " + name);
})("AK");
(function() {
let x = 10; // not accessible outside
})();
There are several common ways to reverse a string in JavaScript
//Using Built-in Methods (Most Common)
const str = "hello";
const reversed = str.split("").reverse().join("");
console.log(reversed); // "olleh"
//Using a Loop
const str = "hello";
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
console.log(reversed); // "olleh"
//Using Recursion
function reverseString(str) {
if (str === "") return "";
return reverseString(str.slice(1)) + str[0];
}
console.log(reverseString("hello")); // "olleh"
//Using reduce()
const str = "hello";
const reversed = str.split("").reduce((acc, char) => char + acc, "");
console.log(reversed); // "olleh"
//For Unicode (emojis, special characters), use:
[...str].reverse().join("");
To check if a string is a palindrome, you verify whether it reads the same forward and backward.
//Using Reverse Method (Most Common)
function isPalindrome(str) {
const reversed = str.split("").reverse().join("");
return str === reversed;
}
console.log(isPalindrome("madam")); // true
console.log(isPalindrome("hello")); // false
//Ignore Case & Spaces (Better Version)
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
const reversed = clean.split("").reverse().join("");
return clean === reversed;
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
//Using Loop (Efficient)
function isPalindrome(str) {
let clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
for (let i = 0; i < clean.length / 2; i++) {
if (clean[i] !== clean[clean.length - 1 - i]) {
return false;
}
}
return true;
}
//Using Two Pointers (Interview Favorite)
function isPalindrome(str) {
let clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
Here are the most common ways to find the maximum value in an array in JavaScript:
const arr = [10, 5, 20, 8];
const max = Math.max(...arr);
console.log(max); // 20
//Using Loop (Interview Friendly)
const arr = [10, 5, 20, 8];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log(max); // 20
//Using reduce()
const arr = [10, 5, 20, 8];
const max = arr.reduce((acc, curr) => {
return curr > acc ? curr : acc;
}, arr[0]);
console.log(max); // 20
//Using sort() (Not Recommended for Performance)
const arr = [10, 5, 20, 8];
arr.sort((a, b) => b - a);
console.log(arr[0]); // 20
Here are the most common ways to remove duplicates from an array in JavaScript:
Using Set (Best & Easiest)
const arr = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]
//Using filter()
const arr = [1, 2, 2, 3, 4, 4];
const unique = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(unique); // [1, 2, 3, 4]
//Using Loop
const arr = [1, 2, 2, 3, 4, 4];
const unique = [];
for (let i = 0; i < arr.length; i++) {
if (!unique.includes(arr[i])) {
unique.push(arr[i]);
}
}
console.log(unique); // [1, 2, 3, 4]
//Using reduce()
const arr = [1, 2, 2, 3, 4, 4];
const unique = arr.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(unique);
Here are the most common ways to merge arrays in JavaScript:
//Using Spread Operator (Best & Modern)
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4]
//Using concat()
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]
//Merge Multiple Arrays
const a = [1];
const b = [2];
const c = [3];
const merged = [...a, ...b, ...c];
console.log(merged); // [1, 2, 3]
//Using push() (Modifies Original)
const arr1 = [1, 2];
const arr2 = [3, 4];
arr1.push(...arr2);
console.log(arr1); // [1, 2, 3, 4]
//Merge & Remove Duplicates
const arr1 = [1, 2, 2];
const arr2 = [2, 3, 4];
const merged = [...new Set([...arr1, ...arr2])];
console.log(merged); // [1, 2, 3, 4]
Here are the most common ways to convert a string to a number in JavaScript:
//Using Number() (Recommended)
const str = "123";
const num = Number(str);
console.log(num); // 123
//Using Unary + (Shortcut)
const str = "123";
const num = +str;
console.log(num); // 123
//Using parseInt()
const str = "123px";
const num = parseInt(str);
console.log(num); // 123
//const str = "123px";
const num = parseInt(str);
console.log(num); // 123
//Using parseFloat()
const str = "123.45px";
const num = parseFloat(str);
console.log(num); // 123.45
//Using * 1 (Less Common)
const str = "123";
const num = str * 1;
console.log(num); // 123
To loop through an object in JavaScript, you can use several methods depending on what you need (keys, values, or both).
const user = {
name: "AK",
age: 25,
city: "Delhi"
};
//for...in (Most Basic)
for (let key in user) {
console.log(key, user[key]);
}
//Object.keys()
Object.keys(user).forEach(key => {
console.log(key, user[key]);
});
//Object.values()
Object.values(user).forEach(value => {
console.log(value);
});
//Object.entries() (Best for both)
Object.entries(user).forEach(([key, value]) => {
console.log(key, value);
});
//Using for...of with entries
for (let [key, value] of Object.entries(user)) {
console.log(key, value);
}
To delay function execution in JavaScript, you typically use timers like setTimeout.
setTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
//Delay a Custom Function
function greet() {
console.log("Hello!");
}
setTimeout(greet, 3000);
//Pass Arguments
function greet(name) {
console.log("Hello " + name);
}
setTimeout(() => greet("AK"), 2000);
//Using Promise + setTimeout
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
console.log("Start");
await delay(2000);
console.log("After 2 sec");
}
run();
//Using setInterval (Repeated Delay)
setInterval(() => {
console.log("Runs every 2 seconds");
}, 2000);
//Cancel Delay
const timer = setTimeout(() => {
console.log("Won't run");
}, 2000);
clearTimeout(timer);
Here are clear Fetch API examples in JavaScript—from basic to practical use:
//Basic GET Request
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
//Using async/await (Recommended)
async function getUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getUsers();
//POST Request (Send Data)
async function createUser() {
const response = await fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "AK",
email: "ak@example.com"
})
});
const data = await response.json();
console.log(data);
}
createUser();
//PUT / UPDATE Request
fetch("https://jsonplaceholder.typicode.com/users/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Updated Name"
})
})
.then(res => res.json())
.then(data => console.log(data));
//DELETE Request
fetch("https://jsonplaceholder.typicode.com/users/1", {
method: "DELETE"
})
.then(() => console.log("Deleted"));
Here’s how to create a Promise in JavaScript step by step:
const myPromise = new Promise((resolve, reject) => {
// async task
if (true) {
resolve("Success");
} else {
reject("Error");
}
});
//Example (Simple)
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
//Example with setTimeout (Async)
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received after 2 seconds");
}, 2000);
});
fetchData.then(data => console.log(data));
//Using Function to Create Promise
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done");
}, 1000);
});
}
getData().then(res => console.log(res));
//Handle Errors
function getData() {
return new Promise((resolve, reject) => {
let error = false;
if (!error) {
resolve("Success");
} else {
reject("Something went wrong");
}
});
}
getData()
.then(res => console.log(res))
.catch(err => console.log(err));