Header Ads Widget

JavaScript Interview Questions for beginners and intermediate

Javascript is a scripting language. Without JavaScript an HTML page is dead. It helps in making a web page interactive. Different mouse or keys events and DOM manipulation allow in making the page dynamic. For a front-end developer is very important to be strong in Javascript. Below is the list of JavaScript question for beginners and intermediate developers.

Javascript interview question
  1. What are different data types in JavaScript?
  2. What is automatic type conversion in JavaScript?
  3. What is difference between var, let and const?
  4. What is strict mode in JavaScript and how is it enabled?
  5. What is hoisting?
  6. What is closure?
  7. What is difference between ==and ===?
  8. What is Template literals (string literals)?
  9. What is undefined and null? What is difference between them?
  10. How many ways you can write a function in JavaScript?
  11. What is callback function?
  12. What is callback hell?
  13. What is higer-Order function?
  14. How can you declare private members of a functions? Can we access private members outside of function?
  15. What is arrow function?
  16. What is Spread and Rest operators?
  17. What is Destructuring?
  18. How many ways you can create an Object in JavaScript?
  19. Can we compare 2 different Objects? How can we compare 2 different Objects?
  20. What is Pass by reference and pass by value?
  21. What is deep clone vs shallow clone of an Object?
  22. What is promise?
  23. What is CORS issue?
  24. What is Preflight Request or OPTIONS Method?
  25. What is function currying?
  26. What is method chaining? Write an example.
  27. What is event bubbling and capturing?
  28. What is differene between class and function?

1. What are different data types in JavaScript?

JavaScript is dynamic typing language. It means that we do not specify the type of variable. Javascript engine itself detect the value type and convert the variable to that type.

For example -
var a = 10; // typeof a in number
//when we reassign hello to a, it becomes String type.
a = "hello"; 

Below are the JavaScript types

  • undefined
  • boolean
  • number
  • string
  • object
  • function

2. What is automatic type conversion in JavaScript?

JavaScript is dynamic typing language. Javascript engine itself detect the value type and convert the variable to of that type. This is referred as automatic type conversion.

3. What is difference between var, let and const?

var, let and const are keywords in Javascript to declare variables. Though var exists from the beginning, let and const are introduced in ES6. Variables declared using var has a scope issue. It does not have block scope but function scope. Means a variable declared within an if block or withing curly braces will be accessible to the outside environment too. This leads to a variable collision. When javascript engines adopted ES6 they implemented let and const, the new way of declaring variables. Now let and const have a block-level scope. A variable declared using let and const within curly braces will have scope only within that block, and can not be accessed outside. let and const are same except we can't re-assign a variable declared using const.
const is generally used for creating constants.

4. What is strict mode in JavaScript and how is it enabled?

The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables. It eliminates silent errors and instead throws them so that the code won't run with errors in the code. introduced in ECMAScript 5. Now we have ES6 so do not use it.

5. What is hoisting?

JavaScript's moves all declarations to the top of the current scope. It is JavaScript's default behaviour. One of the benefits of hoisting is that it enables us to call functions before they appear in the code.

Example
console.log(a); // undefined > a is hoisted, that's why no error
var a = 10;

ES6 came with new keywords let and const. If we change above example let a = 10;, it will give reference error.

6. What is Closure?

Acording to Mozilla Developer guide - A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
In simple word- The child function can have access to the sccope of its outer environment, which means the child function can access the variables of the parent function. Now, the parent function variables are within the reach of the child function due to lexical scope. This concept is called closure.
To understand advance closure concept- Read This

function parent(){
	var a = 10;
    function child(){
    	console.log(a);
    }
}
parent()(); //output- 10

In the above example- when we access child() function outside parent function scope, it remembers its parent member because of closure.

7. What is difference between == and ===?

== is used to check if two values are equal are not, and === is used to check the eqality of value as well as its type. We can apply this on primitive values, it does not work on Objects. If we apply it on Objects it will just check their references not the values of object.

8. What is Template literals (string literals)?

Template literals has multi-line strings and string interpolation feature. Template literals (string literals) are used to create a string which can use expression within and also can remember its spaces and line breaks. We use apostrophe to create string literals.

 var literal = `1+2 = ${1+2}       I remember multiple space and 
      and line break too`;
//output- 1+2 = 3       I remember multiple space and 
      and line break too
      

9. What is undefined and null? What is difference between them?

undefined and null both means nothing. When we forget to assign a value to a variable it becomes undefined. However, We explicitely assign a null value to a vriables. While writing program sometime we assign null value to a variable.
One more difference is typeof null = "object" however typeof undefined = "undefined"

10. How many ways you can write a function in JavaScript?

  • Named Function
  • Annonymous Function
  • Self-invoking Function
      	//named function
        function helloWorld(){
        	console.log("hello World");
        }
        
        //Annonymous Function
        function(){
        	console.log("hello World");
        }
        
        //Self-invoking Function
        (function(){
        	console.log("hello World");
        })();
      

11. What is callback function?

