Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JavaScript Interview Questions for Freshers
2.1.
1. What is JavaScript?
2.2.
2. Different data types in JavaScript.
2.3.
3.Differentiate between Javascript and Java.
2.4.
4.List some features of Javascript.
2.5.
5. What are the key differences between Java and Javascript?
2.6.
6. Tell the advantages of Javascript.
2.7.
7. State whether Javascript is a case-sensitive language.
2.8.
8. Name the company which developed Javascript.
2.9.
9. In JavaScript, how do you create an object?
2.10.
10. In JavaScript, how do you construct an array?
2.11.
11. Is it possible to give an anonymous function as an argument to another function?
2.12.
12. Differentiate between “ == “ and “ === “ operators.
2.13.
13. Differentiate between var and let keywords in javascript.
2.14.
14. Define the scopes of a variable in JavaScript?
2.15.
15. List a few of the built-in methods along with the values they return.
2.16.
16. What are the JavaScript variable naming conventions?
2.17.
17. How does the TypeOf Operator function?
2.18.
18. Define undeclared and undefined variables?
2.19.
19. What are the escape characters in JavaScript?
2.20.
20. Define prompt box.
2.21.
21. Differentiate between slice and splice.
2.22.
22. Define the various types of error constructors supported by JavaScript?
2.23.
23. How is JavaScript code debugged?
2.24.
24. Differentiate between Windows & documents in JavaScript?
2.25.
25. Define arrow functions in JavaScript?
2.26.
26. Give some Javascript frameworks and their uses.
2.27.
27. Define event bubbling and event capturing.
2.28.
28. Define ways to empty an array in Javascript.
2.29.
29. Give the output of the following code?
2.30.
30. Define ways to remove duplicates from the Javascript array.
3.
JavaScript Interview Questions for Experienced
3.1.
31. Draw a simple Javascript DOM.
3.2.
32. Define the symbols used for comments in Javascript.
3.3.
33. Define variable typing in Javascript.
3.4.
34. Define Javascript cookies.
3.5.
35. Give the disadvantages of using innerHTML in Javascript.
3.6.
36. Give some advantages of using external Javascript.
3.7.
37. How is JavaScript using event handlers?
3.8.
38. What is the difference between var and let keyword?
3.9.
39. What is Hoisting in Javascript? 
3.10.
40. What is ECMAScript?
3.11.
41. What is the key difference between “==” and “===” in Javascript?
3.12.
42. What is NaN in Javascript?
3.13.
43. What is asynchronous programming in Javascript? 
3.14.
44. What are the different iterable values in JavaScript?
3.15.
45. What will be the Output of 5+2+” 3″?
3.16.
46. Is Javascript a case-sensitive language?
3.17.
47. What is the value of ans[0] in the below script?
3.18.
48. What is the difference between Object.freeze() and const? 
3.19.
49. What are Promises in Javascript?
3.20.
50. What is currying in JavaScript?
4.
JavaScript Coding Interview Questions
4.1.
51. Define DOM in Javascript. 
4.2.
52. What is the Javascript Event Delegation Model?
4.3.
53. How to empty an array in JavaScript?
4.4.
54. How can you create a cookie using Javascript?
4.5.
55. Name a few Javascript frameworks.
4.6.
56. What is Strict mode in JS?
4.7.
57. What is the difference between a null, undefined, and undeclared variable in Javascript?
4.8.
58. Explain array.slice and array.splice in Js
4.9.
59. Determine the Output of the following code.
4.10.
60. What are IIFEs?
4.11.
61. What are ArrayBuffers?
4.12.
62. What is Callback hell?
4.13.
63. What is the difference between a window and a document?
4.14.
64. Explain Arrow functions. 
4.15.
65. What is the Output?
4.16.
66. What is a WeakMap in Javascript?
4.17.
67. What are the limitations of Javascript?
5.
JavaScript MCQ
5.1.
1.What is used to enforce the restricted variant of JavaScript?
5.2.
2. What is the <noscript> tag used for?
5.3.
3. Give the Output of the following code
5.4.
4.What does JavaScript print when there is an indefinite or an infinite value during an arithmetic computation in a program?
5.5.
5. What is used for calling function definitions in JavaScript?
5.6.
6. Which operator is used to check if a property exists or not?
5.7.
7. What is used to make the function appear to be synchronous?
5.8.
8.What is the output of the following code?
5.9.
9.Which of the following modified the person_name object in the code below?
5.10.
10.Which of the following is a stateless protocol?
6.
Frequently Asked Questions
6.1.
Q. What is JavaScript basic interview questions?
6.2.
Q. How to prepare JavaScript for interview?
6.3.
Q. What is object in JavaScript interview questions?
6.4.
Q. What is BOM in JavaScript interview questions?
6.5.
Q. Which company developed JavaScript? 
6.6.
Q. Does JavaScript support automatic type conversion? 
6.7.
Q. Explain hoisting in JavaScript. 
6.8.
Q. What is the strict mode? 
7.
Conclusion
Last Updated: Aug 8, 2024
Easy

