Top 30 JavaScript Interview Questions And Answers

0
949

We’ve listed down the top 30 JavaScript interview questions and answers for web developers. After a thorough analysis, we came up with this list. And there is a high probability that you might face similar types of questions during interviews.

JavaScript is a cutting edge technology and remain in high demand. It not only used for creating high-end web applications but also powers many web development frameworks like Angular and Node.js.

In our previous posts, we’d covered a wide range interviews for web developers especially on HTML5, CSS, JavaScript, Angular, and Node.js. It is worth checking out them if you plan to become a MEAN stack or a full stack web developer.

Top 30 JavaScript Interview Questions.

Find Answers For JavaScript Interview Questions.

Q.1- What’s An Object In JavaScrpt And How Do We Create Them?

Answer.

A JavaScript object is an entity having state and behavior (properties and method). Since JavaScript is an object-based language, it treats everything as an object.

JavaScript is a template-based language not class based. It supports to create the object directly, there is no need to define a class for this.

JavaScript supports following three ways to create objects.

1. By Object Literal.

The syntax of creating an object using object literal is as follows.

Here, property and value are separated by “:”.

Let’s take an example of creating an object using object literal technique.

2. By Creating An Instance Of The Object (Using New Keyword).

The syntax of creating an object directly is as follows.

Here, the new keyword is used to create the object.

Let’s take an example of creating an object directly.

3. By Using An Object Constructor.

In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.

This keyword refers to the current object.

Let’s take an example of creating an object using object constructor technique.

 

Q-2. What Is Scope In JavaScript?

Answer.

The scope determines the accessibility of variables, objects, and functions in particular part of your code.

In JavaScript, the scope is of two types.

1. Global Scope.

A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.

2. Local Scope.

Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.

 

Q-3. What Is <This> In JavaScript?

Answer.

All the prime languages use ‘this’ keyword to refer to an object that is currently instantiated by the class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies, with how a function call happens.

Global Scope.

If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’ is the top-level object which represents the document, location, history and a few other useful properties and methods. Let’s take a sample code.

The Scenario Of A Function Call.

In the case of a function call, ‘this’ refers to the global object.

Call Object Methods.

When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It is similar to any class-based language.

 

Q-4. What Is Prototype Property In JavaScript?

Answer.

Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function’s prototype so that it becomes available to instances of that function. Let’s take an example that calculates the perimeter of a rectangle.

 

Q-5. What Is Closure In JavaScript?

Answer.

A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.

  • Internal Scope i.e. the variables defined between its curly brackets.
  • Outer Function Scope i.e. the variables of the enclosing function.
  • Global Scope i.e. variables defined as globals.

Please note that a closure can not only access the outer function variables but also see its parameters. But it can’t call the outer function’s arguments object. However, it can directly call the outer function’s parameters.

Here is a code example describing closure by adding a function inside another function.

 

Q-6. Why Is “Self” Needed Instead Of “This” In JavaScript?

Answer.

Inner functions in JavaScript have access to all of the variables defined in the outer function. However, “this” variable is an exception. Since the nested function is just a regular function and not an object method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following example.

Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get a reference to the object, that is available inside the nested function. We assign the object from “this”, to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local object. Following is the sample code.

 

Q-7. What Is An Anonymous Function And When Should You Use It?

Answer.

Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they don’t have a name like normal functions.

We use function operator to declare an anonymous function, instead of the function declaration. Also, function operator can be used to create a new function, wherever it’s valid to put an expression. For example, we declare a new function to be supplied as an argument to a function call or to assign a property of another object.

Here’s a typical example of a named function.

Here’s the same example created as an anonymous function.

Following are the key usage of anonymous functions.

  • Code brevity.
    • Use them in
      • Callbacks, and
      • Event handlers.
  • Scope management.
    • They are useful in the following scenario.
      • To create temporary/private scope.
      • In Closures and Recursions.

 

Q-8. What Is The Difference Between “==” And “===”?

Answer.

These are the operators provided by JavaScript – strict equality and Type converting equality.

Strict equality (===) returns true if the values which it is going to compare have the same data type. Taking an example, “2” will not be equal to 2  i.e. (“2″===2) will return false.

Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2  i.e. (“2″===2) will return true.

Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e. it will not convert values automatically.

 

Q-9. What Are JavaScript Data Types?

Answer.

JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the data types in each of the categories.

Primary Data Types.

  • String
  • Number
  • Boolean

Composite Data Types.

  • Object
  • Array

Special Data Types.

  • Null
  • Undefined

 

Q-10. What Is Prototypal Inheritance In JavaScript?

Answer.

Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other classes.

In JavaScript, the inheritance is prototype-based. This means that there are no classes. Instead, there is an object that inherits from another object.

JavaScript provides three different types of Prototypal Inheritance.

1. Delegation (I.E. The Prototype Chain).

A delegate prototype is an object that serves as a base for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype.

When we try to access any property, it first checks in the properties owned by the object. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it reaches the <Object.prototype> i.e. the root delegate for most of the objects.

2. Concatenative Inheritance (I.E. Mixins, Object.Assign()).

It is the process of inheriting the features of one object to another by copying the source objects properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.

3. Functional (Not To Be Confused With Functional Programming).

In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is called a factory function. Functional inheritance produces an object from a factory and also extends it, by assigning properties.

Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them are equally useful in their ability to enable composition. It provides has-a, uses-a, or can-do relationship as compared to the is-a relationship created with class inheritance.

 

Q-11. What Is An Asynchronous Programming? Why Is It Important In JavaScript?

Answer.

In Asynchronous programming, the engine runs in an event loop. On encountering a blocking operation, a request gets fired and the code keeps running without blocking for the result. When its execution completes, and the response is ready, it fires an interrupt, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations in an asynchronous programming.

The user interface is asynchronous by nature and spends most of the time, waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the server works by waiting for a network request in a loop. Thus, it accepts more incoming requests, while the first one is getting handled.

It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining the performance on the server.

 

Q-12. What Is Variable Typing In JavaScript?

Answer.

JavaScript is very loosely typed language. It means that the variables are declared without a type. Its type is determined once a value is assigned to it. It can change as the variable appears in different contexts.

It’s in contrast to the strongly typed languages that require type declarations.

Consider the following examples.

Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type ‘Number’ and var ‘b’ will be of type ‘String’.

 

Q-13. What Are The Different Ways To Create An Array In JavaScript?

Answer.

There are two main ways to create an array in JavaScript.

1. Using An Array Initializer (Array Literal).

The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.

Let’s see some examples.

2. Using The Array Constructor.

The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.

Let’s see some examples.

 

Q-14. What Are JavaScript Cookies?

Answer.

A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains following data.

  • A name-value pair containing the actual data.
  • An expiry date after which the cookie is no longer valid.
  • The domain and path of the server it should be sent to.

When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. Server side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences.

Thus, every time you visit the site that maintains the cookies, your information is available there.

 

Q-15. Which Built-In Method Adds One Or More Elements To The End Of An Array And Returns The New Length Of The Array?

Answer.

The push() method adds one or more elements to the end of an array and returns the new length of the array.

 

Q-16. What Is The Naming Conventions For The Variables In JavaScript?

Answer.

We have to follow the below rules while naming the variables in JavaScript.

  • Do not use any of the JavaScript reserved keywords as a name for your variable. For example, “break” or “boolean” are JavaScript keywords, and if used as variable names, it’s invalid.
  • JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
  • Also, JavaScript variable names are case sensitive. For example, test and Test are two different variables.

 

Q-17. How Will You Create A Cookie Using JavaScript?

Answer.

The simplest way to create a cookie is to assign a string value to the <document.cookie> object.

Its syntax is as follows.

Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.

If we provide a valid value for the date or time, then the cookie will expire at the given date or time and it will not be accessible after that.

 

Q-18. How To Read A Cookie Using JavaScript?

Answer.

To read a Cookie, we have to access the value of the <document.cookie> object. This <document.cookie> string maintains a list of <name = value> pairs that is separated with semicolons.

Where,

We use String <split()> function to break the <document.cookie> object to sub-strings. Each of these sub-strings contains a key-value pair which represents the information related to a Cookie.

 

Q-19. How To Delete A Cookie Using JavaScript?

Answer.

To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are made to read a deleted Cookie then, nothing is returned.

 

Q-20. How Do You Submit A Form Using JavaScript?

Answer.

We use the following in the web page code to submit a form.

Here <0> refers to the index of the form. If we have more than one forms on a web page, then the index for the first one will be “0”, for the second form, its value will be “1” and so on.

 

Q-21. Why Should You Not Prefer To Use Global Variables In JavaScript And How Can You Prevent It?

Answer.

 

The principal issue in using a global variable is that someone else can create another variable with the same name. And you may not know it until the duplicate could overwrite the value of your variable.

To avoid using globals, follow any of the following approaches.

1. Create a single global variable that holds all your other variables.

2. Enclose all of your code in a self-executing method/function so that any variable declared inside remain in the function scope.

 

Q-22. What Are The Different Objects Used In JavaScript?

Answer.

JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following are the objects, used in JavaScript that shows the relationship of one object to another.

Window Object.

It is the topmost object in the hierarchy. It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.

Document Object.

A Document object represents the HTML document that the window will display. It has various properties that refer to other objects, which allow access to and modification of content in the document.

Form Object.

A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the <FORM>…</FORM> tag.

 

Q-23. What Do We Achieve By Deferring The Loading Of JavaScript?

Answer.

During page load operation, by default, the parsing of the HTML code remains paused until the execution of the script has not stopped.

Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web page.

By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed faster.

In this way, it makes the page load quicker, without the average user even realizing that some JavaScript load after the DOM has loaded.

Let’s see an example.

Here the middle block will execute once the page has loaded even though it appears before the last block.

 

Q-24. What Is Strict Mode In JavaScript?

Answer.

Strict Mode imposes a layer of constraint on JavaScript. It provides following enhancements.

  • JavaScript will throw an error if we try to use the elements of a deprecated language.
  • To use a variable, it has become mandatory to declare it.
  • It disallows duplicate property and parameter names.
  • The eval() method is safer to use, but still considered evil in some cases.
  • It deprecates the “with” statement.
  • JavaScript will throw an error if we try to assign a value to a read-only property.
  • It decreases the global namespace pollution.

To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the “strict” directive determines its scope. If used at the beginning of the js file, its scope is global. However, if we declare strict mode at the first line in the function block, its scope restricts to that function only.

 

Q.25- What Are Event Handlers In JavaScript And How To Use Them?

Answer.

JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the part of HTML document object model (DOM). An event can take place in one of the following cases.

Due to user actions on a web page.

Some events are callbacks triggered by the browser when a page changes its state.

Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event. To use a handler function, we can assign it to the desired event as an attribute of the target HTML element. Please follow the below example.

 

Q-26. What Does A JavaScript Function Result When It Has No Return Statement?

Answer.

If a function doesn’t use the return statement, then it returns undefined as the return value.

However, the browser won’t print anything in its console as it ignores if the expression returns an undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll print exact value.

 

Q-27. What Is EncodeURI() Function?

Answer.

The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.

Let’s See An Example.

Output.

We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the encodeURI function is used to encode special reserved characters and other non-ASCII characters in the URI.

 

Q-28. How Does The <Array()> Differ From <[]> While Creating A JavaScript Array?

Answer.

Both the <Array()> and <[]> works almost the same in JavaScript.

If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Also, if we pass a string or a list of strings as arguments, even then result will be similar.

However, they differ when the input argument is of integer type. In that case, the <Array(n)> statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an array of size <1> and assign <n> as value to the first element.

 

Q-29. How Does Variable Hoisting Take Place In JavaScript?

Answer.

In JavaScript, variable declarations are the first piece of code that executes irrespective of their location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This functionality which moves the declaration to the top either inside a function or in the global code is known as hoisting.

JavaScript will interpret the above in the following manner.

 

Q-30. How Will You Replace All Occurrences Of A String In JavaScript?

Answer.

We can use String’s <replace()> method to substitute any string. There are following two ways to use this method.

Pass The Input String As A Regular Expression.

Use RegExp Class To Create A Regular Expression And Pass It.

 

Summary – Top 30 JavaScript Interview Questions.

Web development market is growing from last many years. And with the inception of new technologies like AngularJS/Node.js, it shall grow further. And we are sure that JavaScript would keep its place as the leading skill for web developers.

Also, we wish you can use the above JavaScript interview questions as a quick reference to brush up your skills.

Suggest

ES6 Javascript: The Complete Developer’s Guide

Master Electron: Desktop Apps using HTML, JavaScript & CSS

The complete JavaScript developer: MEAN stack zero-to-hero

LEAVE A REPLY

Please enter your comment!
Please enter your name here