JavaScript is a function language. We can pass function as argument to another function. Callback function is a function that is passed to another function as parameter. We can use callback function to create higer-Order function.

    function nameWithTitle(user, callback){
      if(user.gender ===”male”){
          return “Mr. ”+ callback(user.name)
      } else {
          return “Miss. ”+ callback(user.name)
      }
    }
    function printName(user){
        return user.name;
    }
    Var user = {name: “john”, gender: “male”}
    var withTitle  = nameWithTitle(user, printName);
    console.log(withTitle); //Output- Mr. John
    

12. What is callback hell?

    
    
    

13. What is higer-Order function?

Higher order function is a function which takes another function as argument and returns better version of it.

    var user = {
        name: 'John',
        gender: 'male',
    };
    
    function nameWithTitle(user, callback){
      if(user.gender ===”male”){
          return “Mr. ”+ callback(user)
      } else {
          return “Miss. ”+ callback(user)
      }
    }
    //nameWithTitle is higher order funnction which takes a callback function 
    //and returns better version of its callback
    
    function getName(user){
        return user.name; 
    }
	
    getName(user) ////output- John
    nameWithTitle(user, getName); //output- Mr. John
    

14. How can you declare private members of a function? Can we access private members outside of function?

All the variables declared using var, let and const within a function are private members, because they can not be accessed outside. But we can access them outside by explicitely returing them or by using child function (closure concept).

    function parent(){
      var privateMember = "I am private memner";
      function child(){
      	return privateMember;
      }
    }
    var c = parent();
    c(); //OUTPUT- I am private memner
    

15. What is arrow function?

Arrow function is ES6 feature to write functions in sort-hand way. It decreases no of lines of code. It also solve the context issue of the function. An arrow function do not have its own context, instead it uses parernt context. Context means- this keyword here.

16. What is Spread and Rest operators?

Rest Operator allows us to pass any number of parameters to a function without individually mentioning them. Using rest operator we can pass dynamic length of arguments. Before ES6, we used arguments keyword to achieve this.

//ES5 way  
    function sum(){
      var total = 0;
      for(var i = 0; i < arguments.length; i++) {
          total+= arguments[i];
      }	
      return total;	
    }
    sum(1,2,3); //output: 6
    sum(1,2,3,4,5); //output: 15
    
    //ES6 way - using rest operator
    function sum(...args){
      var total = 0;
      for(var i = 0; i < args.length; i++) {
        total+= args[i];
      }	
      return total;	
    }
    sum(1,2,3); //output: 6
    sum(1,2,3,4); //output: 10
      

Spread Operator is used to spread values of array, objects.

 
    var obj1 = {id: 1};
    var obj2 = {name: 'John'};
    var newObj = {...obj1, ...obj2}; // {id: 1, name: 'John'};

    var arr1 = [1,2];
    var arr2 = [3,4];
    var newArray = [...arr1, ...arr2]; //[1, 2, 3, 4];
      

spread operator is also used to create new array or object, it creates a deep copy of the object or array.
NOTE it create only one level of deep copy, if object or array is nested then it uses the reference of the child.

 
    var obj = {name: 'John', address: {house: 111, street: '4c'}};
    var shallowCopy = obj;
    var deepCopy = {...obj};
    obj === shallowCopy //true
    obj === deepCopy //false
    obj.address === deepCopy.address //true
      

17. What is Destructuring?

Destructuring is way to unpack the object or array. We can directly assign object properties to the corresponding variables in the left hand side.

      var user = {
          id: 42,
          name: 'Raj',
          is_verified: true
      };
      var {id, ...rest} = user; 
      // id is assigned to id, rest all assigned to rest
      
      console.log(id) //Output- 42
      console.log(rest) //Output- { name: 'Raj', is_verified: true}
      const [a, b ...c] = [1, 2, 3, 4];
      console.log(a); // 1
      console.log(b); // 2
      console.log(c); // [3, 4]
      
      //unpacking fields from object
      var user = {
        id: 42,
        age: 30,
        fullName: {
          firstName: 'John',
          lastName: 'Doe'
        }
      };

      function userId({id}) {
        return id;
      }

      /* firstName is now "aliasName" */
      function getDetail({id, age, fullName: {firstName: aliasName}}) {
        return `${aliasName} is ${age} year old`;
      }

      userId(user); //output- 42
      getDetail(user); //output- John is 30 year old
      

18. How many ways you can create an Object in JavaScript?

We can create Objects many ways, Below are the important ways-

  • function constructor
  • Class
  • Factory pattern
  • Object literal
  • Object.create() method
  • Object.assign() method

19. Can we compare 2 different Objects using equal operator? How can we compare the value of 2 different Objects?

We can’t compare 2 objects value by using equal operator. Equal operator only checks its reference not the value. If 2 object having same properties and values but different reference then it will return false.

 
    var obj1 = {id: 1};
    var obj2 = {id: 1}
    var objCopy = obj1;

    console.log(obj1 == obj2) // output- false
    console.log(obj1 == objCopy) // output- true
      

We can use JSON.stringify to crerate a deep copy of an object.
console.log(JSON.stringify(obj1) === JSON.stringify(obj2) ) //true