JavaScript Interview Questions

Author Akshay Parashar
4 upvotes

Introduction

JavaScript is a programming language used for creating interactive web content. It enables client-side interactivity, supports versatile application development, has a robust ecosystem, ensures cross-browser compatibility, and delivers scalable performance, making it essential for modern web development.

JavaScript Interview Questions

To help you ace your interview and land your dream job as a Javascript Developer, the CodingNinjas team has compiled a comprehensive list of the best Javascript interview questions and answers. The following section will discuss javascript interview questions and answers in detail. Check them out.

JavaScript Interview Questions for Freshers

1. What is JavaScript?

JavaScript is a simple, interpreted programming language with object-oriented features that enables you to add interactivity to HTML pages that would otherwise be static. The language's general-purpose core has been integrated into Netscape, Internet Explorer, and other web browsers.

2. Different data types in JavaScript.

The data types supported by JavaScript are:

  • Undefined
     
  • Null
     
  • Boolean
     
  • String
     
  • Symbol
     
  • Number
     
  • Object

3.Differentiate between Javascript and Java.

 

Java

JavaScript

It is an OOP programming language.It is a Scripting language based on the concept of objects.
Java creates applications that run on a browser or virtual machine.Its code is run on a browser only.
Here the code needs to be compiled.Its code is all in the form of text.

 

4.List some features of Javascript.

The following features are available in Javascript-

  • Interpreted Language- the browser executes Javascript code, and no compilation is needed.
     
  • Cross Platform- means that Javascript is platform-independent and runs the same on all platforms irrespective of the operating system.
     
  • Object-Oriented Scripting Language- The programming style and technique are based upon objects to represent data and code.
     
  • Asynchronous Processing- Javascript has an async-await function and promises feature, which makes it possible to do asynchronous programming.

5. What are the key differences between Java and Javascript?

The key difference between Java and Javascript is that Java is an object-oriented based programming language, while Javascript is a scripting language that is based on the use of objects for data manipulation and representation. The browser on the client side interprets Javascript code, while Java code is executed on the server before its execution on the client side. 

6. Tell the advantages of Javascript.

JavaScript has the following benefits:

Superior Interaction: JavaScript makes other static web pages interactive and allows them to respond to user input.

Quick Response: When JavaScript is used, a web page does not need to reload. Consider the validation of form input.

Rich User Interface: Web apps' user interface (UI) can look and feel significantly better thanks to JavaScript.

Frameworks: JavaScript includes many frameworks and libraries widely used to create various games and web applications.

7. State whether Javascript is a case-sensitive language.

Yes, the language of JavaScript takes the case into account. Consistent letter capitalization is required when typing the language's keywords, variables, function names, and other identifiers.

8. Name the company which developed Javascript.

Netscape developed Javascript.

9. In JavaScript, how do you create an object?

Using the object literal, you can create an object like seen below:

var emp = {
name: "John",
age: 19
};

10. In JavaScript, how do you construct an array?

Using the array literal, you can define arrays as follows:

var a = [ ];
var b = [1, 2, 3, 4, 5];

11. Is it possible to give an anonymous function as an argument to another function?

Yes! A variable may be given an anonymous function. It may also be passed to another function as an argument.

12. Differentiate between “ == “ and “ === “ operators.

Both operate on comparisons. The distinction between the two operators is that while "==" compares values, " === compares both values and types.

