JavaScript is a programming language that is primarily used to create interactive front-end web applications. It is a client-side scripting language, which means that it is executed by the user's web browser rather than the server. JavaScript can be used to create things like interactive forms, dynamic content, and animations. It is also commonly used to create single-page applications, which are web applications that load a single HTML page and dynamically update the content as the user interacts with the page. JavaScript is supported by all major web browsers and is a fundamental part of web development.
Scope: JavaScript has function scope, which means that variables are only accessible within the function they are defined in. Variables defined outside of any function have global scope, which means they are accessible anywhere in the code.
In JavaScript, variables declared with the
var
keywords are function scoped, which means they are only accessible within the function in which they are declared. Variables declared with thelet
andconst
keywords are block-scoped, which means they are only accessible within the block in which they are declared.A block is a piece of code wrapped in curly braces {} . For example, in a for loop or if statement.
It's important to be mindful of the scope of variables in JavaScript because if a variable is not in the correct scope, it can lead to unexpected behavior or errors in the code.
Local Scope allows access to everything within the boundaries (inside the box)
Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in the local scope because it is enclosed from the outer world, except if you return it.
JavaScript also has a concept of closure, which allows a function to remember the scope in which it was created, even if that scope no longer exists. This can be used to create private variables or to keep a reference to a specific scope.
// Global scope
let globalVariable = "This is a global variable";
function myFunction() {
// Function scope
let functionVariable = "This is a function variable";
console.log(globalVariable); // "This is a global variable"
if (true) {
// Block scope
let blockVariable = "This is a block variable";
console.log(functionVariable); // "This is a function variable"
}
console.log(blockVariable); // ReferenceError: blockVariable is not defined
}
console.log(functionVariable); // ReferenceError: functionVariable is not defined
console.log(globalVariable); // "This is a global variable"
In this example, the variable globalVariable
is defined in the global scope and is accessible from anywhere in the code. The variable functionVariable
is defined within the myFunction
function and is only accessible within that function. The variable blockVariable
is defined within an if statement and is only accessible within that block.
If you try to access a variable outside of its scope, you will get a ReferenceError. In this example, trying to access functionVariable
or blockVariable
outside of their respective scopes will result in an error.
It is important to keep in mind that JavaScript function scope, block scope and closure can make the code more complex and harder to debug if not used properly.
2. IIFE (Immediately Invoked Function Expression) :
An IIFE (Immediately Invoked Function Expression) is a function that is defined and immediately executed, without the need for an explicit function call. It is a common pattern in JavaScript that is used to create a private scope for variables and functions.
Here's an example of an IIFE:
(function () {
let privateVariable = "This variable is only accessible within the IIFE";
console.log(privateVariable);
})();
console.log(privateVariable); // ReferenceError: privateVariable is not defined
In this example, an anonymous function is defined and immediately invoked. The function is wrapped in parentheses ()
to indicate that it is a function expression, not a function statement. Inside the function, a variable privateVariable
is defined, which is only accessible within the IIFE. If you try to access the variable outside of the IIFE, you will get a ReferenceError.
- Hosting: Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope before the code is executed. This means that variables and functions can be used before they are declared, but they will be undefined or have the default value (for variables) until they are actually declared.
Here's an example of hoisting in JavaScript:
console.log(hoistedVariable); // undefined
var hoistedVariable = "This variable has been hoisted";
4. Closures :
In JavaScript, a closure is a function that has access to the variables and scope in which it was created, even if that scope no longer exists. This is achieved by creating a closure object, which contains a reference to the function and its scope.
Here's an example of a closure in JavaScript:
function makeCounter() {
let count = 0;
return function() {
return count++;
};
}
let counter = makeCounter();
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter()); // 2
5.Callbacks:
In JavaScript, a callback is a function that is passed as an argument to another function and is executed after the outer function has completed its task. Callbacks are often used to handle asynchronous operations such as network requests or user input events.
Here's an example of a callback in JavaScript:
function doSomething(callback) {
// Perform some task
let result = "Task completed";
callback(result);
}
doSomething(function(result) {
console.log(result); // "Task completed"
});
6.Promises:
In JavaScript, a promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises provide a way to handle asynchronous code in a more synchronous, readable way, without the need for callbacks.
Here's an example of a promise:
let promise = new Promise(function(resolve, reject) {
// Perform some async task
if (success) {
resolve(result);
} else {
reject(error);
}
});
promise.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error);
});
A promise may be in three possible states…
Fulfilled: When the operation is completed successfully.
Rejected: When the operation is failed.
Pending: initial state, neither fulfilled nor rejected
7. Async & Await:
async
and await
are JavaScript keywords that were introduced in ECMAScript 2017 (ES8) to make working with asynchronous code more synchronous, readable and easier to reason about. They are built on top of promises and allow you to write asynchronous code that looks and behaves similar to synchronous code.
async
is used before a function definition to indicate that the function will contain asynchronous code. It automatically returns a promise, so that the function can be used with .then()
and .catch()
Copy codeasync function myAsyncFunction() {
// Perform async task
let result = await somePromise();
return result;
}
myAsyncFunction()
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error);
});
await
is used inside an async
function to wait for a promise to resolve before moving on to the next line of code. It works by pausing the execution of the async
function, returning the resolved value of the promise, and resuming the execution once the promise is settled.
Copy codeasync function myAsyncFunction() {
let result = await somePromise();
// The next line of code will only execute once somePromise is resolved
console.log(result);
}
ES5 -> Callback
ES6 -> Promise
ES7 -> async & await.