20. What is Pass by reference and pass by value?

When we pass any primitive value to a function as argument, it is the value which we pass not the reference. However when we pass any object or array we pass the reference of it not the value.

 
    function mutateArr(arg){
    	arg.length = 0;
    }
    var arr = [1, 2, 3];
    mutateArr(arr);
    console.log(arr); //output – []
    //Arrray is mutated in above example

    function mutateValue(id){
        id = 0;
    }
    var id = 5;
    mutateValue(id);
    console.log(id);// output- 5
    //id is not mutated 
      

21. What is deep clone vs shallow clone of an Object?

Deep copy of an object means- an object with unique memory address. Shallow copy means- an object points to a memory address of an existing object. Both points to same memory address. In case of shallow copy, If we change in any of the object the other object will also see that change. But a deep copy of an object does not affect other objects as it is has unique memory address.

 
    var obj1 = {id: 1};
    var shalowCopy = obj1; //shallow copy, it refers to obj1
    var deepCopy = JSON.parse(JSON.stringify(obj1)); //Deep copy, it referes to new memory address
      

22. What is promise?

A promise is an object that guarantee some value in the future. Value can either be a resolved value, or can be rejected value.

      function getApi(){
        return new Promise((resolve, reject) => {
          resolve(10);	
        })
      }
      //getApi() returns a promise which we can access later.
      var prom= getApi();
      prom.then(result => connsole.log(result)) // output- 10
      
      OR
      
      var promise = fetch('myapi/v2/user');
      //do something
      //......
      promise.
      	then(response => response.json()).
        	then(result => connsole.log(result));
      

23. What is CORS issue?

CORS - in known as cross origin resource sharing. In today's softwarer development industry we host our front-end and backend to differrent server unlike a monolithic app. Our backed api may be hosted at https://behostname.com/myapi. However, front-end can be at https://fehostname.com. Now fehostname is trying to access behostname. We can see that domain is different for both application. In this scenario we see CORS issue in browser. We can allow different origins to access the api by whitelisting them in the backend code. "Access-Control-Allow_Origin": "*" - this will allow any host to access the api.

24. What is Preflight Request or OPTIONS Method?

Pre-flight request is made by browsers as a safety and security measure to make sure that the request being made is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon. It is sent by the browser before the actual request. It contains information like HTTP method and HTTP headers. It tells the server waht the actual request looks like.

25. What is function currying?

When a function returns another function, we can innvoke the child funcion directly by using anohter set of parantheses. This way of pattern is called function currying.

      function parent(){
        console.log('this is parent')
        return function child(){
          console.log('this is child');
          return function grandChild(){
           console.log('this is grand child');
          }
        }
      }
      parent()() //this is function curry pattern > immediate execution of child
      //output- this is child
      
      parent()()() //this is function curry pattern > immediate execution of grandChild
      //output- this is grand child
      
      var grandChild = parent()(); // this is function curry patterrn > immediate execution of child which return grandchild
      grandChild() //output- this is grand child
      

In the above example we are returning child function from parent and grandChild funcion from child function. We can execute child and grand child function immediately by using another set of parantheses or we can hold their reference to another variable then execute them later.

26. What is method chaining? Write an example.

If a function returns an object which inernally holds methods then we can execute those method directly by putting a dot operator. In simple word a method chaining is (as name suggest) - Execution of methods in a chain by putting dot operator. In javascript when we put parantheses, it means we are trying to execute a function. So, if a function return an object and that object contains methods, we can use dot operator just after the parantheses and give any of the method name from returned object and use parantheses to execute that method. If we continnue this chain - we call it method chaining.

      function parent(){
      	var count= 0;
        var obj = {
        	increment: function(){
            	count++;
                return obj;
            },
            decrement: function(){
            	count--;
                return obj;
            },
            print: function(){
            	console.log("count ", count);
            }
        };
        return obj;
      }
      parent().increment().print()
      //output- count 1
 
      
      parent().increment().increment().increment().decrement().print()
      //output- count 2
      

In the above example we are using method chaining. parent function is returning an object. That object containing 3 methods increment, decrement and print. We can hold returned obejct in a variable something like- var result = parent(), result is having 3 properties- increment(function), decrement(function) and print(function). Now we can access the properties of result object using dot operator, soemthing like this- result.increment(). It will invoke increment method. But, instead of holding the returned value to a variable we can directly use dot operator and execute the methods of return object like we have done in the example.
NOTE- Once we execute print method, we can't use method chaining as it is not returning object with methods.

27. What is event bubbling and capturing?

Javascript is evennt based language. When we click any button a event is generated and starrt propogating towards to root of the element. This event propogation towards root is called event bubbling. Rreverse of it is called event capturing (From root to the target elemennt).

28. What is difference between class and function?

Class is new way of creating constructor in Javascript. It encapsulates the data and implementation within the class, it hides implementation from outer environment. It is just a syntactical sugar on the top of function. When a ES6 class is transpiled, it is converted to ES5. An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not

Post a Comment

0 Comments