Javascript Day-3

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 5

Default parameter:

Default parameters refer to the ability to assign default values to function


parameters in JavaScript. In previous versions of JavaScript, if a function was
called without passing a value for a parameter, the parameter would be assigned the
value undefined. With the introduction of default parameters in ES6, you can
specify a default value for a parameter in the function's parameter list.

function greet(name = 'Anonymous') {


console.log(`Hello, ${name}!`);
}

greet();
greet('John');

............................................

Rest and spread operators:

Rest Operator (...):

The rest operator is denoted by three dots (...) and is used in function parameter
lists to capture multiple arguments into a single array. It allows you to represent
an indefinite number of arguments as an array within a function.

function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}

console.log(sum(1, 2, 3, 4));

...........................................

Spread Operator (...):

The spread operator, also denoted by three dots (...), is used to expand elements
from an array or object into individual elements. It can be used in function calls,
array literals, and object literals.

const numbers = [1, 2, 3, 4];


console.log(...numbers); // Output: 1 2 3 4

const array1 = [1, 2, 3];


const array2 = [...array1, 4, 5];
console.log(array2);

const obj1 = { foo: 'bar', x: 42 };


const obj2 = { ...obj1, y: 10 };
console.log(obj2);

......................................................
Synchronous Execution:

In synchronous execution, code is executed line by line, and each operation blocks
the execution until it completes.
This means that each operation must finish before the next one can begin.
Synchronous operations are typically predictable and easy to understand, but they
can also cause the program to halt if an operation takes a long time to complete.
console.log("Start");
console.log("First");
console.log("Second");
console.log("End");

............................................................

Asynchronous Execution:

In asynchronous execution, code doesn't wait for an operation to finish before


moving on to the next one.
Instead, asynchronous operations are scheduled to run in the background, and the
program continues its execution without blocking.
When an asynchronous operation completes, a callback function or a promise is used
to handle the result.

console.log("Start");

setTimeout(function() {
console.log("Async operation complete");
}, 2000);

console.log("End");

................................
How many ways to achive acynchronous exection

callback:

function fetchData(callback) {
const data = "Async data";
callback(null, data);
}

fetchData(handleData);

console.log("Vinay");
console.log("namith");
console.log("sashank");

function handleData(error, result) {


if (error) {
console.error(error);
} else {
console.log(result);
}
}

.............................................

Promise:
A Promise in JavaScript represents the eventual completion (or failure) of an
asynchronous operation. It is an object that may produce a single value in the
future. Promises help handle asynchronous code in a more structured and readable
way.

EX:1
const promis=new Promise((resolve,reject)=>{
console.log("Async Execution");
if(false){
resolve();
}
else{
reject();
}
});

promis.then(
()=>{
console.log("Passed");
},
()=>{
console.log("Not Passed No Bikes");
}
)

....................
Ex:2

const promis=new Promise((resolve,reject)=>{


console.log("Async Execution");
if(false){
const person={name:"Anurag"}
resolve(person);
}
else{
const error={errcode:'1001'}
reject(error);
}
});

promis.then(
(val)=>{
console.log(val);
}
).catch(()=>console.log("Failed"))
.finally(()=>{console.log("clean up") });
.............................................

function fetchData() {
return new Promise(function(resolve, reject) {
const data = "Async data";
resolve(data); // Resolve the promise with the data
});
}

setTimeout(() => {
console.log("Vinay");
console.log("namith");
console.log("sashank");
}, 2000);

fetchData()
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.error(error);
});
....................................................

let p=Promise.resolve("execution is done");


let n=Promise.reject("execution is fail");

p.then((val)=>console.log(val));

..................................................

callback Hell:

Callback Hell, also known as the Pyramid of Doom, refers to a situation in


asynchronous JavaScript programming where multiple nested callbacks are used,
leading to code that becomes hard to read, understand, and maintain. It occurs when
there are numerous asynchronous operations that depend on the results of previous
operations.

function fetchData(callback) {
setTimeout(function() {
const data1 = "Data 1";
callback(data1, function(response1) {
// Nested callback
setTimeout(function() {
const data2 = "Data 2";
callback(data2, function(response2) {
// Nested callback
setTimeout(function() {
const data3 = "Data 3";
callback(data3, function(response3) {
// Nested callback
setTimeout(function() {
const result = "Final result";
callback(result);
}, 2000);
});
}, 2000);
});
}, 2000);
});
}, 2000);
}

fetchData(function(data, callback) {
console.log(data);
});

................................................
promise chaining:

function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
const data = "Data";
resolve(data);
}, 2000);
});
}

fetchData()
.then(function(data) {
console.log(data);
return fetchData();
})
.then(function(data) {
console.log(data);
return fetchData();
})
.then(function(data) {
console.log(data);
return fetchData();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error(error);
});
.........................................

let p=Promise.resolve("done");

p.then((val)=>{
console.log(val);
return "done2"
}).then((val)=>{
console.log(val);
return "done3";
}).then((val)=>console.log(val));
.............................................

Fetch Data From api

fetch('https://jsonplaceholder.typicode.com/todos')
.then(function(response) {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error('Error:', error);
});

.................................................

You might also like