YouTube Icon

Interview Questions.

Top 100+ Javascript Advanced Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Javascript Advanced Interview Questions And Answers

Question 1. What Is The Difference Between Undefined And Not Defined In Javascript?

Answer :

In JavaScript, if you attempt to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var call isn't defined and script will forestall executing. However, if you use typeof undeclared_variable, then it'll go back undefined.

Before getting in addition into this, let's first recognize the distinction among assertion and definition.

Let's say var x is a announcement because you have not described what value it holds yet, however you have got declared its life and the want for reminiscence allocation.

> var x; // maintaining x
> console.Log(x); //output: undefined 

Here var x = 1 is each a declaration and definition (additionally we can say we're doing an initialisation). In the instance above, the announcement and undertaking of price take place inline for variable x. In JavaScript, every variable or characteristic assertion you deliver to the pinnacle of its modern-day scope is referred to as hoisting.

The assignment takes place so as, so whilst we try to get admission to a variable this is declared however now not defined but, we will get the result undefined.

Var x; // Declaration
if(typeof x === 'undefined') // Will go back true

If a variable that is neither declared nor described, while we strive to reference this kind of variable we'd get the result not defined.

> console.Log(y);  // Output: ReferenceError: y isn't always described

Question 2. What Will Be The Output Of The Code Below?
Var Y = 1;
if (characteristic F())

y += Typeof F;

console.Log(y);

Answer :

The output could be 1undefined. The if condition statement evaluates the usage of eval, so eval(characteristic f()) returns function f() (that is real). Therefore, within the if statement, executing typeof f returns undefined due to the fact the if statement code executes at run time, and the statement inside the if condition is evaluated at some point of run time.

 Var okay = 1;
  if (1)

    eval(feature foo());
    k += typeof foo;
  
console.Log(ok); 
The code above will even output 1undefined.
 Var ok = 1;
  if (1)

    feature foo();
    ok += typeof foo;
  
  console.Log(k); // output 1function

CSS3 Interview Questions
Question three. What Is The Drawback Of Creating True Private Methods In Javascript?

Answer :

One of the drawbacks of making real non-public strategies in JavaScript is that they may be very reminiscence-inefficient, as a brand new replica of the method could be created for every instance.

Var Employee = feature (call, agency, revenue)

    this.Call = call attribute default cost is null
    this.Company = employerattribute default price is null
    this.Profits = salaryattribute default fee is null
    // Private method
    var increaseSalary = function ()

        this.Earnings = this.Revenue + one thousand;
;
    // Public technique
    this.DispalyIncreasedSalary = function()

        increaseSlary();
        console.Log(this.Earnings);
 ;
;

// Create Employee magnificence item
var emp1 = new Employee("John","Pluto",3000);
// Create Employee elegance object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);
Here each example variable emp1, emp2, emp3 has its personal copy of the increaseSalary non-public method.
So, as a recommendation, don’t use non-public techniques except it’s necessary.

Question 4. What Is A “closure” In Javascript? Provide An Example

Answer :

A closure is a function defined interior some other feature (referred to as the discern feature), and has get right of entry to to variables that are declared and described within the figure characteristic scope.

The closure has get entry to to variables in 3 scopes:

Variables declared of their very own scope
Variables declared in a discern function scope
Variables declared in the global namespace
var globalVar = "abc";
// Parent self invoking function 
(characteristic outerFunction (outerArg)  // begin of scope outerFunction
    // Variable declared in outerFunction characteristic scope 
    var outerFuncVar = 'x';    
    // Closure self-invoking function 
    (feature innerFunction (innerArg)  // start of scope innerFunction
        // variable declared in innerFunction feature scope
        var innerFuncVar = "y"; 
        console.Log(          
            "outerArg = " + outerArg + "n" +
            "outerFuncVar = " + outerFuncVar + "n" +
            "innerArg = " + innerArg + "n" +
            "innerFuncVar = " + innerFuncVar + "n" +
            "globalVar = " + globalVar);
     // give up of scope innerFunction)(5); // Pass 5 as parameter 
// stop of scope outerFunction )(7); // Pass 7 as parameter 

innerFunction is closure this is described interior outerFunction and has get entry to to all variables declared and described within the outerFunction scope. In addition, the characteristic defined inner some other feature as a closure will have get admission to to variables declared in the global namespace.

Thus, the output of the code above could be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

CSS3 Tutorial
Question 5. Write A Mul Function Which Will Produce The Following Outputs When Invoked?

Answer :

console.Log(mul(2)(3)(four)); // output : 24 

console.Log(mul(four)(three)(four)); // output : 48

Below is the answer accompanied via a proof to the way it works:

feature mul (x)

    go back feature (y)
 // nameless characteristic 

        return characteristic (z)
 // anonymous feature 
            go back x * y * z; 
        ;
    ;


Here the mul function accepts the first argument and returns an nameless characteristic, which takes the second parameter and returns any other anonymous feature a good way to take the 1/3 parameter and go back the multiplication of the arguments which have been surpassed.

In JavaScript, a function defined inner another one has get right of entry to to the outer function's variables. Therefore, a characteristic is a first-rate object that may be returned by other features as well and be handed as an issue in any other function.

A characteristic is an example of the Object kind
A characteristic may have residences and has a hyperlink lower back to its constructor approach
A characteristic can be saved as a variable
A function can be pass as a parameter to some other function
A feature may be again from another function
HTML five Interview Questions
Question 6. How To Empty An Array In Javascript?

Answer :

For example,

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

How are we able to empty the array above?

There are a couple approaches we are able to use to empty an array, so allow's talk all of them.

Method 1 :

arrayList = []

Above code will set the variable arrayList to a new empty array. This is usually recommended in case you don't have references to the authentic array arrayList everywhere else, because it will clearly create a brand new, empty array. You must be careful with this technique of emptying the array, due to the fact when you have referenced this array from every other 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 using another variable 

arrayList = []; // Empty the array 

console.Log(anotherArrayList); // Output ['a','b','c','d','e','f']

Method 2 : 

arrayList.Duration = zero;

The code above will clean the prevailing array by placing its length to zero. This manner of emptying the array additionally updates all the reference variables that point to the original array. Therefore, this technique is useful while 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 with the aid of some other variable 

arrayList.Length = zero; // Empty the array by way of placing duration to zero

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

Method three : arrayList.Splice(zero, arrayList.Duration);

The implementation above can even work flawlessly. This way of emptying the array will also update all of the references to the authentic array.

Var arrayList = ['a','b','c','d','e','f']; // Created array 

var anotherArrayList = arrayList;  // Referenced arrayList through every other variable 

arrayList.Splice(zero, arrayList.Duration); // Empty the array through putting length to 0

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

Method four :

while(arrayList.Length)

  arrayList.Pop();


The implementation above also can empty arrays, but it also includes no longer endorsed to apply this method frequently.

Question 7. How Do You Check If An Object Is An Array Or Not?

Answer :

The satisfactory way to find out whether or no longer an object is an instance of a specific elegance is to use the toString method from Object.Prototype:

  var arrayList = [1,2,3];

One of the pleasant use instances of type-checking an item is whilst we do method overloading in JavaScript. For instance, shall we say we've got a technique called greet, which takes one unmarried string and also a list of strings. To make our greet technique practicable in both situations, we need to recognise what type of parameter is being surpassed. Is it a single price or a listing of values?

 Feature greet(param)

  if()
 // right here have to test whether or not param is array or not 
  
else

  
 

However, because the implementation above may not necessarily take a look at the kind for arrays, we are able to check for a single fee string and positioned some array common sense code within the else block. For instance:

 function greet(param)

  if(typeof param === 'string')
 
  
else

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

Now it is satisfactory we are able to go together with either of the aforementioned  implementations, however whilst we have a scenario where the parameter may be single fee, array, and object type, we can be in hassle.

Coming again to checking the form of an item, as noted formerly we can use Object.Prototype.ToString

if( Object.Prototype.ToString.Name( arrayList ) === '[object Array]' )

    console.Log('Array!');

If you're using jQuery, then you may also use the jQuery isArray approach:
  if($.IsArray(arrayList))

    console.Log('Array');
  
else

  console.Log('Not an array');
  

FYI, jQuery makes use of Object.Prototype.ToString.Call internally to check whether an item is an array or not. In contemporary browsers, you can additionally use

Array.IsArray(arrayList);

Array.IsArray is supported by using Chrome five, Firefox 4.0, IE 9, Opera 10.Five and Safari five

HTML five Tutorial PHP Interview Questions
Question 8. What Will Be The Output Of The Following Code?
Var Output = (function(x)
    
Delete X;    
go back X;  

)(zero);
console.Log(output);

Answer :

The output might be zero. The delete operator is used to delete homes from an object. Here x isn't always an object however a neighborhood variable. Delete operators don't affect local variables.

Question nine. What Will Be The Output Of The Following Code?
Var X = 1;
var Output = (characteristic()
    
Delete X;    
Return X;
  
)();
 console.Log(output);

Answer :

The output could be 1. The delete operator is used to delete the belongings of an item. Here x isn't always an object, but rather it is the worldwide variable of kind number.

AJAX Interview Questions
Question 10. What Will Be The Output Of The Code Below?
Var X =  Foo : 1;
var Output = (characteristic()

delete X.Foo;
return X.Foo;

)();
console.Log(output);

Answer :

The output might 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 feature, we are able to delete the foo property from object x. After doing so, while we strive to reference a deleted belongings foo, the end result isundefined.

PHP Tutorial
Question 11. What Will Be The Output Of The Code Below?
Var Employee =

organisation: 'xyz'

var Emp1 = Object.Create(employee);
delete Emp1.Employer Console.Log(emp1.Agency);

Answer :

The output could be xyz. Here, emp1 item has company as its prototype assets. The delete operator would not delete prototype belongings.

Emp1 object would not have business enterprise as its personal assets. You can take a look at it console.Log(emp1.HasOwnProperty('agency')); //output : fake. However, we can delete the employer belongings at once from theEmployee item using delete Employee.Company. Or, we also can delete the emp1 item using the __proto__ property delete emp1.__proto__.Agency.

HTML+Javascript Interview Questions
Question 12. What Is Undefined X 1 In Javascript?

Answer :

var trees = ["redwood","bay","cedar","oak","maple"];

delete trees[3];

When you run the code above and sort console.Log(timber); into your Chrome developer console, you may get ["redwood", "bay", "cedar", undefined × 1, "maple"]. When you run the code in Firefox's browser console, you'll get ["redwood", "bay", "cedar", undefined, "maple"]. Thus, it is clean that the Chrome browser has its own manner of showing uninitialised indexes in arrays. However, when you test timber[3] === undefined in both browsers, you will get similar output as true.

CSS3 Interview Questions
Question 13. What Will Be The Output Of The Code Below?
Var Trees = ["xyz","xxxx","test","ryan","apple"];
delete Trees[3];
console.Log(trees.Length);

Answer :

The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even in case you deleted all factors of an array the usage of the delete operator.

In different words, when the delete operator removes an array element, that deleted element is not longer present in array. In location of price at deleted index undefined x 1 in chrome and undefined is placed on the index. If you do console.Log(bushes) output ["xyz", "xxxx", "test", undefined × 1, "apple"] in Chrome and in Firefox ["xyz", "xxxx", "test", undefined, "apple"].

AJAX Tutorial
Question 14. If We Have A Javascript Associative Array
Var Counterarray =

A : three,
b : four
;
Counterarray["c"] = 1;
how Can We Calculate The Length Of The Above Associative Array's Counter Array?

Answer :

There aren't any in-built capabilities and properties to be had to calculate the length of associative array object right here. However, there are other methods through which we will calculate the period of an associative array object. In addition to this, we can also enlarge an Object by way of adding a way or assets to the prototype with a view to calculate period. However, extending an object would possibly spoil enumeration in diverse libraries or may create go-browser troubles, so it is now not endorsed except it's essential. Again, there are numerous approaches with the aid of which we are able to calculate length.

Object has the keys approach which may be used to calculate the period of an object:

 Object.Keys(counterArray).Duration // Output 2 

We also can calculate the duration of an item by using iterating through an object and by means of counting the object's very own property.

Function getSize(object)

  var depend = 0;
  for(key in object)

    // hasOwnProperty approach check personal assets of object
    if(object.HasOwnProperty(key)) be counted++;
  
  go back matter;

We also can add a length technique immediately on Object:
  Object.Duration = feature()

  var depend = zero;
  for(key in item)

    // hasOwnProperty technique test personal assets of item
    if(object.HasOwnProperty(key)) be counted++;
  
  go back rely;
  
  //Get the dimensions of any item using
  console.Log(Object.Duration(counterArray))

Question 15. What Is The Instanceof Operator In Javascript? What Would Be The Output Of The Code Below?
Feature Foo()

go back Foo;

new Foo() Instanceof Foo;

Answer :

Here, instanceof operator tests the contemporary object and returns genuine if the item is of the specified type.

For Example:
var dog = new Animal();

canine instanceof Animal // Output : true

Here dog instanceof Animal is actual due to the fact dog inherits from Animal.Prototype.

 Var name = new String("xyz");

 call instanceof String // Output : authentic

Here name instanceof String is real due to the fact that canine inherits from String.Prototype. Now allow's understand the code under:

feature foo()
 
  go back foo; 


new foo() instanceof foo;

Here characteristic foo is returning foo, which again factors to function foo.

Function foo()
 
  go back foo; 

var bar = new foo();

// here bar is pointer to feature foo()go back foo.

So the brand new foo() instanceof foo return fake;

CSS Advanced Interview Questions
Question 16. What Will Be The Output Of Code Below?
Var Salary = "one thousand$";
(function ()

console.Log("unique Salary Was " + Salary);
var Salary = "5000$";
Console.Log("my New Salary " + Salary);

)();

Answer :

The output would be undefined, 5000$. Newbies frequently get tricked by JavaScript's hoisting idea. In the code above, you is probably looking ahead to earnings to hold its fee from the outer scope until the factor that profits receives re-declared within the internal scope. However, because of hoisting, the earnings fee turned into undefined rather. To understand this better, have a glance of the code under:

 var revenue = "one thousand$";

 (feature ()

     var revenue = undefined;
     console.Log("Original salary turned into " + salary);
     salary = "5000$";
     console.Log("My New Salary " + profits);
 
)();

revenue variable is hoisted and declared at the top within the feature's scope. The console.Log internal returns undefined. After the console.Log, salary is redeclared and assigned 5000$.

CSS Advanced Tutorial
Question 17. What Is Function Hoisting In Javascript?
Feature Expression
 var Foo = Function Foo()
   
return 12; 
 ; 

Answer :

In JavaScript, variable and capabilities are hoisted. Let's take function hoisting first. Basically, the JavaScript interpreter looks in advance to find all variable declarations and then hoists them to the top of the characteristic where they may be declared. For example:

 foo(); // Here foo continues to be undefined 

 var foo = characteristic foo()
 
  return 12; 
 ; 

Behind the scene of the code above looks as if this:

  var foo = undefined;

     foo(); // Here foo is undefined 

    foo = characteristic foo()

       / Some code stuff
      
   var foo = undefined;
    foo = function foo()

       / Some code stuff
      
      foo(); // Now foo is described here.

Java Abstraction Interview Questions
Question 18. What Is The Difference Between The Function Declarations Below?
 Var Foo = Function() 
  // Some Code
 ; 
  Function Bar() 
  // Some Code
 ; 

Answer :

The principal distinction is the feature foo is defined at run-time whereas function bar is defined at parse time. To recognize this in better manner, permit's take a look at the code under:

Run-Time characteristic declaration 

 Another benefit of this primary-one manner of declaration is that you could declare capabilities based totally on sure conditions. For instance:

 However, if you try and run comparable code the usage of the layout under, you'll get an errors:

HTML 5 Interview Questions
Question 19. What Will Be The Output Of The Code Below?
 // Nfe (named Function Expression 
 var Foo = Function Bar()

return 12;
;
 typeof Bar();  

Answer :

The output might be Reference Error. To make the code above paintings, you may re-write it as follows:

Sample 1

 var bar = characteristic()

return 12;
;
 typeof bar();  

or

Sample 2

 feature bar()

go back 12;
;
 typeof bar();  

A characteristic definition can have best one reference variable as its feature call. In pattern 1, bar's reference variable points to nameless function. In pattern 2, the feature's definition is the call feature.

 Var foo = feature bar()
 
    // foo is visible right here 
    // bar is visible right here
  console.Log(typeof bar()); // Work here :)
 ;
 // foo is seen here
 // bar is undefined here

Javascript Objects Tutorial
Question 20. What Will Be The Output Of The Code Below?
Var Z = 1, Y = Z = Typeof Y;
console.Log(y);

Answer :

The output might be undefined. According to the associativity rule, operators with the equal priority are processed primarily based at the associativity property of the operator. Here, the associativity of the undertaking operator is Right to Left, so typeof y will evaluate first , that's undefined. It might be assigned to z, and then y might be assigned the cost of z and then z might be assigned the value 1.

Javascript Objects Interview Questions
Question 21. What Will Be The Output Of The Code Below?
Var Bar = True;
console.Log(bar + zero);
console.Log(bar + "xyz");
console.Log(bar + True);
console.Log(bar + False);

Answer :

The code will output 1, "truexyz", 2, 1. Here's a trendy guiding principle for addition operators:

Number + Number -> Addition
Boolean + Number -> Addition
Boolean + Number -> Addition
Number + String -> Concatenation
String + Boolean -> Concatenation
String + String -> Concatenation




CFG