Arrow Functions in JavaScript (ES6)
Basic Syntax
Traditional Function
function add(a, b) {
return a + b;
Arrow Function
const add = (a, b) => {
return a + b;
};
Shorter (Implicit Return)
const add = (a, b) => a + b;
If there is only one expression, return and {} are optional.
Arrow Function with One Parameter
const square = x => x * x;
[Link](square(5)); // 25
Parentheses can be skipped if there is only one parameter.
Arrow Function with No Parameters
const greet = () => "Hello World";
[Link](greet());
Arrow Functions with Multiple Statements
const calculate = (a, b) => {
const sum = a + b;
const product = a * b;
return { sum, product };
};
[Link](calculate(4, 5));
Arrow Functions & Array Methods (Most Common Use)
map()
const numbers = [1, 2, 3, 4];
const squares = [Link](n => n * n);
[Link](squares);
filter()
const numbers = [10, 15, 20, 25];
const result = [Link](n => n > 15);
[Link](result);
reduce()
const numbers = [10, 20, 30];
const total = [Link]((sum, n) => sum + n, 0);
[Link](total);
Arrow functions are heavily used with array methods.
Arrow Function vs Normal Function (this keyword)
Normal Function
const person = {
name: "Amit",
greet: function () {
[Link]([Link]);
};
[Link](); // Amit
Arrow Function
const person = {
name: "Amit",
greet: () => {
[Link]([Link]);
};
[Link](); // undefined
Important Difference
Arrow functions do NOT have their own this.
They inherit this from their surrounding scope.
Arrow Functions & arguments Object
Normal Function
function showArgs() {
[Link](arguments);
showArgs(1, 2, 3);
Arrow Function (Not Allowed)
const showArgs = () => {
[Link](arguments); // Error
};
Arrow functions do not have arguments object.
Use rest operator instead:
const showArgs = (...args) => {
[Link](args);
};
Arrow Functions Cannot Be Used As Constructors
const Person = (name) => {
[Link] = name;
};
const p = new Person("Amit"); // Error
Arrow functions cannot be called with new.
When to Use Arrow Functions
Callbacks
Array methods (map, filter, reduce)
Short utility functions
React components & hooks
When NOT to Use Arrow Functions
Object methods needing this
Constructors
Event handlers where this is required
filter() Method
What it does
• Creates a new array
• Includes elements that pass a condition
• Does NOT modify the original array
Syntax
[Link]((element, index, array) => condition)
Example 1: Filter even numbers
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = [Link](num => num % 2 === 0);
[Link](evenNumbers); // [2, 4, 6]
map() Method
What it does
• Creates a new array
• Transforms each element
• Length of array remains the same
Syntax
[Link]((element, index, array) => newValue)
Example 1: Square numbers
const numbers = [1, 2, 3, 4];
const squares = [Link](num => num * num);
[Link](squares); // [1, 4, 9, 16]
reduce() Method
What it does
• Reduces an array to a single value
• Useful for sum, total, average, grouping
Syntax
[Link]((accumulator, current) => newAccumulator, initialValue)
Example 1: Sum of numbers
const numbers = [10, 20, 30];
const sum = [Link]((total, num) => total + num, 0);
[Link](sum); // 60
find() Method
What it does
• Returns the first matching element
• Returns undefined if not found
Syntax
[Link]((element) => condition)
Example 1: Find a number
const numbers = [5, 12, 8, 130];
const found = [Link](num => num > 10);
[Link](found); // 12
sort() Method
What it does
• Sorts the array in-place
• Converts elements to strings by default
Modifies original array
Syntax
[Link]((a, b) => a - b)
Example 1: Sort numbers (ascending)
const numbers = [40, 10, 100, 25];
[Link]((a, b) => a - b);
[Link](numbers); // [10, 25, 40, 100]
Example 2: Sort strings
const names = ["Ravi", "Amit", "Neha"];
[Link]();
[Link](names);
Introduction to Async (Asynchronous JavaScript)
What is Async?
• JavaScript is single-threaded
• Asynchronous operations allow long-running tasks to run without blocking the main thread
Synchronous vs Asynchronous
Synchronous (Blocking)
[Link]("Start");
for (let i = 0; i < 1e9; i++) {}
[Link]("End");
The browser freezes until the loop finishes.
Asynchronous (Non-Blocking)
[Link]("Start");
setTimeout(() => {
[Link]("Async Task");
}, 2000);
[Link]("End");
Output
Start
End
Async Task
JS continues execution without waiting.
Async in Action (Callbacks → Promises → Async/Await)
[Link] (Old Approach)
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 2000);
fetchData(result => {
[Link](result);
});
Problems:
• Callback hell
• Difficult to read and maintain
[Link]
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
fetchData
.then(data => [Link](data))
.catch(error => [Link](error));
Better readability
Error handling using .catch()
3. Async / Await (Modern JS)
async function getData() {
try {
const result = await fetchData;
[Link](result);
} catch (error) {
[Link](error);
getData();
Looks synchronous
Easy to debug
Most preferred
HTTP Requests
What is an HTTP Request?
A way for a client (browser/app) to communicate with a server.
Common HTTP Methods
Method Purpose
GET Fetch data
POST Send new data
PUT Update entire data
Method Purpose
PATCH Update partial data
DELETE Remove data
HTTP Request Using fetch()
GET Request
fetch("[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link](error));
Using async/await
async function fetchUsers() {
try {
const response = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link](error);
fetchUsers();
HTTP Status Codes
What are Status Codes?
They indicate the result of an HTTP request.
Categories
Range Meaning
1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error
Common Status Codes
Code Meaning
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error
Handling Status Codes
if (![Link]) {
throw new Error(`HTTP Error: ${[Link]}`);
JSON Data
What is JSON?
• JavaScript Object Notation
• Lightweight data-exchange format
• Used in APIs
JSON Example
"id": 1,
"name": "Amit",
"email": "amit@[Link]"
Convert JSON ↔ JS Object
JSON → JS Object
const jsonString = '{"name":"Amit","age":25}';
const obj = [Link](jsonString);
[Link]([Link]);
JS Object → JSON
const user = { name: "Amit", age: 25 };
const jsonData = [Link](user);
[Link](jsonData);
Real-World Async Example (API Call)
async function getUser() {
try {
const response = await fetch("[Link]
if (![Link]) {
throw new Error("User not found");
const user = await [Link]();
[Link]([Link]);
} catch (error) {
[Link]([Link]);
}
getUser();