/

December 3, 2024

7 JavaScript Concepts That Every Web Developer Should Know

Basic concepts of JavaScript which are important to learn for any JavaScript developer

  1. Scope
  2. IIFE (Immediately Invoked Function Expression)
  3. Hoisting
  4. Closures
  5. Callbacks
  6. Promises
  7. Async & Await

 

1. Scope

Scope means variable access. 

Scope is simply a box with a boundary for variables, functions, and objects. 

A scope can be defined in three ways 

  • Local Scope: Variables declared within a function are accessible only within that function’s scope. This encapsulation prevents conflicts and unintended modifications from other parts of the code.
  • Global Scope: Variables declared outside of any function or block are in the global scope, accessible from anywhere within the program. However, relying too heavily on global variables can lead to code that’s harder to maintain and debug.
  • Block Scope: Introduced with the ‘let’ and ‘const’ keywords, block scope confines variables to the nearest enclosing pair of curly braces ‘{}’. This enhances code predictability and reduces the risk of variable hoisting, a behavior associated with the var keyword.
  • Block scope and local scope are almost the same.
  • In local scope, variables are typically defined within a function, while block scope is created within code blocks like if , for , or while statements. 
  • Var is recommended not to use because it can be accessed outside the function as well so let and const keywords are used in local and block scope.

Example: The code given below will give you an error because “title” is defined within the boundary (local scope) of the showtitle() function. You can not have access to this variable outside the function.

function showtitle() {
let title = “ProductTitle”;
}showtitle();
console.log( title );

 

Output : 

Uncaught ReferenceError: title is not defined

 

Example: Now, take a look at the code given below and see how you can access the variable “title” defined in the local scope.

function showtitle() {
let title = “ProductTitle”;console.log( title );
}

showtitle();

 

Output : 

ProductTitle

 

 

2. IIFE (Immediately Invoked Function Expression)

As the name suggests IIFE is a function in JavaScript which is immediately invoked and executed as soon as it is defined. Variables declared within the IIFE cannot be accessed by the outside world and this way you can avoid the global scope from getting polluted. So the primary reason to use IIFE is to immediately execute the code and obtain data privacy. 

Example: Below is the example.

let shapeType = ‘Circle’;
const shape = (() => {
return {
changeToSquare: () => {
shapeType = ‘Square’;
return shapeType;
},
changeToTriangle: () => {
shapeType = ‘Triangle’;
return shapeType;
}
};
})();console.log(shape.changeToSquare());

 

Output:

Square

 

 

3. Hoisting

In Javascript, you can call a function before it is defined and you won’t get an error ‘Uncaught ReferenceError’. The reason behind this is hoisting where the Javascript interpreter always moves the variables and function declaration to the top of the current scope (function scope or global scope) before the code execution. 

Example: here, we invoke our function before we declare it (with hoisting)

greet(‘Alice’);

function greet(name) {
console.log(‘Hello, ‘ + name + ‘!’);
}

 

Output:

Hello, Alice!

 

 

4. Closures

A closure is simply a function inside another function that has access to the outer function variable. The inner function (closure) can access the variable defined in its scope (variables defined between its curly brackets), in the scope of its parent function, and in the global variables. Now here you need to remember that the outer function can not have access to the inner function variable. 

Example:  Below is the example of closure.

const createCounter = () => {
let count = 0;
const increment = () => {
count++;
console.log(`Current count: ${count}`);
}
return increment;
}const counter = createCounter();
counter();
counter();
counter();

 

Output:

Current count: 1

Current count: 2

Current count: 3

 

 

5. Callbacks

In JavaScript, a callback is simply a function that is passed to another function as a parameter and is invoked or executed inside the other function. Here a function needs to wait for another function to execute or return a value and this makes the chain of the functionalities (when X is completed, then Y is executed, and it goes on.).

Example: Below is the example of callbacks

const addNumbers = (a, b) => {
console.log(`The sum of ${a} and ${b} is ${a + b}`);
}const processAddition = (callback) => {
const num1 = 5;
const num2 = 10;
callback(num1, num2);
}

processAddition(addNumbers);

 

Output:

The sum of 5 and 10 is 15

 

 

6. Promises

We understand the concept of callback but what will happen if your code will have callbacks within callbacks within callbacks and it goes on? Well, this recursive structure of callback is called ‘callback hell’ and promises to help to solve this kind of issue. Promises are useful in asynchronous JavaScript operations when we need to execute two or more back-to-back operations (or chaining callback), where each subsequent function starts when the previous one is completed. A promise is an object that may produce a single value some time in the future, either a resolved value or a reason that it’s not resolved (rejected). A promise may be in three possible states

  • Fulfilled: When the operation is completed successfully.
  • Rejected: When the operation fails.
  • Pending: initial state, neither fulfilled nor rejected.

Example: Let’s discuss how to create a promise in JavaScript with an example.

const emailPromise = new Promise((resolve, reject) => {
const isEmailValid = true;
if (isEmailValid) {
resolve(“Email is valid”);
} else {
reject(“Invalid email”);
}
});emailPromise
.then(result => console.log(result))
.catch(() => { console.log(‘Invalid email!’); });

 

Output:

Email is valid
Promise {<resolved>: undefined}

 

 

7. Async & Await

Stop and wait until something is resolved. Async & await is just like promises; it also provides a way to maintain asynchronous operation more synchronously. 

You can use Async/Await to perform the Rest API request where you want the data to fully load before pushing it to the view. For Node Js and browser programmers async/await is a great syntactic improvement. It helps the developer to implement functional programming in javascript and it also increases the code readability. 

To notify JS that we are working with promises we need to wrap ‘await’ inside an ‘async’ function.

Example: Below is the example.

const showUsers = async () => {
try {
const response = await fetch(‘https://jsonplaceholder.typicode.com/users’);
const users = await response.json();
console.log(users);
} catch (error) {
console.error(‘Error fetching users:’, error);
}
}showUsers();

 

Output:

 

From the same category