1. What is Function Declaration/Definition/Statement?
function Square(num) {
return num * num;
}
2. What is Function Expression?
The function is called Anonymous Function.
const Square = function (num) {
return num * num;
}
3. What is First Class Functions?
We can pass functions inside functions, manipulate it and return it as well.
function Square(num) {
return num * num;
}
function displayFunction(fn, arg) {
console.log(fn(arg));
}
displayFunction(Square, 3);
4. What is and IIFE - Immediately Invoked Function Expression?
(function Show(num) {
console.log(num);
})(4);
5. IIFE O/P based question
(function x(a) {
(function y(b) {
console.log(a, b);
})(2);
})(1);
// Output:
1 2
6. Function Scope - O/P based question
var donot have block scope, it has functional scope. let has block scope. We can use closures to fix issue of var.
for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
0
1
2
3
4
-----
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
5
5
5
5
5
-----
for (var i = 0; i < 5; i++) {
function inner(i) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
inner(i);
}
0
1
2
3
4
7. Function Hoisting
Incase of function hoisting the complete function is hoisted in the scope, Unlike undefined variables.
displayName();
function displayName() {
console.log("Arjunan");
}
8. Function Hoisting O/P based question
Hoisting will happen here so x on outside will be 21. But while having function hoisting is happening, the var x inside that is also hoisted so it will be undefined. Since there is a local variable already present it will shadow the outer one. So output will be undefined.
var x = 21;
var fun = function () {
console.log(x);
var x = 20;
};
fun();
// undefined
9. Params v/s Arguments
function Square(num) { // Params
return num * num;
}
Square(5); // Arguments
10. Rest v/s Spread
Spread will open a array and Rest will combine a array
function add(...nums) { // Rest
return nums[0] + nums[1];
}
let arr = [1, 2]
add(...arr) // Spread
11. Params v/s Arguments - O/P based question
function fn(a, ...nums, x, y) {
console.log(x, y);
}
fn(5, 6, 3, 7);
// Rest parameter must be last formal parameter
-----
function fn(a, x, y, ...nums) {
console.log(a, x, y)
console.log(nums)
}
fn(5, 6, 3, 7);
5 6 3
[ 7 ]
12. Callback Functions
You can call function when you want to. Map, Filter, Reduce, setTimeout, addEventListener all take callback functions.
document.addEventListener("click", () => {});
13. Arguments in Arrow and Normal Functions
function ShowArgs() {
console.log(arguments);
}
ShowArgs(1, 2, 3);
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
const ShowArgsArrowFn = () => {
console.log(arguments);
};
ShowArgsArrowFn(1, 2, 3);
// ReferenceError: arguments is not defined