Categories

Top 50 JavaScript Interview Questions and Answers

Today, Google and Facebook use JavaScript to build complex, desktop-like web applications. With the launch of Node js, It has also become one of the most popular languages for building server-side software. Today, even the web isn’t big enough to contain JavaScript’s versatility. I believe that you are already aware of these facts and this has made you land on this JavaScript Interview Questions article

1. What is JavaScript?

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

2. What are the data types supported by JavaScript?

The data types supported by JavaScript are:

1) Undefined

2) Null

3) Boolean

4) String

5) Symbol

6) Number

7) Object

3. What is the difference between Java & JavaScript?

Java

JavaScript

Java is an OOPS programming language.

JavaScript is an OOPS scripting language.

It creates applications that run in a virtual machine or browser.

The code is run on a browser only.

Java code needs to be compiled.

JavaScript code are all in the form of text.

4. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language. The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

5. What are the features of JavaScript?

1) It is a lightweight, interpreted programming language.

2) It is designed for creating network-centric applications.

3) It is complementary to and integrated with Java.

4) It is an open and cross-platform scripting language.

6. What is a name function in JavaScript & how to define it?

A named function declares a name as soon as it is defined. It can be defined using function keyword as :
function named(){
// write code here
}

7. How can you create an Array in JavaScript?

You can define arrays using the array literal as follows-
var x = [];
var y = [1, 2, 3, 4, 5];

8. How can you create an object in JavaScript?

JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: "Daniel",
age: 23
};

9. What are the advantages of JavaScript?

Following are the advantages of using JavaScript −

Less server interaction −
You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.

Immediate feedback to the visitors −
They don’t have to wait for a page reload to see if they have forgotten to enter something.

Increased interactivity −
You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.

Richer interfaces −
You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

10. Can you assign an anonymous function to a variable and pass it as an argument to another function?

Yes! An anonymous function can be assigned to a variable. It can also be passed as an argument to another function.

In case you are facing any challenges with these JavaScript Interview Questions, please comment on your problems in the section below.

11. What is Closure? Give an example.

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.

12. What is Callback?

A callback is a plain JavaScript function passed to some method as an argument or option. It is a function that is to be executed after another function has finished executing, hence the name ‘call back‘. In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.

13. What are the scopes of a variable in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables −
A global variable has global scope which means it is visible everywhere in your JavaScript code.

Local Variables −
A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

14. What is the purpose of ‘This’ operator in JavaScript?

The JavaScript this keyword refers to the object it belongs to. This has different values depending on where it is used. In a method, this refers to the owner object and in a function, this refers to the global object.

15. What is argument objects in JavaScript & how to get the type of arguments passed to a function?

JavaScript variable arguments represents the arguments that are passed to a function. Using type of operator, we can get the type of arguments passed to a function.

16. How to read a cookie using JavaScript?

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.

The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

You can use strings’ split() function to break the string into key and values.

17. How does Type Of Operator work?

The type of operator is used to get the data type of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. It is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

18. What are the variable naming conventions in JavaScript?

The following rules are to be followed while naming variables in JavaScript:

1) You should not use any of the JavaScript reserved keyword as variable name. For example, break or boolean variable names are not valid.

2) JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123name is an invalid variable name but _123name or name123 is a valid one.

3) JavaScript variable names are case sensitive. For example, Test and test are two different variables.

19.How to create a cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-

20. Name some of the built-in methods and the values returned by them.

Built-in Method

Values

CharAt()

It returns the character at the specified index.

Concat()

It joins two or more strings.

forEach()

It calls a function for each element in the array.

indexOf()

It returns the index within the calling String object of the first occurrence of the specified value.

length()

It returns the length of the string.

pop()

It removes the last element from an array and returns that element.

push()

It adds one or more elements to the end of an array and returns the new length of the array.

reverse()

It reverses the order of the elements of an array.

21. What are the ways to define a variable in JavaScript?

The three possible ways of defining a variable in JavaScript are:

Var
The JavaScript variables statement is used to declare a variable and, optionally, we can initialize the value of that variable. Example: var a =10; Variable declarations are processed before the execution of the code.

Const
The idea of const functions is not allow them to modify the object on which they are called. When a function is declared as const, it can be called on any type of object.

Let
It is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in.

22. In how many ways a JavaScript code can be involved in an HTML file?

There are 3 different ways in which a JavaScript code can be involved in an HTML file:

1) Inline

2) Internal

3) External

An inline function is a JavaScript function, which is assigned to a variable created at runtime. You can differentiate between Inline Functions and Anonymous since an inline function is assigned to a variable and can be easily reused. When you need a JavaScript for a function, you can either have the script integrated in the page you are working on, or you can have it placed in a separate file that you call, when needed. This is the difference between an internal script and an external script.

23. List out the different ways an HTML element can be accessed in a JavaScript code.

Here are the list of ways an HTML element can be accessed in a Javascript code:

getElementById(‘idname’):
Gets an element by its ID name

getElementsByClass(‘classname’):
Gets all the elements that have the given classname.

getElementsByTagName(‘tagname’):
Gets all the elements that have the given tag name.

querySelector():
This function takes css style selector and returns the first selected element.

24. What is the difference between Attributes and Property?

Attributes
provide more details on an element like id, type, value etc.

Property
is the value assigned to the property like type=”text”, value=’Name’ etc.

25. How to delete a cookie using JavaScript?

If you want to delete a cookie so that subsequent attempts to read the cookie in JavaScript return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.

Intermediate Level JS Interview Questions and Answers

26. What is the difference between undeclared & undefined?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

27. What is the difference between the operators ‘==‘ & ‘===‘?

The main difference between “==” and “===” operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn’t allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type “===” return false, while “==” return true.

28. What is the difference between Local storage & Session storage?

Local Storage
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or program.

Session Storage

It is similar to local storage; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.

In case you are facing any challenges with these JavaScript Interview Questions, please comment on your problems in the section below.

29. What is a Typed language?

Typed Language is in which the values are associated with values and not with variables. It is of two types:

Dynamically
in this, the variable can hold multiple types; like in JS a variable can take number, chars.

Statically
in this, the variable can hold only one type, like in Java a variable declared of string can take only set of characters and nothing else.

30. What is the difference between null & undefined?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

31. What is NaN in JavaScript?

NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.

In case you are facing any challenges with these JavaScript Interview Questions, please comment on your problems in the section below.

32. What is an event bubbling in JavaScript?

Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element. Then the execution passes to its parent element and so on till the body element.

33. What is the difference between innerHTML & innerText?

innerHTML
It will process an HTML tag if found in a string

innerText
It will not process an HTML tag if found in a string

34. Name some of the JavaScript Frameworks

A JavaScript framework is an application framework written in JavaScript. It differs from a JavaScript library in its control flow. There are many JavaScript Frameworks available but some of the most commonly used frameworks are:

1) Angular

2) React

3) Vue

35. How do JavaScript primitive/object types passed in functions?

One of the differences between the two is that Primitive Data Types are passed By Value and Objects are passed By Reference.

By Value
means creating a COPY of the original. Picture it like twins: they are born exactly the same, but the first twin doesn’t lose a leg when the second twin loses his in the war.

By Reference
means creating an ALIAS to the original. When your Mom calls you “Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give birth to a clone of yourself: you are still one, but you can be called by these two very different names.

36. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

example:

parseInt("4F", 16)

37. What would be the result of 2+5+”3″?

Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its concatenation will be done. So the result would be 73. The ” ” makes all the difference here and represents 3 as a string and not a number.

38. What are Exports & Imports?

Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code into multiple files. For example-

Advanced Level JavaScript Interview Questions and Answers for Experienced Professionals

39. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict mode is a way to introduce better error-checking into your code.

1) When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.

2) You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.

40. What is a prompt box in JavaScript?

A prompt box is a box which allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.

41. How to empty an Array in JavaScript?

There are a number of methods you can use to empty an array:

Method 1 –
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 arrayList anywhere 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.

arrayList = []


Method 2 –
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.

arrayList.length = 0;


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

arrayList.splice(0, arrayList.length);


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

while(arrayList.length) { arrayList.pop(); }

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

42. What will be the output of the code below?

var Y = 1;
if (function F(){})
{
y += Typeof F;</span>
}
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 c

43. When to Use Internal and External JavaScript Code?

Suppose you have only a few lines of code that is specific to a particular webpage. In that case, it is better to keep your JavaScript code internal within your HTML document.

On the other hand, if your JavaScript code is used in many web pages, you should consider keeping your code in a separate file. If you wish to make some changes to your code, you have to change only one file, making code maintenance easy. If your code is too long, it is better to keep it in a separate file. This helps in easy debugging.

44. What are escape characters in JavaScript?

JavaScript escape characters enable you to write special characters without breaking your application. Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

For example-

document.write "I am a "good" boy"
document.write "I am a "good" boy"

45. What is the reason for wrapping the entire content of a JavaScript source file in a function book?

This is an increasingly common practice, employed by many popular JavaScript libraries. 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 easy alias for a global variable. This is often used in jQuery plugins.

46. What are Cookies in JavaScript?

A cookie is a piece of data stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.

47. What do you mean by Self Invoking Functions?

Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.

Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.

48. What is the difference between exec () and test () methods in javascript?

test () and exec () are RegExp expression methods used in javascript.

We'll use exec () to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; else, it'll return an 'empty' result.

We will use a test () to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.

49. What are some advantages of using External JavaScript?

External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the or element of the HTML file where the code is to be placed.

Some advantages of external javascript are

It allows web designers and developers to collaborate on HTML and javascript files.

We can reuse the code.

Code readability is simple in external javascript.

50. What are the types of errors in javascript?

There are two types of errors in javascript.

Syntax error:
Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.

Logical error:
Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.