Top 15 Javascript Advanced Interview Questions
Q1. What Will Be The Output Of The Code Below?
Var Employee =
agency: 'xyz'
var Emp1 = Object.Create(employee);
delete Emp1.Business enterprise Console.Log(emp1.Corporation);
The output would be xyz. Here, emp1 item has company as its prototype assets. The delete operator does not delete prototype belongings.
Emp1 object would not have employer as its own assets. You can check it console.Log(emp1.HasOwnProperty('organization')); //output : fake. However, we are able to delete the employer property directly from theEmployee object the usage of delete Employee.Business enterprise. Or, we can also delete the emp1 item using the __proto__ belongings delete emp1.__proto__.Enterprise.
Q2. If We Have A Javascript Associative Array
Var Counterarray =
A : 3,
b : four
;
Counterarray["c"] = 1;
how Can We Calculate The Length Of The Above As
There are no in-constructed capabilities and residences available to calculate the length of associative array object here. However, there are other methods by way of which we will calculate the duration of an associative array object. In addition to this, we can also increase an Object by including a method or assets to the prototype so that you can calculate period. However, extending an object would possibly ruin enumeration in diverse libraries or might create pass-browser troubles, so it's no longer endorsed until it's essential. Again, there are numerous ways by means of which we will calculate period.
Object has the keys approach which can be used to calculate the length of an item:
Object.Keys(counterArray).Length // Output 2
We can also calculate the period of an item by iterating thru an item and with the aid of counting the object's personal belongings.
Function getSize(object)
var be counted = zero;
for(key in object)
// hasOwnProperty technique check own belongings of object
if(object.HasOwnProperty(key)) matter++;
go back rely;
We also can upload a duration approach directly on Object:
Object.Duration = characteristic()
var be counted = zero;
for(key in object)
// hasOwnProperty method test own property of item
if(item.HasOwnProperty(key)) depend++;
go back count;
//Get the scale of any object using
console.Log(Object.Length(counterArray))
Q3. What Will Be The Output Of The Code Below?
Var Z = 1, Y = Z = Typeof Y;
console.Log(y);
The output could be undefined. According to the associativity rule, operators with the identical priority are processed based totally on the associativity belongings of the operator. Here, the associativity of the task operator is Right to Left, so typeof y will evaluate first , which is undefined. It could be assigned to z, and then y could be assigned the fee of z and then z might be assigned the value 1.
Q4. How Do You Check If An Object Is An Array Or Not?
The first-class way to find out whether or now not an object is an instance of a specific class is to apply the toString method from Object.Prototype:
var arrayList = [1,2,3];
One of the first-class use instances of kind-checking an item is whilst we do method overloading in JavaScript. For instance, let's say we have a technique called greet, which takes one unmarried string and additionally a list of strings. To make our greet method conceivable in each situations, we want to recognize what kind of parameter is being surpassed. Is it a unmarried cost or a listing of values?
Characteristic greet(param)
if()
// here have to test whether or not param is array or no longer
else
However, because the implementation above may not always check the type for arrays, we can test for a single price string and positioned a few array common sense code within the else block. For instance:
characteristic greet(param)
if(typeof param === 'string')
else
// If param is of type array then this block of code might execute
Now it's first-class we will go with either of the aforementioned two implementations, however when we've a scenario wherein the parameter may be single fee, array, and object kind, we are able to be in problem.
Coming returned to checking the sort of an item, as stated previously we can use Object.Prototype.ToString
if( Object.Prototype.ToString.Name( arrayList ) === '[object Array]' )
console.Log('Array!');
If you're using jQuery, then you can 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.Name internally to test whether or not an item is an array or now not. In modern-day browsers, you may additionally use
Array.IsArray(arrayList);
Array.IsArray is supported through Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5
Q5. What Is Undefined X 1 In Javascript?
Var trees = ["redwood","bay","cedar","oak","maple"];
delete timber[3];
When you run the code above and kind console.Log(bushes); into your Chrome developer console, you will get ["redwood", "bay", "cedar", undefined × 1, "maple"]. When you run the code in Firefox's browser console, you will get ["redwood", "bay", "cedar", undefined, "maple"]. Thus, it's clear that the Chrome browser has its very own manner of showing uninitialised indexes in arrays. However, whilst you test bushes[3] === undefined in both browsers, you'll get similar output as authentic.
Q6. What Will Be The Output Of Code Below?
Var Salary = "1000$";
(feature ()
console.Log("authentic Salary Was " + Salary);
var Salary = "5000$";
Console.
The output could be undefined, 5000$. Newbies frequently get tricked by way of JavaScript's hoisting concept. In the code above, you might be expecting profits to maintain its cost from the outer scope until the point that revenue gets re-declared in the internal scope. However, because of hoisting, the profits price turned into undefined alternatively. To recognize this higher, have a look of the code under:
var salary = "1000$";
(characteristic ()
var revenue = undefined;
console.Log("Original profits turned into " + earnings);
earnings = "5000$";
console.Log("My New Salary " + profits);
)();
revenue variable is hoisted and declared on the pinnacle within the characteristic's scope. The console.Log interior returns undefined. After the console.Log, income is redeclared and assigned 5000$.
Q7. 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;
Here, instanceof operator checks the contemporary object and returns real if the object is of the specified type.
For Example:
var dog = new Animal();
canine instanceof Animal // Output : true
Here dog instanceof Animal is actual on account that dog inherits from Animal.Prototype.
Var name = new String("xyz");
name instanceof String // Output : proper
Here call instanceof String is true considering the fact that canine inherits from String.Prototype. Now let's understand the code underneath:
characteristic foo()
return foo;
new foo() instanceof foo;
Here feature foo is returning foo, which again factors to characteristic foo.
Feature foo()
return foo;
var bar = new foo();
// here bar is pointer to characteristic foo()go back foo.
So the brand new foo() instanceof foo go back fake;
Q8. What Will Be The Output Of The Code Below?
Var Bar = True;
console.Log(bar + 0);
console.Log(bar + "xyz");
console.Log(bar + True);
console.Log(bar + False);
The code will output 1, "truexyz", 2, @Here's a wellknown guiding principle for addition operators:
Number + Number -> Addition
Boolean + Number -> Addition
Boolean + Number -> Addition
Number + String -> Concatenation
String + Boolean -> Concatenation
String + String -> Concatenation
Q9. What Is The Difference Between Undefined And Not Defined In Javascript?
In JavaScript, if you try and use a variable that does not exist and has no longer been declared, then JavaScript will throw an mistakes var name is not defined and script will prevent executing. However, in case you use typeof undeclared_variable, then it's going to go back undefined.
Before getting similarly into this, allow's first understand the difference among announcement and definition.
Let's say var x is a announcement due to the fact you haven't described what cost it holds but, but you have 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 assertion and definition (additionally we are able to say we are doing an initialisation). In the example above, the assertion and challenge of cost show up inline for variable x. In JavaScript, every variable or characteristic declaration you carry to the top of its modern-day scope is called hoisting.
The venture happens so as, so when we try to get right of entry to a variable that is declared however not defined yet, we can get the result undefined.
Var x; // Declaration
if(typeof x === 'undefined') // Will go back real
If a variable this is neither declared nor described, while we attempt to reference one of these variable we would get the result now not defined.
> console.Log(y); // Output: ReferenceError: y isn't always defined
Q10. What Will Be The Output Of The Code Below?
Var Trees = ["xyz","xxxx","test","ryan","apple"];
delete Trees[3];
console.Log(timber.Length);
The output might be @When we use the delete operator to delete an array detail, the array period is not affected from this. This holds even if you deleted all factors of an array the use of the delete operator.
In other words, while the delete operator removes an array detail, that deleted detail is not longer present in array. In place of cost 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"].
Q11. What Is The Drawback Of Creating True Private Methods In Javascript?
One of the drawbacks of creating genuine personal methods in JavaScript is that they are very reminiscence-inefficient, as a brand new copy of the method could be created for each instance.
Var Employee = function (call, employer, earnings)
this.Name = namecharacteristic default fee is null
this.Company = agencycharacteristic default fee is null
this.Profits = earnings 5000; //Public characteristic default fee is null
// Private method
var increaseSalary = characteristic ()
this.Profits = this.Profits + a thousand;
;
// Public approach
this.DispalyIncreasedSalary = characteristic()
increaseSlary();
console.Log(this.Salary);
;
;
// Create Employee magnificence object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class item
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 very own copy of the increaseSalary non-public method.
So, as a recommendation, don’t use non-public methods unless it’s essential.
Q12. Write A Mul Function Which Will Produce The Following Outputs When Invoked?
Console.Log(mul(2)(3)(4)); // output : 24
console.Log(mul(4)(three)(4)); // output : forty eight
Below is the wer observed through a proof to the way it works:
characteristic mul (x)
return feature (y)
// anonymous characteristic
return characteristic (z)
// nameless characteristic
return x * y * z;
;
;
Here the mul characteristic accepts the primary argument and returns an nameless feature, which takes the second one parameter and returns some other nameless characteristic on the way to take the 0.33 parameter and go back the multiplication of the arguments that have been surpassed.
In JavaScript, a characteristic described internal any other one has get entry to to the outer feature's variables. Therefore, a feature is a quality object that can be back through other capabilities as well and be handed as a controversy in every other feature.
A function is an instance of the Object kind
A feature may have houses and has a hyperlink again to its constructor method
A function can be stored as a variable
A characteristic may be skip as a parameter to some other feature
A feature can be again from any other feature
Q13. 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 situation statement evaluates the usage of eval, so eval(characteristic f()) returns feature f() (which is proper). Therefore, inside the if assertion, executing typeof f returns undefined due to the fact the if assertion code executes at run time, and the declaration in the if situation is evaluated during run time.
Var ok = 1;
if (1)
eval(characteristic foo());
k += typeof foo;
console.Log(okay);
The code above can even output 1undefined.
Var okay = 1;
if (1)
function foo();
ok += typeof foo;
console.Log(ok); // output 1function
Q14. What Will Be The Output Of The Code Below?
Var X = Foo : 1;
var Output = (function()
delete X.Foo;
go back X.Foo;
)();
console.Log(output);
The output could be undefined. The delete operator is used to delete the belongings of an item. Here, x is an object which has the assets foo, and as it's miles a self-invoking characteristic, we can delete the foo belongings from item x. After doing so, when we attempt to reference a deleted assets foo, the result isundefined.
Q15. 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 pair approaches we can use to drain an array, so permit's talk them all.
Method 1 :
arrayList = []
Above code will set the variable arrayList to a brand new empty array. This is suggested in case you do not have references to the unique array arrayList anywhere else, because it will sincerely create a brand new, empty array. You need to be cautious with this approach of emptying the array, because when you have referenced this array from any other variable, then the original reference array will stay unchanged.
For Instance,
var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by way of every other variable
arrayList = []; // Empty the array
console.Log(anotherArrayList); // Output ['a','b','c','d','e','f']
Method 2 :
arrayList.Length = zero;
The code above will clean the existing array by means of setting its length to @This way of emptying the array also updates all of the reference variables that point to the unique array. Therefore, this method is beneficial when you want to replace all reference variables pointing to arrayList.
For Instance,
var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList through any other variable
arrayList.Duration = zero; // Empty the array via putting period to zero
console.Log(anotherArrayList); // Output []
Method three : arrayList.Splice(0, arrayList.Length);
The implementation above will even paintings perfectly. This way of emptying the array may even replace all the references to the unique array.
Var arrayList = ['a','b','c','d','e','f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by any other variable
arrayList.Splice(zero, arrayList.Length); // Empty the array by means of putting duration to 0
console.Log(anotherArrayList); // Output []
Method four :
whilst(arrayList.Duration)
arrayList.Pop();
The implementation above can also empty arrays, but it is usually now not recommended to apply this approach regularly.