var a = 7;
var b = "7";
(a == b)  // Returns true since the value of both a and b is the same
(a === b) // Returns false since the typeof a  is "number" and typeof b is "string"

13. Differentiate between var and let keywords in javascript.

Some variations include:

The 'var' keyword has been used in JavaScript programming since the beginning, whereas the 'let' keyword was just introduced in 2015.

"Var" is a keyword with function scope. The variable stated with the var keyword is available throughout the function, while in "let," the scope of a variable declared with this keyword is restricted to the block in which it is declared. 

14. Define the scopes of a variable in JavaScript?

The area of your program where a variable is defined is its scope. There will only be two scopes for a JavaScript variable.

Global Variables: A global variable is visible throughout your JavaScript code since it has a global scope.

Local Variables: Local variables are only accessible within the function in which they are defined. The parameters of a function are always specific to that function.

15. List a few of the built-in methods along with the values they return.

Build-in MethodValues
ChatAt()Returnsoccurrence the character at the specified index.
Concat()Join two or more strings.
forEach()Calls the function for every element in the array.
indexOf()Returns the index in the calling String object of the first occurence of the specified value.
length()It returns the length of the string.
pop()It removes the last element from the array and returns that element.
push()Adds one or more elements at the end of an array and returns that element.
reverse()It reverses the order of the elements of an array.

16. What are the JavaScript variable naming conventions?

When naming variables in JavaScript, the following guidelines must be followed:

  • Any special word that is reserved by JavaScript are keywords and shouldn't be used as variable names. Break or boolean variable names, for instance, are invalid.
     
  • Variable names in JavaScript shouldn't begin with a number (0-9). They must either start with a letter or an underscore. For instance, name123 or _123name are acceptable variable names, whereas 123name is not.
     
  • Case matters in JavaScript variable names. As an illustration, Test, and test are two distinct variables.

17. How does the TypeOf Operator function?

To determine the data type of its operand, use the typeof operator. A literal or a data structure, such as a variable, function, or object, can serve as the operand. Before its sole operand, which can be of any type, it is a unary operator. Its value is a string that specifies the operand's data type.

18. Define undeclared and undefined variables?

Undeclared variables are not declared and don't exist in a program. A runtime error occurs if the software tries to read the value of an undefined variable.

Variables declared in the program but do not have a value are considered undefined variables. An undefined value is returned if the software tries to read the value of an undefined variable.

19. What are the escape characters in JavaScript?

