Top JavaScript Interview Questions

1) Difference between let and var to declare a variable
var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
Also, variables declared with let are not accessible before they are declared in their enclosing block
2) Difference between ‘===’and ‘==’ in JavaScript
JavaScript has both strict and type–converting comparisons. A strict comparison (e.g., ===) is only true if the operands are of the same type and the contents match. The type-converting comparison (e.g. ==) converts the operands to the same type before making the comparison.

Equality (==)

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Inequality (!=)

The inequality operator returns true if the operands are not equal. If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. If both operands are objects, then JavaScript compares internal references which are not equal when operands refer to different objects in memory.

Identity / strict equality (===)

The identity operator returns true if the operands are strictly equal (see above) with no type conversion.

Non-identity / strict inequality (!==)

The non-identity operator returns true if the operands are not equal and/or not of the same type.

3) Difference between class-based (Java) and prototype-based (JavaScript) languages ?

Class-based (Java)Prototype-based (JavaScript)
Class and instance are distinct entities.All objects can inherit from another object.
Define a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Create a single object with the new operator.Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes.Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain.Inherit properties by following the prototype chain.
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

4) What is Prototype in JavaScript ?

Prototype is an object used as a template from which to get the initial properties for a new object.
Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object’s properties

5) What is the difference between DOM properties and HTML attributes?

You can define attributes on your HTML elements, when writing HTML source code,. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element has two attributes.

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it’s not a one-to-one relationship.

For instance, for this HTML element, the corresponding DOM node will have id,type, and value properties (among others).

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn’t modify or limit the value.
  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn’t a pure reflected property because it’s limited to known values (e.g., the valid types of an input). If you had <input type=”foo”>, then theInput.getAttribute(“type”) gives you “foo” but theInput.type gives you “text”.
  • In contrast, the value property doesn’t reflect the value attribute. Instead, it’s the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs “Luke” into the input box, then:

The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.So if you want to know what’s currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute.

6) What are the different ways to create an object in JavaScript ?

Explicit

Shorthand object literal syntax, using curly braces:

Using a function:

This creates a singleton

 7) Explain how prototypical inheritance works ?

  • A prototype is an internal object from which other objects inherit properties. Its main purpose is to allow multiple instances of an object to share a common property. Thus, object properties which are defined using the prototype object are inherited by all instances which reference it.
  • The prototype is a reference to another object and it is used whenever JS can’t find the property you’re looking for on the current object. Simply put, whenever you call a property on an object and it doesn’t exist, JavaScript will go to the prototype object and look for it there. If it finds it it will use it, if not it will go to that object’s property and look there. This can bubble up all the way to Object.prototype before returning undefined. This is the essence of the prototype chain and the behavior that sits behind JavaScript’s inheritance

8) What is closure in JavaScript ?

  • A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent functions scope.
  • The closure has access to variable in three scopes.
    • Variable declared in its own scope.
    • Variable declared in parent function scope.
    • Variable declared in global namespace.

9) What is function hoisting in JavaScript ?

10) What is instanceof operator in JavaScript ?

  • instanceof operator checks the current object and return true if the object is of the specified type.

11) What will the following code output ? 

The code above will output 5 even though it seems as if the variable was declared within a function and can’t be accessed outside of it. This is because

is interpreted the following way:

But b is not declared anywhere in the function with var so it is set equal to 5 in the global scope.

12) Write a function that would allow you to do this ? 

You can create a closure to keep the value of a even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable a.

13) What does “use strict” do?
The “use strict” literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error:

It will throw an error because x was not defined and it is being set to some value in the global scope, which isn’t allowed with “use strict” The small change below fixes the error being thrown:

use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime.

  • Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.
  • Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.
  • Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems).
  • Disallows duplicate parameter values. Strict mode throws an error when it detects a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.
    • Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g. var object = {foo: "bar", foo: "baz"};) but as of ECMAScript 2015 this is no longer the case.

14) Explain what a callback function is and provide a simple example ?
A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

15) How would you check if a number is an integer or a decimal ?
with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose.

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

16) Find all duplicates in an array ?
The general algorithm is,
1. Loop through the array
2. At each element check if it exists in the hash table, which has a lookup of O(1) time
3. If the element exists in the hash table then it is a duplicate, if it doesn’t exist, insert it into the hash table, also O(1)

17) What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.

Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:

18) What are the different Module Formats in JavaScript ?
-> Module format is syntax we can use to define module.
-> Before 2015, JavaScript did not have any official syntax to define modules.
-> Prominently used module formats are,

  • CommonJS
  • AMD
  • UMD
  • ES2015

-> Node.js uses CommonJS pattern.
– require(‘foo’) to load a module.
– module.exports to expose functionality.
-> Require.js for browser based modules.
– require takes an array of dependencies and a callback.
– define takes an array of dependencies and exposes and API.

19) Give an example to define a module in CommonJS ?

20) How do you add an element at the beginning of an array? How do you add one at the end ?

In ES6 spread operator can be used.

Or in short,

21) What is the difference between Array.splice() and Array.slice() ?
-> The splice() method returns the removed items in an array and slice() method returns the selected elements in an array as a new array object.
-> The splice() method changes the original array and slice() method doesn’t change the original array.
-> The splice() method can take n number of arguments. 

-> The slice() method can take 2 arguments.
-> Argument 1: Required.An integer that specifies where to start the selection. Use negative numbers to select from the end of an array.
-> Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *