0

Dear Readers,

Kindly find & share the  most interesting & common Interview Question for Java Script.

Question 1

  1. What is the difference between undefinedand not definedin JavaScript?

In JavaScript, if you try to use a variable that doesn’t exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined.

Before getting further into this, let’s first understand the difference between declaration and definition.

Let’s say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.

> var x; // declaring x

> console.log(x); //output: undefined

Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting.

The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined.

var x; // Declaration

if(typeof x === ‘undefined’) // Will return true

If a variable that is neither declared nor defined, when we try to reference such a variable we’d get the result not defined.

> console.log(y);  // Output: ReferenceError: y is not defined

Question 2

What will be the output of the code below?

var y = 1;

if (function f(){}) {

y += typeof f;

}

console.log(y);

The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.

var k = 1;

if (1) {

eval(function foo(){});

k += typeof foo;

}

console.log(k);

The code above will also output 1undefined.

var k = 1;

if (1) {

function foo(){};

k += typeof foo;

}

console.log(k); // output 1function

Question 3

What is the drawback of creating true private methods in JavaScript?

One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance.

var Employee = function (name, company, salary) {

this.name = name || “”;       //Public attribute default value is null

this.company = company || “”; //Public attribute default value is null

this.salary = salary || 5000; //Public attribute default value is null

// Private method

var increaseSalary = function () {

this.salary = this.salary + 1000;

};

// Public method

this.dispalyIncreasedSalary = function() {

increaseSlary();

console.log(this.salary);

};

};

// Create Employee class object

var emp1 = new Employee(“John”,”Pluto”,3000);

// Create Employee class object

var emp2 = new Employee(“Merry”,”Pluto”,2000);

// Create Employee class object

var emp3 = new Employee(“Ren”,”Pluto”,2500);

Here each instance variable emp1, emp2, emp3 has its own copy of the increaseSalary private method.

So, as a recommendation, don’t use private methods unless it’s necessary.

Question 4

What is a “closure” in JavaScript? Provide an example

A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.

The closure has access to variables in three scopes:

  • Variables declared in their own scope
  • Variables declared in a parent function scope
  • Variables declared in the global namespace

var globalVar = “abc”;

// Parent self invoking function

(function outerFunction (outerArg) { // begin of scope outerFunction

// Variable declared in outerFunction function scope

var outerFuncVar = ‘x’;

// Closure self-invoking function

(function innerFunction (innerArg) { // begin of scope innerFunction

// variable declared in innerFunction function scope

var innerFuncVar = “y”;

console.log(

“outerArg = ” + outerArg + “\n” +

“outerFuncVar = ” + outerFuncVar + “\n” +

“innerArg = ” + innerArg + “\n” +

“innerFuncVar = ” + innerFuncVar + “\n” +

“globalVar = ” + globalVar);

}// end of scope innerFunction)(5); // Pass 5 as parameter

}// end of scope outerFunction )(7); // Pass 7 as parameter

innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.

Thus, the output of the code above would be:

outerArg = 7

outerFuncVar = x

innerArg = 5

innerFuncVar = y

globalVar = abc

Question 5

Write a mul function which will produce the following outputs when invoked:

console.log(mul(2)(3)(4)); // output : 24

console.log(mul(4)(3)(4)); // output : 48

Below is the answer followed by an explanation to how it works:

function mul (x) {

return function (y) { // anonymous function

return function (z) { // anonymous function

return x * y * z;

};

};

}

Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed.

In JavaScript, a function defined inside another one has access to the outer function’s variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • A function can be stored as a variable
  • A function can be pass as a parameter to another function
  • A function can be returned from another function

Question 6

How to empty an array in JavaScript?

For instance,

var arrayList =  [‘a’,’b’,’c’,’d’,’e’,’f’];

How can we empty the array above?

There are a couple ways we can use to empty an array, so let’s discuss them all.

Method 1

arrayList = []

Above code will set the variable arrayList to a new empty array. This is recommended if you don’t have references to the original array arrayListanywhere else, because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.

For Instance,

var arrayList = [‘a’,’b’,’c’,’d’,’e’,’f’]; // Created array

var anotherArrayList = arrayList;  // Referenced arrayList by another variable

arrayList = []; // Empty the array

console.log(anotherArrayList); // Output [‘a’,’b’,’c’,’d’,’e’,’f’]

Method 2

arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.

For Instance,

var arrayList = [‘a’,’b’,’c’,’d’,’e’,’f’]; // Created array

var anotherArrayList = arrayList;  // Referenced arrayList by another variable

arrayList.length = 0; // Empty the array by setting length to 0

console.log(anotherArrayList); // Output []

Method 3

arrayList.splice(0, arrayList.length);

The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.

var arrayList = [‘a’,’b’,’c’,’d’,’e’,’f’]; // Created array

var anotherArrayList = arrayList;  // Referenced arrayList by another variable

arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0

console.log(anotherArrayList); // Output []

Method 4

while(arrayList.length){

arrayList.pop();

}

The implementation above can also empty arrays, but it is usually not recommended to use this method often.

Question 7

How do you check if an object is an array or not?

The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype:

var arrayList = [1,2,3];

One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let’s say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values?

function greet(param){

if(){ // here have to check whether param is array or not

}else{

}

}

However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block. For example:

function greet(param){

if(typeof param === ‘string’){

}else{

// If param is of type array then this block of code would execute

}

}

Now it’s fine we can go with either of the aforementioned two implementations, but when we have a situation where the parameter can be single value, array, and object type, we will be in trouble.

Coming back to checking the type of an object, as mentioned previously we can use
Object.prototype.toString

if( Object.prototype.toString.call( arrayList ) === ‘[object Array]’ ) {

console.log(‘Array!’);

}

If you are using jQuery, then you can also use the jQuery isArray method:

if($.isArray(arrayList)){

console.log(‘Array’);

}else{

console.log(‘Not an array’);

}

FYI, jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

In modern browsers, you can also use

Array.isArray(arrayList);

Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

Question 8

What will be the output of the following code?

var output = (function(x){

delete x;

return x;

})(0);

console.log(output);

The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don’t affect local variables.

Question 9

What will be the output of the following code?

var x = 1;

var output = (function(){

delete x;

return x;

})();

console.log(output);

The output would be 1. The delete operator is used to delete the property of an object. Here x is not an object, but rather it’s the global variable of type number.

Question 10

What will be the output of the code below?

var x = { foo : 1};

var output = (function(){

delete x.foo;

return x.foo;

})();

console.log(output);

The output would be undefined. The delete operator is used to delete the property of an object. Here, x is an object which has the property foo, and as it is a self-invoking function, we will delete the foo property from object x. After doing so, when we try to reference a deleted property foo, the result isundefined.

Question 11

What will be the output of the code below?

var Employee = {

company: ‘xyz’

}

var emp1 = Object.create(Employee);

delete emp1.company

console.log(emp1.company);

The output would be xyz. Here, emp1 object has company as its prototype property. The delete operator doesn’t delete prototype property.

emp1 object doesn’t have company as its own property. You can test it console.log(emp1.hasOwnProperty(‘company’)); //output : false. However, we can delete the company property directly from theEmployee object using delete Employee.company. Or, we can also delete the emp1 object using the __proto__property delete emp1.__proto__.company.