When working with special characters like ampersands (&), apostrophes ('), double quotes (" "), and single quotes (' '), JavaScript uses escape characters, often backslash (\ \). JavaScript displays any characters that are contained within the escape.

  • \n – Newline
     
  • \r – Carriage return
     
  • \t – Horizontal tabulator
     
  • \v – Vertical tabulator
     
  • \b – Backspace
     
  • \f – Form feed

20. Define prompt box.

A prompt box is a box that offers a text box for the user to enter information. There will be a label and box where the text or number can be entered.

21. Differentiate between slice and splice.

Slice

Splice

It doesn't modify the original array(immutable).Modifies the original array(mutable).
Returns the subset of the original array.Its returns the deleted elements as an array.
It is used to pick the element from the array.It is used to insert or delete elements from an array.

22. Define the various types of error constructors supported by JavaScript?

The creation of an error object is the responsibility of the Error constructor. Runtime errors result in instances of the error objects being thrown. Additionally, user-defined exceptions can use the Error object as their base object.

JS supports seven error constructors along with the generic error constructor-

  • EvalError – Produces an instance of an error relating to the global function eval ().
     
  • InternalError – Creates an instance of an error relating to an internal JS engine error.
     
  • RangeError- A numeric variable or parameter that is outside of its valid range will result in a RangeError instance being created.
     
  • ReferenceError- Dereferencing an incorrect reference will create an instance of ReferenceError.
     
  • SyntaxError- When parsing code in eval, it creates an instance of an error relating to a syntax error ().
     
  • TypeError- Creates a TypeError instance when a parameter or variable's type isn't valid.
     
  • URLError- When invalid parameters are supplied to the decode URI() or encodeURI functions,  an error instance is created.

23. How is JavaScript code debugged?

By pressing the appropriate key, typically the F12 key, all contemporary web browsers, including Chrome, Firefox, and others, feature an integrated debugger that can be used anytime. The debugging tools provide users with a number of functions.

The code editor we use to create JavaScript applications, such as Visual Studio Code, Atom, Sublime Text, etc., also allows us to debug JavaScript code.

24. Differentiate between Windows & documents in JavaScript?

Windows

Document

The window of Javascript is a global object which holds variables, functions, locations, and history.This also comes under the window and can be understood as the property of the window.
It is the representation of the user’s browser window and represents the content of the webpage.It is the representation of any HTML document that is loaded on the browser
Global objects, functions, and variables of JavaScript are part of the window object.The HTML tags, elements, and their attributes are members of the Document.

 

25. Define arrow functions in JavaScript?

JavaScript functions are written using arrow functions, which are clear and concise. An arrow function's general syntax is as follows:

const welcome = () => {
  console.log("welcome to coding ninjas!");
};

26. Give some Javascript frameworks and their uses.

The development of online applications involves a variety of frameworks, many of which are available for JavaScript. Several well-known frameworks include:

  • React - Frontend development of the web application
     
  • Angular - Frontend development of the web application
     
  • Node - Backend or server-side development of the web application

27. Define event bubbling and event capturing.

In the HTML DOM API, there are 2 approaches for handling event propagation and the sequence in which events are received. Event Bubbling and Event Capturing are these. In the former, the event is aimed at its intended target; in the latter, it is directed toward a different element.

Event capturing: Also referred to as trickling, it is hardly used. The event is initially captured by the outermost element, which then propagates it to the innermost element.

Event Bubbling: This method involves handling the event in the innermost element before propagating it to the outermost element.

28. Define ways to empty an array in Javascript.

Some of the ways by which we can empty an array in Javascript are:

  • By giving the length of the array as 0:
var x = [1, 2, 3, 4];
x.length = 0;
  • By declaring an empty array:
var x = [1, 2, 3, 4];
x = [];
  • By popping the elements of the array:
var x = [1, 2, 3, 4];
while (x.length > 0) {
  x.pop();
}
  • By using the splice array function:
var x = [1, 2, 3, 4];
x.splice(0, x.length);

29. Give the output of the following code?

var Car = function Fun()
{
return 13;
};
typeof Fun();

Given that a function definition can only have one name for a reference variable, the result would be a reference error.

30. Define ways to remove duplicates from the Javascript array.

The different ways to remove duplicates in Javascript are mentioned below:

  • Filter method:

Three arguments are specified to call the filter() function. These are the array, element in use, and element index.
 

  • For loop:

All the recurring elements are kept in an empty array.

JavaScript Interview Questions for Experienced

 

31. Draw a simple Javascript DOM.

Javascript Dom

32. Define the symbols used for comments in Javascript.

The symbols for comments are given below:

// for Single line comments and

/* Multi
Line
Comment
*/

33. Define variable typing in Javascript.

A variable can be given a number by using variable type. A string can be given the same variable.

i = 13;
i = "coding ninjas";

This is called variable typing.

34. Define Javascript cookies.

When a user accesses a website to store information they need, small test files called cookies are created and kept in the user's computer. Examples include user name specifics and previous visit shopping cart data.

35. Give the disadvantages of using innerHTML in Javascript.

Some disadvantages of using innerHTML are given below:

  • Everywhere content is changed.
     
  • It is incompatible with "appending to innerHTML"
     
  • The old content gets replaced with html even if you use += like "innerHTML = innerHTML + 'html' ".
     
  • The full innerHTML document is parsed again and broken down into components. It is therefore slower.
     
  • Since the innerHTML does not validate, we may introduce legitimate but flawed HTML and cause the document to malfunction.

36. Give some advantages of using external Javascript.

External JavaScript is JavaScript code (script) created in a different file with the extension.js. This file is linked inside the <head> or body> element of the HTML file, depending on where the code is to be inserted. External Javascript has some benefits, including

  • It makes it possible for web developers and designers to work together on HTML and javascript files.
     
  • The code is reusable.
     
  • In external javascript, code readability is simple.

37. How is JavaScript using event handlers?

Events are the outcomes of activities, like the user clicking a link or completing a form. An event handler is needed to ensure that each of these events is carried out correctly. Event handlers are an additional object attribute. The name of the event and the course of action if the event occurs are included in it.

38. What is the difference between var and let keyword?

The var keyword is used to declare. The scope of this keyword is “function-scope,” which means that if a variable is declared using the var keyword, it could be accessed anywhere in the entire function or a program.

The ‘let ‘variable is also used to declare a new variable, but its scope is limited to a block, which means variables declared using the let keywords have block scope.

Let’s take an example to understand better:

The following examples take variables from the loop and display the result accordingly.

for (var a = 0; a < 5; a++) {
  console.log(a);
}
console.log(a);

Output

0
1
2
3
4
5

As the loop ended, we could still access the variable, and hence we can see 5 as the output in this scenario.

But if we try the same with “let” keyword :

for (let a = 0; a < 5; a++) {
  console.log(a);
}
console.log(a);

Output : 

0
1
2
3
4
file.js:4
console.log(a);
            ^


ReferenceError: a is not defined
    at Object.<anonymous> (HelloWorld.js:4:13)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

The above code will result in an error saying that the variable was not defined, as the variable’s scope was just in the loop. While we were trying to access it after the loop ended, the variable had to be defined again.

39. What is Hoisting in Javascript? 

The declarations of variables or functions are by default moved at the top of the entire code, making sure they are accessible everywhere in the program. The assignment of the variables happens only when they are declared. This property is known as Hoisting. 

For example –

The first important step is to declare a variable using let/var. The second is to initialize it or assign any value to the variable, and the last is the final step to use the variable. 

To understand it better, let’s consider the following code snippet :

console.log(a);
var a = 5; 

As the declaration and assignment are made after using the variable, we would get an Output as undefined.

 Output

undefined

But if we would have had the variable declared and assigned first, 

var a = 5;
console.log(a); 

Output

5

We would get five as the Output because we made the declaration before using the variable. 

40. What is ECMAScript?

ECMAScript(European Computer Manufacturers Association Script) is a scripting programming language based on JavaScript and is widely used for the World Wide Web for client-side scripting. It is an object-oriented programming language and is considered a core programming language.

41. What is the key difference between “==” and “===” in Javascript?

== (Equality Operator)=== (Identity Operator)

It converts the variable value to the same type before performing the comparison.

It follows type coercion.

It does not follow any type conversion and only returns true if both the values and types are identical for the variables in comparison.
It is less preferred than the Identical operator as it might give us unexpected results at times. It is widely preferred and gives us accurate results.

For example: “1” == true or “0” == false will give you true as the final answer.

It is more preferred over the Equality operator.

Let’s take an example to understand better : 

console.log(123==123);
console.log(123===123);

Output

true
true

In the above example, both operators were true as the final Output as it involved no type conversion. Hence, a simple equality condition has been checked for both of the cases. But let’s see if we try to compare a string value and an integer value now, 

console.log(123=="123");
console.log(123==="123");

Output

true
false

The above example shows that the double equals do not consider the change in data type and simply compare the variable’s value. In contrast, the triple equals compare the deals of the same data type. 

The double equals perform a type conversion and then compare the values. 

42. What is NaN in Javascript?

In Javascript, NaN stands for Not a Number. This property is used to check if the entered value is a valid number or not. NaN value gets generated when the value cannot be computed, or type conversion of the non-numeric value to the number is not a valid numeric.

For example, when we try to divide a 0 by 0. For any arithmetic operation in which one of the values is undefined Javascript returns NaN. 

We will get a NaN value in the following given scenarios: 

1. If any one of the operands is an arithmetic operation is undefined 

2. When we try to divide a number by 0 

3. When we try to multiply zero with infinity 

4. When we divide infinity by infinity 

Let’s see an example to understand it better : 

var cn = 0/ 0;
console.log(cn);

Output 

NaN

Javascript treats NaN like an actual number, which can be used to perform any number type operations.

43. What is asynchronous programming in Javascript? 

Asynchronous programming allows it to express waiting for long-running actions without freezing the program during these actions. JavaScript environments typically implement this programming style using callbacks, which are called when the actions are complete.

An event loop schedules such callbacks to be called when appropriate, one after the other, so their execution does not overlap.

44. What are the different iterable values in JavaScript?

The different types of inbuilt iterable values in Js are : 

  1. Arrays
  2. Strings
  3. Maps
  4. Sets
  5. DOM-based node lists

45. What will be the Output of 5+2+” 3″?

In Javascript, 

5 and 2 will be considered as integer values, and their sum will be 7 

But 3 is a string type variable,

So the final output will be the concatenation of both of these numbers leading the answer to be 73.

46. Is Javascript a case-sensitive language?

Yes, Javascript is a case-sensitive language. This means that the keywords,function-name, variable name all should be typed with a consistent capitalization of letters. The word let and LET will have different meanings in JS.So while using any variable or keyword, we should keep the case of the letters in mind.

47. What is the value of ans[0] in the below script?

const ans = ['jacket', 't-shirt'];
ans.length = 0;


ans[0]; // => ??? 

The length method used for arrays has a unique property that deletes the array values between the old and the new length. As the ans.length is set to 0, all the values in the array have been deleted. Hence the final answer is undefined. 

Ans[0] is undefined as the array has been emptied.

48. What is the difference between Object.freeze() and const? 

const applies only to the keywords and does not allow re-assigning a value to a const variable. 

Const variables cannot be redeclared or reassigned. The scope of a const variable is limited to block-scope. This means we cannot use a const variable declared in a block outside it. 

For example : 

{
const Pi = 3.14;
console.log(Pi);
}


// outside block
console.log(Pi); // error

Output :

3.14



Uncaught error: Pi is not defined

 Object.freeze() : It is applied to the objects in Javascript. It freezes the objects, which does not allow any new properties to be rendered in them. It also prevents any modifications to the existing properties, attributes and values. 

For example : 

let ans ={
Pi = 3.14
};
Object.freeze(ans);
ans.Pi = 3.145;
console.log(ans.Pi); // 3.14, the value will not be modified.

Output

3.14

49. What are Promises in Javascript?

A promise is an object which represents the eventual completion of either completion or failure of an asynchronous function.

There are three states of the Promise object :

  1. Pending: which is the initial state (before the promise succeeds or fails
  2. Resolved: When a promise is successfully completed 
  3. Rejected: When a promise is rejected(failed)

It can be created using a constructor.

var promise = new Promise(function(resolve, reject){
    //add body to the function
});

50. What is currying in JavaScript?

Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline. It helps to avoid passing the same variable again and again, also in creating high order functions.

function addcn(a, b, c) {
    return a + b + c;
}



function addcn_curried(a)//curried function {

    return function (b) {
        return function (c) {
            return a + b + c
        }
    }
}

let res = addcn(1, 2, 3);
console.log(res);

let mc1 = addcn_curried(1);
let mc2 = mc1(2);
let res2 = mc2(3);
console.log(res2);

let res3 = addcn_curried(1)(2)(3);
console.log(res3);

Output

6
6
6

JavaScript Coding Interview Questions

51. Define DOM in Javascript. 

Document Object Module (DOM) is not a part of Javascript, but it is a web API used to build websites. Using DOM, developers can create documents, navigate through them and modify, add accordingly to the document.

Also see, Html interview questions

52. What is the Javascript Event Delegation Model?

Event delegation allows us to attach a single event listener to a parent element, which will work for all descendants matching a selector, whether those descendants exist now or are added in the future.                                   

53. How to empty an array in JavaScript?

There are various methods to do so. Let’s discuss each one of them.

Suppose a[] = [1,2,3,4,5,6];

Method 1:

We can set the value of a [] = [];

The above method assigns a new array to the variable a, deleting its previous values.

Method 2: 

We are aware of the JS array.length function, this function deletes the values of the array within a defined value.

We can empty an array ‘a’ by simply assigning, 

a.length = 0;

Method 3:

We can use a pop() method to delete all the elements of the array till the array.length is true.

while(a.length)
{
a.pop()
}

Method 4:

The splice method in array.splice(cuts) the array from a defined initial value till the final value.

It requires two parameters (initial, final) values from the user. 

In the above example, to delete all the elements of an array, we can write the following code:

a.splice(0,a.length);

54. How can you create a cookie using Javascript?

Cookies are data stored on your system and were invented so that the browser can remember a few details about the user. 

We can create a cookie by simply assigning a string value to document.cookie object. 

We can not only create but read, delete cookies using this document. cookie property.

We can create Javascript Cookies using :

document.cookie = "Coding Ninjas";

55. Name a few Javascript frameworks.

Best Javascript frameworks to use today are :

  1. Angular
  2. React
  3. Vue.Js
  4. ember.Js
  5. Meteor

56. What is Strict mode in JS?

It is a stricter or secured version of ordinary javascript language that produces errors for those mistakes handled silently otherwise. It was introduced in ECMAScript 5.

For example : 

In normal Js, if we try to run the below commands 

a=10;
console.log(a);

We will not get an error as the compiler would by default consider ‘a’ as a ‘var’ data type.

But if we use strict Js, we would get an error if we try to run the above code stating a is not defined.

57. What is the difference between a null, undefined, and undeclared variable in Javascript?

We can assign null as a value to any variable.

A variable is said to be undefined when its value is yet to be assigned.(empty variable)

A variable is said to be undeclared when it is not assigned any data type. When a variable is not even declared and used, the compiler will give us an error stating that the variable is not defined.

For example:

var a = null; // null is assigned to a variable
var b;
console.log(b);// b does not hold any value
console.log(c);//c is not declared

Output:

null
undefined


HelloWorld.js:5
console.log(c);//c is not declared 
            ^
ReferenceError: c is not defined
    at Object.<anonymous> (HelloWorld.js:5:13)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11
 

58. Explain array.slice and array.splice in Js

1) The slice() method copies a given part of the array and returns it. It does not modify the original array.

