In JavaScript, functions are objects. A good way to imagine functions is as callable “action objects”.
We can not only call them, but also treat them as objects: add/remove properties, pass by reference etc.
function sayHi() { let sayHi = function() { function f(sayHi = function() {}) {
[Link]("Hi"); [Link]("Hi"); [Link]("Hi"); // sayHi (works!)
} }; }
sayHi(); // sayHi sayHi(); f();
// sayHi (there's a name!)
Named Function Expression: Named Function Expression or NFE or Nested Function is a term for
function expressions that have a name.
let sayHi = function func(who) {
if (who) {
[Link]('Hello ',who);
} else {
func("Guest");
}
};
sayHi();
//func()
Scheduling: setTimeout and setInterval
We may decide to execute a function not right now, but at a certain time later. That’s called “scheduling a call”.
There are two methods for it:
• setTimeout allows us to run a function once after the interval of time.
• setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating
continuously at that interval.
let sayHi=function(){
[Link]("Hello");
function sayHi(phrase, who) { }
[Link]( phrase + ', ' + who ); let si=setInterval(sayHi,2000)
}
setTimeout(sayHi, 1000, "Hello", "John"); let timerStop=function(){
clearInterval(si);
alert('stop’);
}
setTimeout(timerStop,5000)
In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function,
even if it’s not a method of an object. The value of this is evaluated during the run-time, depending on the
context.
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
[Link]( [Link] );
}
[Link] = sayHi;
[Link] = sayHi;
[Link]();
[Link]();
admin[‘func']();
Arrow functions are special: they don’t have their “own” this. If we reference this from such a function, it’s
taken from the outer “normal” function. That’s a special feature of arrow functions, it’s useful when we actually
do not want to have a separate this, but rather to take it from the outer context.
let sayHello = function () { let sayHello = () => {
[Link]("Welcome to JavaScript"); [Link]("Welcome to JavaScript");
}; };
sayHello(); sayHello();
There are two parts for the Arrow function syntax:
1. let sayHello = ()
This declares a variable sayHello and assigns a function to it using () to just say that the variable is a function.
2. => { }
This declares the body of the function with an arrow and the curly braces.
No parameter, single line code: One parameter, single line code:
let sayHello = () => [Link]("Welcome to let sayHello = data => [Link]("Welcome to JavaScript
JavaScript"); "+data);
sayHello(); sayHello("and React");
const myObject1 ={ myMethod() {
[Link](this==myObject1);
function myMethod2() {
[Link](this==myObject1)
};
myMethod2();
}}
const myObject2 ={ myMethod() {
[Link](this==myObject2);
myMethod2=()=>{[Link](this==myObject2)};
myMethod2();
}}
[Link]();
[Link]("<br>")
[Link]();
Asynchronous Programming
//Synchronous Programming [Link]("Before For loop</br>");
for (var i = 0; i < 2; i++) {
[Link]("Before For loop</br>"); setTimeout(function(){
for (var i = 0; i < 2; i++) { [Link]("<h1>setTimeout</br>");
f1(); f1();
f2(); },5000);
} f2();
[Link]("After For loop</br>"); }
function f1() { [Link]("After For loop</br>");
[Link]("In f1</br>"); function f1() {
} [Link]("In f1</br>");
function f2() { }
[Link]("In f2</br>"); function f2() {
} [Link]("In f2</br>");
}
Callback Function
function f2(data){ function f1(n1,n2,f2=function(data){
[Link]("Data:- "+data); [Link]("Data:- "+data);
} }){
function f1(n1,n2,f){
let n=n1+n2;
let n=n1+n2;
f2(n) f2(n);
}; };
F1(5,7) f1(5,7)
Function binding
When passing object methods as callbacks, for instance to setTimeout, there’s a known problem: "losing this".
let user = {
firstName: "John",
sayHi() {
[Link]("Hello," ,[Link]);
} };
setTimeout([Link], 1000);
//setTimeout([Link](), 1000);
bind: Functions provide a built-in method ”bind” that allows to fix this.
let user = {
firstName: "John",
sayHi(str="Hello") {
[Link](str," ",[Link]);
}
};
let sayHi = [Link](user);
sayHi("Hi");
setTimeout(sayHi, 1000);
Callback hell, which is also called a Pyramid of Doom, consists of more than one nested callback which makes
code hard to read and debug. As calls become more nested, the code becomes deeper and increasingly more
difficult to manage, especially if there are more loops, conditional statements, and so on in the code. To overcome
the disadvantage of callbacks, the concept of Promises was introduced.
//Callback hell const func = () => {
setTimeout(() => {
f1(function () { fun(1);
f2(function () { setTimeout(() => {
}); fun(2);
}); setTimeout(() => {
fun(3);
function f1(f) { }, 1000)
[Link]("In f1</br>"); }, 1000)
f(); }, 1000)
} }
function f2(f) { let fun = (data) => {
[Link]("In f2</br>"); [Link]("Hello "+data+"<br/>");
f(); }
} func();
Promise
• A Promise is a holder for a result or an error that will become available in the future.
• Promise provides a more structured way to write asynchronous calls.
• Promises have replaced callback functions as the preferred programming style for handling asynchronous calls.
• Built-in support for promises has been introduced as part of JavaScript from 2015.
• The Promise object represents the eventual completion (or failure) of an asynchronous operation and its
resulting value.
• A Promise is a returned object to which you can attach callbacks, instead of passing callbacks into a function.
• Promise comes to the rescue when there are chained asynchronous calls that are dependent on each other.
The constructor of the Promise accepts only one argument, a function with parameters resolve and reject.
new Promise(function (resolve, reject) { A Promise has three states:
//async code here • Pending: the result of the async call is not known yet.
//resolve if success, reject if error • Resolved: async call returned with success.
}); • Rejected: async call returned with an error.
Example 1:
var myPromise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("<h1>success</h1>");
}, 2000);
//setTimeout(() => reject(new Error("Whoops!")), 3000);
});
[Link](
function (data) {
[Link](data + "<h2>received in 2 seconds</h2>");
},
function (error) {
[Link](error);
}
);
Example 2:
function myDisplayer(some) {
[Link]("demo").innerHTML = some
}
let myPromise = new Promise(function (myResolve, myReject) {
let req = new XMLHttpRequest();
[Link]("GET", "[Link]");
[Link] = function () {
if ([Link] == 200) {
myResolve([Link]);
}
else {
myReject("File not Found");
}
};
[Link]();
});
[Link](function (value) {myDisplayer(value);},function(error) {myDisplayer(error);});
"async/await" was introduced to implement asynchronous code with promises that resemble synchronous code.
The word “async” before a function means one simple thing: a function always returns a promise. Other values
are wrapped in a resolved promise automatically.
async function hello() {
return "Hello Async";
}
hello().then((val) => [Link](val));
async function hello() {
return [Link]("Hello Async");
}
hello().then((val) => [Link](val));
There’s another keyword, await, that works only inside async functions. The keyword await makes JavaScript
wait until that promise settles and returns its result. Can’t use await in regular functions.
function func(x) {
setTimeout(function(){[Link](x)}, 2000);
}
async function hello() {
await func("Hello Async/Await");
}
hello();
function func(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function hello() {
[Link](await func("Hello Async/Await"));
}
hello();