7 JavaScript Concepts That Every Web Developer Should Know
JavaScript is Everywhere. Millions of web pages are built on JavaScript and it’s not going anywhere at least for now. On one side HTML and CSS give styling to the web pages but on the other side, it’s the magic of JavaScript that makes your web page alive. Today this language is not just limited to your web browser. You can also use it for server-side applications. Isn’t it cool to use a single language for both client-side and server-side applications? A single language fulfills both of the purposes and this is the main reason TONs of job postings are there for JavaScript developers in the tech industry.
According to the Stack Overflow Developer Survey 2019, JavaScript is the #1 programming language. The language is widely used by 95% of all websites Whether it’s a small startup or a big company, most of them are working on some kind of website or an app that requires a good knowledge of this language. A lot of frameworks and libraries are there for JavaScript. These frameworks and libraries can be easily learned if your JavaScript fundamentals are clear. A lot of concepts are confusing and overwhelming for developers but a good knowledge of these concepts will help you in the long run. Frameworks and libraries come and go but the fundamentals always remain the same. It’s easy to build any kind of application and learn any framework and libraries if the fundamentals are clear. Also, it will help you in interviews as well. Let’s discuss some of the basic concepts of JavaScript which are important to learn for any JavaScript developer. Become a good front-end developer with Geeksforgeeks JavaScript Foundation – Self-Paced and learn all the aspects of web development with ease.
These are the 7 Concepts
1. Scope
Scope means variable access. What variable do I have access to when a code is running? In JavaScript by default, you’re always in the root scope i.e. the window scope. The scope is simply a box with a boundary for variables, functions, and objects. These boundaries put restrictions on variables and determine whether you have access to the variable or not. It limits the visibility or availability of a variable to the other parts of the code. You must have a clear understanding of this concept because it helps you to separate logic in your code and also improves readability. 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.
More about block scope
Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of the showName() function. You can not have access to this variable outside the function.
NOTE: The code below shows an error due to a typo in the function call, causing an error before the intended scoping error is raised by the console.log call.
function showName() {
let name = "GeeksforGeeks";
}
showName();
console.log(name);
Output:
Uncaught ReferenceError: name is not defined
Example: Now, take a look at the code given below and see how you can access the variable “name” defined in the local scope.
function showName(){
let name = "GeeksforGeeks";
console.log(name);
}
showName();
Output:
GeeksforGeeks
Example: Here we will use block scope.
function fun() {
let a = 10;
console.log(a);
}
console.log(a);
Output:
Uncaught ReferenceError: a is not defined at <anonymous>:5:17
2. IIFE (Immediately Invoked Function Expression)
As the name suggests IIFE is a function in JavaScript which 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 paintColor = 'Red'
const paint = (() => {
return {
changeColorToBlue: () => {
paintcolor: 'Blue';
return paintColor;
},
changeColorToGreen: () => {
paintColor: 'Green';
return paintColor;
}
}
})();
console.log(
paint.changeColorToBlue()
);
Output:
Red
3. Hoisting
A lot of developers get unexpected results when they are not clear about the concept of hoisting in JavaScript. 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. Let’s understand this with an example.
Example: Take a look at the code given below.
function cowSays(sound) {
console.log(sound);
}
cowSays('moo');
Output:
moo
Example: here, we invoke our function before we declare it (with hoisting)
cowSays('moo');
function cowSays(sound) {
console.log(sound);
}
Output:
moo
4. Closures
A closure is simply a function inside another function that has access to the outer function variable. Now, this definition sounds pretty much straightforward but the real magic is created with the scope. 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 (we have already discussed this in the scope concept). Let’s take an example and understand it in a better way.
Example: Below is the example of closure.
const first = () => {
const greet = 'Hi';
const second = () => {
const name = 'john';
console.log(greet);
}
return second;
}
const newFunc = first();
newFunc();
Output:
Hi
In the above example, the inner function ‘second()’ is a Closure. This inner function will have access to the variable ‘greet’ which is part of the outer function ‘first()’ scope. Here the parent scope won’t have access to the child scope variable ‘name’.
Now the question is why do we need to learn closures? What’s the use of it? Closures are used when you want to extend behavior such as passing variables, methods, or arrays from an outer function to an inner function. In the above example, second() extends the behavior of the function first() and also has access to the variable ‘greet’.
JavaScript is not pure object-oriented language but you can achieve object-oriented behavior through closures. In the above example, you can think of const ‘newFunc’ as an Object having properties ‘greet’ and ‘second()’ a method as in an OOP language.
Here you need to notice that after the first() statement is executed, variables inside the first() function will not be destroyed (even if it has a ‘return’ statement) because of closures as the scope is kept alive here and the child function can still access the properties of the parent function. So closures can be defined in simple terms as “a function run, the function executed. It’s never going to execute again but it’s going to remember that there are references to those variables so the child scope always has access to the parent scope.”
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.). This is the reason callback is generally used in the asynchronous operation of JavaScript to provide the synchronous capability.
Example: Below is the example of callbacks
const greeting = (name) => {
console.log('Hello ' + name);
}
const processUserName = (callback) => {
name = 'GeeksforGeeks';
callback(name);
}
processUserName(greeting);
Output:
Hello GeeksforGeeks
In the above example notice that the greeting passed as an argument (callback) to the ‘processUserName’ function. Before the ‘greeting’ function is executed it waits for the event ‘processUserName’ to execute first.
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). According to the developer.Mozilla “A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.”. Promises resolve the issue of ‘callback hell’ which is nothing but a recursive structure of callbacks (callbacks within callbacks within callbacks and so forth).
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.
Example: Let’s discuss how to create a promise in JavaScript with an example.
const promise = new Promise((resolve, reject) => {
isNameExist = true;
if (isNameExist) {
resolve("User name exist")
} else {
reject("error")
}
})
promise.then(result => console.log(result)).catch(() => {
console.log(‘error!')
})
Output:
User name exist
Promise {<resolved>: undefined}
Consider the above code for a sample promise assumed like doing the ‘isNameExist’ operation asynchronously, In that promise Object arguments as two functions resolve and reject. If the operation is successful which means ‘isNameExist’ is ‘true’ then it will be resolved and display the output “User name exist” else the operation will be failed or be rejected and it will display the result ‘error !’. You can easily perform chaining operations in promises where the first operation will be executed and the result of the first operation will be passed to the second operation and this will be continued further.
7. Async & Await
Stop and wait until something is resolved. Async & await is just syntactic sugar on top of Promises and like promises it also provides a way to maintain asynchronous operation more synchronously. So in JavaScript asynchronous operations can be handled in various versions…
- ES5 -> Callback
- ES6 -> Promise
- ES7 -> async & await
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 Nodejs 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.
Example: Below is the example.
const showPosts = async () => {
const response = await fetch('https://jsonplacenolder.typicode.com/posts');
const posts = await response.json();
console.log(posts) ;
}
showPosts();
Output:
To notify JS that we are working with promises we need to wrap ‘await’ inside an ‘async’ function. In the above example, we (a)wait for two things: response and posts. Before we can convert the response to JSON format, we need to make sure we have the response fetched, otherwise we can end up converting a response that is not there yet, which will most likely prompt an error.
Imagine you’re in a tech interview, and you get a tough question. Stay calm and confident with Tech Interview 101 – From DSA to System Design. This course is perfect for computer science enthusiasts. You’ll learn all about Data Structures, Algorithms, and System Design with hands-on practice. Get the skills you need to succeed in any interview. Ready to land your dream job? Sign up today!