array.slice(inital,final) 

2) Array.splice method is used to remove the items of the selected array and does not form another array. This method modifies the original array. Array.splice can be used to add or remove elements from the array. 

59. Determine the Output of the following code.

var courses = ["JavaScript","Java","C","C++","Python"];
delete courses[2];
console.log(courses.length);

The delete function does not affect the array’s length as the operator deletes only the value present at the given position. 

Hence the Output would be 5. 

We will have an empty value in the ‘C’ course in the array courses.

60. What are IIFEs?

Immediately Invoked Function Expressions are also called Self Executing Anonymous Functions, executed immediately after their definition.

It contains two major parts :

  1. The first is the anonymous function in the given scope enclosed within ‘()’
  2. The second part is the immediately invoked function expression through which the Js interpreter will directly interpret the function. 

61. What are ArrayBuffers?

ArrayBuffers is a data type used to store a generic, fixed-length binary data buffer. We cannot directly modify the contents of an ArrayBuffer, but we can create a typed view or a DataView, that is used to read or write the contents of the buffer.

let buffer = new ArrayBuffer(16);

The above statement creates a buffer of a fixed length of 16 bytes. 

62. What is Callback hell?

Callback hell is also known as the Pyramid of Doom. It is an anti-pattern of multiple nested callbacks, making it difficult to read or debug the code. It is a slang term used to define multiply nested if statements or functions.

