Important JavaScript Concepts You MUST Know

#1: Closures:

Closure in layman’s terms is simply a function inside a function, also called nested function. It looks pretty straightforward when we see it like this but the real magic is related to its scopes. A closure has three scopes, nested function has access to variables defined in its own scope, in the scope of its parent function and the global variables. This behavior of closures can be very handy when It comes to programming in Javascript. One of all the benefits of this is the abstraction, as we all know that Javascript is not pure class based Object Oriented Programming language like Java and C# but we can achieve this OO behavior through……. YESS! → Closures. Consider the following code sample:

function foo() {
  var firstName = "design";			//property
  var lastName = "code";				// property
  var getFullName = function() {	//method
    return firstName + " " + lastName;
	//this return works like an access modifier
	//only getFullName() method is accessable of foo object
  return {		
    getFullName: getFullName

var object = foo();

In the code above you can see that the getFullName() function has the access to the outer function’s firstName and lastName properties and we can think of var object as an Object having these two properties and getFullName() a method as in an OOP language. The other important thing to notices here is that we can’t access the properties here, no matter they are part of foo, the reason behind this is the return statement, we have only given access to the method not the properties. It kind of works like the access modifiers of OOP language, to make that code work, we have to do something like this:


One very important thing you guys might have noticed is that after foo() statement is executed in the previous code snippet, variables inside the foo() function will not be destroyed (unlike other functions when they return, their variables are destructed) because of closures as the scope is kept alive here and child function can still access the properties of parent function.

#2: Prototype Inheritance:

Inheritance is the well-known concept in programming and has its many benefits like reusability, minimize duplicate code, easy and flexibility in changing code, extensibility and many more.

Every javascript object (standard JS objects, functions and custom objects) has a prototype. The prototype is also an object and these objects inherit their methods and properties from. We can create a JS prototype through a constructor function (In JS, functions are also objects). A constructor function has the following syntax:

function Person(fName, lName, age)
this.fName = fName;
this.lName = lName;
this.age = age;

var emp = new Person('Design','Code',25);
var stu = new Person('Bharat','Bhushan',30);                 

We can also do Person.prototype.region = ‘Asia’ and the region property will also be inherited by all objects of Person prototype.

Date.prototype.myFormat = function() {

  return this.getDate() + '/' + (this.getMonth() + 1) + '/' + this.getFullYear();

var date = new Date();

Prototype inheritance can be used to extend standard JavaScript objects as well. Like the code sample on left, will print date in DD/MM/YYYY format.

#3: Hoisting

Variable hoisting is a concept that most of the developers fail to notice which leads to unexpected results in the script. In JS, the interpreter move any variable and function declaration to top of the current scope (function scope or global scope). You might have noticed that we can call a function in JS before it is defined (viewing from top to bottom), the reason behind this is hoisting. Consider the following code example:



function foo() {

var abc = 20;

//ouput will be 10 undefined                 

As you can see we can call the foo function no matter it is defined later in the script and also console.log(abc) printed undefined instead of giving ‘Uncaught Reference’ not defined exception as abc is actually defined later and it was moved to top of the scope before execution. Just the declaration part (var abc) is hoisted not the assignment part(=20). That is why undefined is printed. Not knowing of this concept can lead to unexpected errors that can be difficult to handle.

#4: Single threaded JS & Event Loop

Once an interviewer asked me that “Is Javascript Multi threaded or Single threaded”, I said Single. He then asked, “Then how the ASYNC calls are handled and the UI thread is responsive during the call”, I couldn’t answer then.

The fact is that Javascript is actually single threaded, each tab or window runs a single JS thread. JS engine manages a queue of events to which events are enqued and dequed, when an async call is sent through ajax and its response is received, an event is pushed into that event queue. These events are also pushed for button clicks handlers, time outs or key press handler etc. JS thread keeps on checking that queue when thread is idle and there is nothing to execute, if there is something in the queue, it pops it out and execute. To make it simple to understand just say that there is a queue of unprocessed events and a loop that iterates over this queue and execute the event handlers of those events one by one. The single threaded behavior can be understood by the example that there are two events in the event queue for ajax response received and one for a mouse over, but we are executing an infinite loop in the current JS thread, those callbacks will not get a chance to run no matter their time has come and will always be executed when the thread is idle.

#5: Callbacks:

Callbacks is a very important concept in javascript as it can be very handy in many scenarios. A callback is simply a function that is passed to another function as a parameter and is invoked or executed inside the other function. This might not seem helpful now but it will be pretty clear after the following example. Suppose there is a function that takes a studentId as a parameter and returns the employee object returned from the server based on that Id and we have to show that student returned from this function, on screen.

function getStudentById(id) {
  var student = null;

    url: "/Student/getById/" + id,
    type: "GET",
    success: function(std) {
    student = std;
    error: function() {
      console.log("error occurred.");

  return student;

It looks fine when we see it but there is a problem when we execute it. The problem is the function returns a null and the reason behind is that ajax call is asynchronous and executed separately waiting for the result from the server and meanwhile function returns the same null value that we assigned earlier.

Here comes the callbacks. The simplest solution to this problem is passing a callback that is invoked when the result arrives from server. After doing that the code will look something like this:

// our callback function that we want to execute when result comes
var callback = function showStudentDetail(student) {		
        // Do manipulate the student object here
    document.getElementsByTagName("P")[0].innerHTML +=;

function getStudentById(id, callback) {
                url: "http://localhost:29506/Home/getById/"+id,
                type: "GET",
                success: function (student) {
                error: function () {
                    console.log("error occurred.");
//sample execution code
getStudentById(123, callback);                 

Callback solved our problem but let just think for a second that we just handled the success scenario not the failure, for that we will have to pass another callback function (success and failure cases) and what if we want to execute two or more back to back async operations where each subsequent function starts when the previous one is completed. This can be easily handled with promises.

#6: Promises

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

The benefits of using promises are also described here at developer.mozilla:

* We can do chaining with promises i.e. executing two or more asynchronous operations back to back

* Callbacks will never be called before the completion of the current run of the JavaScript event loop

* Callbacks added with .then even after the success or failure of the asynchronous operation, will be called

* Multiple callbacks may be added by calling .then several times, to be executed independently in insertion order

We will discuss some of these concepts later. But first create our own promise and convert the previous getStudentById() code to return a promise and then attach our callbacks to that.

function getStudentById(id) {

  return new Promise(function(resolve, reject) {

      url: "/Student/getById/" + id,
      type: "GET",
      success: function(std) {
      error: function() {
        reject("error occurred.");


var successCallback = function(student) {
var failureCallback = function(error) {

getStudentById(100).then(successCallback, failureCallback)                 

In code above, in case of success, we resolve the promise and pass data from server to resolve which eventually passes to successCallback and invoke attached callback, and incase of failure, promise will be rejected and failureCallback will be invoked. One of the benefits of using promises is that, lets suppose we want to do two asynchronous operations and the second operation is dependent on the result of first operation. It can be done easily with promises like this:

return secondOperation(resultFromFirst);
// do something else with this result

The second operation will be executed after the first one is completed and firstOnes result will be passed to the second. This is called Chaining in promises and is one of significant benefits of promises. Another advantageous use case of promises is, let suppose we want to do something when all of our promises are resolved, we have to wait for all the promises to resolve and then perform some operation on the basis of results of all. We can do something like this:

var p1 = getStudentById(10);
var p2 = getStudentById(102);
var p3 = getStudentById(103);

Promise.all([p1, p2, p3]).then(function(students) {
  console.log("All the students are here: " + students);

It is resolved when all the promises in the array are resolved and rejected when any of them is rejected. Modern functions (like Angular $http module) return promises, we just have to attach our callbacks to it and don’t need to write our own.

#7: Array Manipulation:

JS arrays provide a lot of handy functions that most of the guys don’t know. One of them is array filter(), the filter function takes a functions as a parameter, executes the function on each element of the array and returns a newly created array of the elements that passed the condition provided in the function, for example we have a student array:

var students = [{
  name: 'design code',
  age: 29
}, {
  name: 'bharat bhushan',
  age: 22
}, {
  name: 'code by bharat',
  age: 11

var studentAbove25 = students.filter(function(student) {
  return student.age > 25;

Another useful function is map(), while filter function is used to search or strain an array as the name suggests, map function is used to apply an operation on each element of array, it iterates over each element of array, applies the provided function just like filter and returns new array of all the elements after the provided operation. The very basic example is:

var array = [1,2,3,4];
var result ={
return element * 2;
//The result will be newly created array having 2,4,6,8 

We can concatenate javascript arrays using concat() method, it takes array to be concatenated as parameter and returns the new array while keeping the original ones unchanged. JS arrays can contain different types of data types like below:

var array1 = [1,2,3];
var array2 = [4,5,'six'];
var result = array1.concat(array2); // result will be: 1,2,3,4,5,six

These were some of the concepts that I learnt and considered should be shared with everybody to help them understand JS easily with practical examples. I hope this article might have helped you about learning something about JavaScript.

Comments System WIDGET PACK