What is a Callback Function?
A callback function is a function that is passed as an argument to another function and is executed
after some operation has been completed. It allows functions to be executed asynchronously, which
is common in JavaScript, especially when dealing with tasks like API calls, reading files, or handling
events.
Example:
function greet(name) {
console.log('Hello ' + name);
function processUserInput(callback) {
const name = "John";
callback(name);
processUserInput(greet); // Output: "Hello John"
Scope
Scope in JavaScript refers to the visibility or accessibility of variables and functions in different parts
of your code. There are two main types of scope in JavaScript:
1. Global Scope: Variables declared outside of any function are in the global scope and can be
accessed from anywhere in the code.
Example:
let globalVar = "I am global";
function printGlobalVar() {
console.log(globalVar); // Can access the global variable
printGlobalVar(); // Output: "I am global"
2. Local Scope (Function Scope/Block Scope): Variables declared within a function or block {} are
local to that scope and cannot be accessed outside of it.
Example:
function testScope() {
let localVar = "I am local";
console.log(localVar); // Output: "I am local"
testScope();
Hoisting
Hoisting is a behavior in JavaScript where variable and function declarations are moved (or
"hoisted") to the top of their scope before the code execution. This means that variables and
functions can be used before they are declared in the code.
Example:
sayHello();
function sayHello() {
console.log('Hello World!');
// Output: "Hello World!"
Closure
A closure is a function that remembers and has access to its own lexical scope, even when the
function is executed outside that scope. Closures allow inner functions to remember the
environment (scope) in which they were created.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer Variable: ${outerVariable}`);
console.log(`Inner Variable: ${innerVariable}`);
};
const newFunction = outerFunction('outerValue');
newFunction('innerValue');
// Output:
// Outer Variable: outerValue
// Inner Variable: innerValue