JavaScript — Part 4
The Promise API:
There are two types of methods:
A) Instance Methods
(Methods used on a promise you created)
Instance Methods
· then() → success
· catch() → error
· finally() → always
B) Static Methods
(Methods used on the Promise class itself, like Promise.all())
Static Methods
· Promise.resolve() → make resolved promise
· Promise.reject() → make rejected promise
· Promise.all() → wait for all (fails if one fails)
· Promise.allSettled() → wait for all (never fails)
· Promise.race() → first finished
· Promise.any() → first successful
Example: basic example to print the resolved value of the promises in the console.
Here, after 1s, Value 1 is printed, after 2s Value 2 is printed and after 3s, Value 3 is printed.
Example: doing the same thing we did above using the promise.all()
But what if one of the promise get rejected? Will promise.all() still works? No!
How to deal with this? We can use .catch() or can use Promise.allSettled() as shown below:
Now, what if we wish that the promise which first get resolved will get printed? Then we can use Promise.race():
What if the fastest one giving an error? Then .race() will show error. How to deal then? We can use .any():
Async/Await in JavaScript:
What is async/await?
Async/await is a cleaner, easier way to work with Promises. It helps you write asynchronous code that looks like normal synchronous code.
What is async?
A function becomes “async” when you write:
async function myFunc() {}
Inside an async function, you can use await. An async function always returns a Promise.
What is await?
await pauses the function and waits for a Promise to finish.
let result = await promise;
Your code stops at this line until the promise resolves.
Example: Even though you just returned a string, the function returns a Promise automatically.
In this code, the function greet is marked as async, which means it automatically returns a Promise even though it simply returns the string “Hello”. When greet() is called, it doesn’t return the string directly — it returns a Promise that eventually resolves to “Hello”. Since it’s a Promise, we use .then() to get the final value. So greet().then(console.log) waits for the Promise to resolve and then prints “Hello” to the console.
Example: introducing the “await” in the code.
Here we create an async function called demo, which allows us to use the await keyword inside it. Inside the function, a promise is created that immediately resolves with the text “Hello World”. When the code reaches await promise, the function pauses and waits for that promise to finish. Once the promise resolves, the result is stored in the variable result, and finally the program prints “Hello World” to the console.
Error Handling-try and catch:
What is try…catch?
try and catch are used to handle errors in JavaScript so that your program does not crash when something goes wrong.
How it works
· The code inside try runs normally.
· If an error happens, the program immediately jumps to catch.
· The code inside catch handles the error safely.
Why is try…catch useful?
· Prevents your program from breaking
· Helps you show user-friendly messages
· Lets you handle unexpected errors safely
Example: basic example where there is no error!
Example: basic example where there is error but no error handling.
Example: now handling error using the try-catch
Also, try…catch works only for synchronous code. But setTimeout runs after the try block is already done, so try…catch cannot catch its errors.
Example: setTimeout inside the try…catch.
But, how can we rectify this? We can do so by writing another try…catch inside the setTimeout():
The Error Object & Custom Errors:
What is the Error Object?
In JavaScript, whenever something goes wrong, the language creates an Error object. This object contains useful information about what went wrong.
The Error object has important properties:
Built-in Error Types:
Example: a basic example showing try…catch.
Now, getting the name and message for an error:
Creating Custom Errors
You can create your own errors using the Error constructor — useful for validation, API responses, and logic checks.
Example:
Example: throwing errors manually
The Finally Clause:
What is the Finally Clause?
The finally block is a part of JavaScript’s error-handling structure (try → catch → finally). It is used to write code that must run no matter what happens — whether an error occurs or not.
Basic idea
· try → code that may cause an error
· catch → runs only if an error happens
· finally → always runs, after try or catch, no matter what
This is why finally is used for things like closing files, stopping timers, cleaning up memory, resetting variables, etc.
Example: a basic try…catch block without finally.
Example: introducing error in the catch block as well as in try block
So, what if we write some code after the catch block? It will not run:
Then how we make sure that if error occurred in “catch” block then the rest of the code should work? We can do so by using the “finally” block:
Fetch API:
What is Fetch API?
Fetch API is a built-in browser feature that lets you request data from servers (APIs). It returns a Promise, so you can use .then, .catch, or async/await.
Basic Syntax
fetch(“url”)
.then(response => response.json()) // convert to JSON
.then(data => console.log(data)) // use the data
.catch(error => console.log(error)); // handle errors
Example: a basic example of fetching, using the API.
This code fetches weather data from an API and prints it to the console. The fetch function sends a request to the given URL and returns a Promise. In the first .then(), the response (value1) is converted to JSON and returned. In the second .then(), the resulting JSON data (value2) is received and logged to the console.
Do you know? Getting a response is a 2 way process?
Getting a response from the Fetch API happens in two steps. First, when you call fetch(), the browser connects to the server and gives you a response object, but this object only contains basic information like status code (200, 404), headers, and a placeholder for the body. The actual data (like JSON) is not available yet. Second, you must extract the real data from the response by calling a method such as response.json(), response.text(), or response.blob(). These methods also return a Promise, because converting the body into usable data takes some time. So the fetch process is: (1) fetch returns a response object, (2) you extract the data from the response.
Example: here you can see the status of the response is present
This code sends a request to the weather API and logs details about the response before printing the actual data. The fetch call returns a Promise containing the response object. In the first .then(), it logs the HTTP status code (value1.status) and whether the request was successful (value1.ok). Then it converts the response to JSON by returning value1.json(). The next .then() receives that JSON data (value2) and logs the weather information to the console.
Sending POST request with Fetch API:
What is a POST request?
A POST request is used when you want to send data to a server — like form data, login info, or creating a new record.
How do we send POST with Fetch?
To make a POST request, we add:
· method: “POST”
· headers to tell the server we are sending JSON
· body with the actual data (converted to JSON using JSON.stringify())
Basic Syntax
fetch(“URL”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify(dataToSend)
});
Example: a basic example for this
This code sends a POST request to an API with a JSON object containing a name and job. The fetch function is given options specifying the HTTP method, headers, and the request body, which is converted to a JSON string. After the request is sent, the first .then() converts the server’s response into JSON, and the second .then() logs that response to the console.
Example: async and await with the fetch API with POST
This version uses async and await to make the POST request easier to read. Inside the sendData function, the fetch call waits for the server response, then await response.json() converts that response to JSON. The final result is printed to the console. Using async/await makes the code look more like normal synchronous code while still handling asynchronous operations.
Cookies in JavaScript:
What are Cookies?
Cookies are small pieces of data stored in the browser. Websites use them to remember things like:
· Login information
· User preferences
· Items in a cart
· Last visited page
Cookies are stored as key–value pairs.
Where can we find cookie for a website?
How to Create/Set a Cookie
You set a cookie by writing to document.cookie. By doing so we are adding cookies to the existing cookies, not replacing any cookie.
Example:
Now, we can also take user input and set them as the part of the cookie:
But, will it be able to take and store URI component and store by above method? No! We need to use encodeURIComponent to do so.
Also, to decode it we are using decodeURIComponent:
Cookie Options:
Common attributes you can add:
We can’t add multiple cookies just by separating them with “;”:
Important points about cookies:
· Cookies are automatically sent to the server with every request.
· Maximum size is about 4 KB per cookie.
· Cookies can expire using expires or max-age.
· Without expiry, cookies are deleted when the browser closes.
· Cookies are stored as plain text, so avoid storing sensitive data.
· Use secure, HttpOnly, and SameSite for better security.
· Updating a cookie is done by writing it again with the same name.
· Deleting a cookie requires setting an old expiration date.
· Cookies work across pages of the same domain (unless restricted).
Get Aditya Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
· Cookies slow down requests because they are sent every time.
· Cookies store only strings, so objects must be converted using JSON.stringify().
Local Storage & related methods:
What is localStorage?
localStorage is a built-in browser storage where you can save data permanently. The data:
· stays even after you close or reopen the browser
· is stored on your computer
· uses key–value pairs
· stores strings only
Why do we use localStorage?
To remember things like:
· theme (dark/light)
· username
· settings
· form data
· cart items
· tokens (not recommended for sensitive data)
Main Methods of localStorage
Where can I find the local storage in the website?
Now, in order to add the items in the local storage we uses “.setItem”:
We can see that we did it successfully in the “Application” section:
Example: to get the value at the key we use the “.getItem”
Example: to clear the local storage we can use the “.clear()”:
Example: to get the length of the local storage we uses “.length”:
Important Points About localStorage (Short Summary)
· Data stays permanently until manually removed.
· Stores data as key–value pairs.
· Only stores strings, so objects must be JSON stringified.
· Has around 5–10 MB storage limit (much larger than cookies).
· Data is not sent to the server automatically (unlike cookies).
· Accessible only in the same domain.
· Should not store sensitive data (like passwords or tokens).
· Easy to use: setItem(), getItem(), removeItem(), clear().
sessionStorage & related methods:
What is sessionStorage?
sessionStorage is a small key-value storage inside the browser that:
· Stores data only for one browser tab
· Data is deleted when the tab is closed
· Works like localStorage but shorter lifetime
· Stores everything as strings
Why use sessionStorage?
Use it when you want data to exist only while one tab is open, such as:
· Tracking temporary form inputs
· Storing a user’s progress on one page
· Holding JWT tokens for one tab
· Preventing data from leaking across tabs
Important Notes (Very Simple)
· Data stays only until the tab is closed
· Does not share data between tabs
· Max storage ~5MB
· Stores values as strings only
· Not secure → avoid storing passwords
· Data persists on refresh (not lost)
Where can I find this Session storage in my browser?
Example: to store a value “sessionStorage.setItem”
This thing will get reflected as:
Some other methods:
What is the Storage Event?
The storage event is a browser event that triggers when localStorage or sessionStorage changes in another tab.
It fires only in other tabs, NOT in the same tab that made the change.
Why does it exist?
To help multiple tabs sync data.
Example:
· User logs out in one tab → all other tabs also log out.
· Change theme in one tab → update theme in all tabs.
What Data Does the Event Give?
Important Notes:
· Fires only in other tabs, not in the same tab.
· Works only for localStorage, not sessionStorage in many browsers.
· Useful for multi-tab communication.
· clear() also triggers the event.
Example:
Introduction to Object Oriented Programming:
Object-Oriented Programming (OOP) is a way of writing code where we group related data and functions into a single unit called an object. It helps us structure programs so they are easy to understand, reuse, and maintain.
In JavaScript, OOP is based on objects. Each object stores:
· Properties → data
· Methods → functions that belong to the object
Using OOP, we model real-world things as code.
Example: A car has properties like color, speed, and methods like start() or stop().
Why Use OOP?
· Organizes code in a clean way
· Makes code reusable
· Helps create multiple objects easily
· Reduces errors by grouping related things together
Four Pillars of OOP in JavaScript:
1. Encapsulation
· Wrap data + functions into one unit (object)
2. Abstraction
· Hide complexity and show only what is needed
3. Inheritance
· One object can get properties and methods from another
4. Polymorphism
· Same method name behaves differently in different objects
Protypes and __proto__ in JavaScript:
In JavaScript, every object has a hidden link to another object called its prototype, and this prototype is where JavaScript looks for properties or methods if they are not found on the original object.
Think of it like a backup or a parent object. The __proto__ property (pronounced “dunder proto”) is simply a pointer that shows which prototype your object is connected to. When you access obj.someFunction, JavaScript first checks inside obj; if it can’t find it, it climbs up the chain using obj.__proto__, then the prototype’s prototype, and so on — this is called the prototype chain.
Functions in JS also have a special property called prototype, which is used when creating objects with constructors or classes; this prototype becomes the __proto__ of all objects created by that constructor. This system allows JavaScript to share methods efficiently, avoid duplicates, and support OOP-style behaviour.
Example: creating a basic object in the JS
Now, let’s create a method:
So, will this method can be used by our object obj? No, to let it do so:
Now, we can create prototype of a prototype as well:
Classes and Objects in JavaScript:
What is a Class?
A class is a blueprint or template for creating objects. It describes what properties (data) and what methods (functions) the objects will have.
Think of a class as a “design” and objects as the “real things” created from that design.
What is an Object?
An object is an actual thing created from a class. Each object has its own copy of properties, but shares methods defined in the class.
Basic Syntax of a Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(“Hello, I am “ + this.name);
}
}
let p1 = new Person(“Aditya”, 21);
p1.greet();
Example: creating a simple class with the methods.
Example: creating two instanced of class
Constructors in JavaScript:
What is a Constructor?
A constructor is a special function inside a class that automatically runs when you create an object.
Its job is to set the initial values of the object.
In simple words:
A constructor prepares the object when it is created.
Constructor Syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
· constructor() → special function
· this.name / this.age → properties added to the object
Creating an Object
let p1 = new Person(“Aditya”, 21);
console.log(p1.name);
console.log(p1.age);
When new Person(“Aditya”, 21) runs:
· constructor is automatically called
· it sets:
o this.name = “Aditya”
o this.age = 21
Example: Adding Methods Along with Constructor
Example: constructor Without Parameters
Also, If You Don’t Write a Constructor — JavaScript automatically creates an empty one:
constructor() {}
So, the class still works.
Short Summary
· Constructor = a special function that prepares an object.
· It runs automatically when using new.
· It sets properties using this.
· Child classes use super() to call parent constructor.
· If you don’t write one, JS creates a default constructor.
Contact Me:
📧 Email: adii.utsav@gmail.com
🔗 LinkedIn: https://www.linkedin.com/in/aditya-kumar-3241b6286/
💻 GitHub: https://github.com/Rememberful