async1(function() {
    async2(function() {
        async3(function() {
            async4(function() {
                ....
            });
        });
    });
});

63. What is the difference between a window and a document?

The window is the first thing that gets loaded into the browser. This window object has most properties like length, innerWidth, innerHeight, name if it has been closed, its parents, and more. The window object refers to the browser window.

The document object is your HTML, ASPX, PHP, or another document that will load into the browser. The document gets loaded inside the window object and has properties like title, URL, cookie, etc.

64. Explain Arrow functions. 

Arrow Functions are a new concept of ES, as they allow us to create smaller and cleaner functions. 

For example : 

let a = function(a,b){
  return a +b ;
}
 

We can write the above function as, 

// using arrow functions

let a = (a, b) => a * b;

65. What is the Output?

console.log(typeof typeof 1);

typeof method returns the data type of the given variable. 

Here, typeof 1 will return ‘number’

typeof’ number’ will return a string.

The answer is String. 

66. What is a WeakMap in Javascript?

In a WeakMap, the keys are objects instead of primitive values. It is known as a directory where all the keys are weak. Weak maps provide a way to extend objects without interfering with garbage collection.

67. What are the limitations of Javascript?

  1. It cannot write files on the server.
  2. Due to security reasons, every web browser provides an option to disable javascript.
  3. Developers cannot use it for network applications.
  4. We need AJAX and a server-side script to access Databases
  5. It is not engine-friendly.
  6. It cannot access web pages hosted on different domains. 

 

Must Read Difference Between "var", "let" and "const" in JS 

JavaScript MCQ

1.What is used to enforce the restricted variant of JavaScript?

A. "use strict;"

B. ‘use strict;’

C. Both A and B

D. None of the above

Answer: C. Both A and B

2. What is the <noscript> tag used for?

A. To display the contents by non-JavaScript based browsers

B. Clear the cache

C. Both A and B

D. None of the above

Answer: A. To display the contents by non-JavaScript based browsers.

3. Give the Output of the following code

print(Nan === Nan)

A. True

B. False

C. Compile Time Error

D. Undefined

Answer: B. True

4.What does JavaScript print when there is an indefinite or an infinite value during an arithmetic computation in a program?

A. Prints runtime error

B. Prints outOfBound exception

C. Displays “infinity”

D. Displays “undefined”

Answer: C. Displays “infinity”

5. What is used for calling function definitions in JavaScript?

A. Function calling

B. Function prototype

C. Function declaration

D. Function literal

Answer: D.Funciton literal

6. Which operator is used to check if a property exists or not?

A. Exist

B. Within

C. in

D. Exists

Answer: C.in

7. What is used to make the function appear to be synchronous?

A. async

B. await

C. resolve

D. None of the above

Answer: B. await

8.What is the output of the following code?

let randomValue = { name: "Ninjas" }
randomValue = 15

if (!typeof randomValue === "string") {
	console.log("It's not a string.")
} else {
	console.log("It's a string.")
}

A. It's not a string.

B. It's a string.

C. Undefined error

D. TypeError

Answer: B. It's a string.

9.Which of the following modified the person_name object in the code below?

const person_name = { name: 'Ninja Codes' };

Object.seal(person_name);

A. name.person_name = “Coding Ninja”

B. delete person_name.name

C. person_name.age = 23

D. person_name.name = “Coding Ninja”

Answer:D. person_name.name = “Coding Ninja”

10.Which of the following is a stateless protocol?

A. HTTP

B. XHTML

C. HTML

D. All of the above

Answer: A. HTTP

Frequently Asked Questions

Q. What is JavaScript basic interview questions?

Some common JavaScript interview questions include: What is JavaScript? What are the data types in JavaScript? What is the difference between null and undefined in JavaScript? What is the use of closures? What are the different ways to declare variables in JavaScript? 

Q. How to prepare JavaScript for interview?

For preparing for an interview for JavaScript, you should review the basics of the language, practice some coding questions and get familiar with the libraries and frameworks of JavaScript. Revise concepts such as callbacks, asynchronous programming and closures.

Q. What is object in JavaScript interview questions?

Objects are the fundamental data types in JavaScript. They are primarily used to store key-value pairs where keys are of the string datatype and the value can be of any other JavaScript data type. They contain functions or methods which associate with it.

Q. What is BOM in JavaScript interview questions?

BOM stands for Browser Object Model. It is a set of APIs which are provided by the web browsers to interact with the browser itself and its components. In JavaScript, BOM provides properties and methods to interact with the web browser.

Q. Which company developed JavaScript? 

JavaScript was developed by Netscape Communications Corporation, with Brendan Eich creating the initial prototype in 10 days in 1995.

Q. Does JavaScript support automatic type conversion? 

Yes, JavaScript supports automatic type conversion, also known as type coercion. This feature allows variables to change data types during operations based on context.

Q. Explain hoisting in JavaScript. 

Hoisting in JavaScript refers to the mechanism where variable and function declarations are moved to the top of their containing scope during compilation. This allows variables to be used before they are declared.

Q. What is the strict mode? 

Strict mode is a feature in JavaScript introduced in ECMAScript 5 that enforces stricter parsing and error handling, aiming to eliminate silent errors and promote writing cleaner JavaScript code. It enables better performance optimizations and improves security.

Conclusion

This article contains the Javascript interview questions and answers for both freshers and experienced applicants. These javascript interview questions and answers will help build the basics of Javascript. Javascript interview questions and answers explained above are simple and concise. We hope you gained knowledge regarding the most often asked Javascript interview questions and answers.

Live masterclass