Hey everyone👋🏻, In this article, we are going to see the top asked Javascript interview questions and answers. Nowadays, Javascript becomes very popular in web development.

The most used language in the web application is JavaScript, and the web project is incomplete without it. It becomes one of the popular languages which can be used on the Client-side as well as Server-side since the Node.js launch.

The most popular framework which is made by Google and Facebook are also written in JavaScript. If you are looking to make a career in Web development, then this would be the best option to learn and start your career.

Javascript is mostly used in Frontend development, Game Development, Web designing, and Mobile Development.


We are going to learn JavaScript, by answering the most frequently asked javascript interview questions.

Q1. What is JavaScript?

The JavaScript language is a lightweight, interpreted language that can be used to create interactive HTML pages that are otherwise static.
JavaScript is the most popular web scripting language used for both client-side and server-side development.

Q2. What are the features of JavaScript?

1. JavaScript is a lightweight, interpreted programming language.
2. Designed for creating network-centric applications.
3. Complementary to and integrated with Java & HTML.
4. Open and cross-platform.

Q3. Explain the various JavaScript datatypes?

JavaScript supports the following data types:
1. Boolean
2. Object
3. Undefined
4. Number
5. Symbol
6. Null
7. String

Q4. What are the ways to define a variable in JS?

In JavaScript, you can define variables in three different ways:
Var – The JavaScript variables statement declares a variable and, optionally, initializes its value. Example: var a =10; Variable declarations are processed before code execution.
Const – Const functions are not permitted to modify the object to which they are called. A const function can be called on any type of object.
Let – It tells us that the variable may be reassigned, as with a counter in a loop, or a value swap in an algorithm. It indicates that the variable will only be used in the block in which it is defined.

Q5. What is the DOM?

1. A Document Object Model is a programming interface for HTML and XML documents.
2. When the browser tries to render an HTML document, it creates an object based on the HTML document called DOM.
3. Using this, we can manipulate or change various elements inside the HTML document.

Q6. How can you create an object in JavaScript?

Object concepts are well supported in JavaScript. Using the object literal, you can create an object as follows −
var emp = {
name: "Michael",
age: 28
};

Q7. How can you create an Array in JavaScript?

The array literal can be used to define arrays as follows:
var x = [];
var y = [1, 2, 3, 4, 5];

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

Yes, we can assign an anonymous function to a variable. Moreover, it can be passed as an argument to another function, which is also called the Higher-Order Function.

Q9. What is Higher Order Function?

Higher-Order Function that operates another function, either by taking them as arguments or by returning them.
ex.
function high (fn) {
fn();
}
high(function() {  /**code**/  });

Q10. What are argument objects in JavaScript & How to find the type of arguments passed to a function?

JavaScript variable arguments represent the arguments passed to a function. We can get the type of arguments passed to a function with the typeof operator. For example:
func() // undefined, 0 type
func(23) // Number type
func('hello') // String type

Q11. What is the purpose of the ‘this’ operator in JavaScript?

‘this’ keyword refers to the object that the function is a property of. Depending on where it is used, it has different values
function() {
console.log(this);
}
This above function is a property of global object. And the global object is window object.

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

The scope of a variable is the area of your program in which it is defined. JavaScript variables will have three scopes –
Global Variables − Global variables have a global scope, which means they are accessed from anywhere, inside the code.
Local Variables − A local variable is only visible in the function where it is defined. The parameters of a function are always local to that function.
Block Variables – A block variable cannot be accessed outside the block. Variable let and const have block scope.
For example:
{
let x = 10;
}
console.log(x); // gives you error as it is outside of the block.

Q13. What is Closure?

A closure is created whenever a variable definition that is defined outside of the current scope is accessed from inside another scope. It allows you to access an outer function’s scope from an inner function. When a JavaScript function is created, a closure is created too. You can use closure by simply defining it within another function and exposing it.

Q14. What is Callback?

A callback is a function that will be executed after another function gets executed. The function that is used as an argument to another function is called the Callback function.

Q15. What is Recursion?

Function which call itself repeatidly until it arrives at a result.

Q16. What are the variable naming conventions in JavaScript?

1. You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. 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 an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
3. JavaScript variable names are case-sensitive. For example, Name and name are two different variables.

Here are the examples:-
var name; // correct
var 2name; // incorrect
var _2name; // correct

Q17. How does TypeOf Operator work?

You can use the typeof operator to find the data type of a JavaScript variable. An operand can either be a literal or a data structure like a variable, a function, or an object. As a unary operator, it is placed before its single operand, which may be of any type. The value of this field is a string indicating the data type of the operand.

Q18. What is the difference between Rest & Spread operators?

1. Rest parameter should always be used as the last parameter of the function. It is used to take several arguments and turn them into an array. Whereas the Spread operator takes an array or an object and spreads it.
2. Rest is used in a function declaration, whereas the Spread operator is used in function calls.

Q19. How to create a cookie using JavaScript?

1. A cookie is simply data, usually small, sent from a website and stored on the user’s computer by the web browser used to access the website.
2. It is a reliable way for websites to remember stateful information and record the user’s browsing activity.
A cookie is simply data, usually small, sent from a website and stored on the user’s computer by the web browser used to access the website.
It is a reliable way for websites to remember stateful information and record the user’s browsing activity.
document.cookie = key1 = value1; key2 = value2; ; keyN = valueN; expires = date;

Q20. How to read a cookie using JavaScript?

1. Reading a cookie using JS is as simple as creating.
2. Cookie object is the cookie, use this string whenever you wish to access the cookie.
3. The document.cookie string keeps a list of name = value pairs, where a semicolon separates each pair.
4. The name represents a cookie’s name, and the value represents the respective cookie’s string value.
5. For breaking the string into key and value, you can use the split() method.

Q21. How to delete a cookie using JavaScript?

1. Simply setting the expiration date (expires) to a time that’s already passed.
2. Some web browsers don’t let you delete a cookie unless you don’t specify the cookie’s path.
3. Hence, defining the cookie path is important to ensure that the right cookie is deleted, assign a string value to the document.

Q22. What is Object Destructuring? How it is useful?

It is a new way to extract elements from an object or an array. You don’t need to initialize the individual variables. It is easy to use, understand, and readable.
For example:
var {var1, var2, var3} = {'one', 'two', 'three'}

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

The following are the ways through which an HTML element can be accessed in Javascript:
1. getElementById(‘idname’): Retrieves an element by its ID.
2. getElementsByClass(‘classname’):Returns all elements with the given classname.
3. getElementsByTagName(‘tagname’): Returns all elements with the given tagname.
4. querySelector(): Returns the first element selected by a CSS style selector.

Q24. What is the difference between Attributes and Property?

When writing HTML source code, you can define attributes on your HTML elements. 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:
<input type="checkbox" checked="true">

In this example the DOM element input has the property type with the value “checkbox” and the property checked with the value true.

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

An HTML file can involve JavaScript code in one of three different ways:
1. Inline: Inline functions are JavaScript functions that are assigned to variables at runtime. They can be distinguished from anonymous functions since they are assigned to a variable and can be reused.
2. Internal: JavaScript code is placed in the head and body section of an HTML page.
3. External: We use the external javascript by passing the source path in the script tag into our HTML page.

Q26. Explain difference between event.preventDefault() and event.stopPropagation() ?

1. The event.preventDefault() method prevents the default behavior of an element. If used in a form element it prevents it from submitting.
2. While the event.stopPropagation() method stops the propagation of an event. It stops the event from occurring in the bubbling or capturing phase. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.

Q27. Explain pop(), shift() and unshift().

pop() – it removes the last element from the array.
shift() – it removes the element from the start of the array.
unshift() – push or adds the value at the beginning of the array.

Q28. 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 client-server traffic. If you don’t manually clear it through the settings or programs, it will stay.
Session Storage – While session storage is similar to local storage, the only difference is that local storage has no expiration date while session storage gets cleared when the page session ends. The browser will terminate the Session Storage after it is closed.

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

The major difference between “==” and “===” is that “==” compares variables by making type corrections, e.g. the number with a string with numeric literal, “==” allows that, but “===” doesn’t allow that, because it is not only checks the value, but also the datatype of two variable if two variables have different type “===” return false, while “==” return true.

Q30. What is the difference between undeclared & undefined?

Variables that are not declared in a program are called undeclared variables. An undeclared variable leads to a runtime error if the program attempts to read the value of the variable.
Variables declared in the program but not assigned a value are undefined variables. When the program attempts to read a value from an undefined variable, it returns an undefined value.

Q31. What is the difference between null & undefined?

A variable that has been declared but not yet assigned a value is undefined.
Null is an assignment value. This value can be assigned to a variable as a representation of no value. Furthermore, undefined and null are distinct types: undefined is a type itself (undefined), and Null is an object.

Q32. What is call() and apply() functions?

When the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement.
Similar to call() but the only difference is we don’t know the number of parameters in the function. So, we can pass the array like ([2, 3]) instead of (2, 3).

Q33. What is the difference between Window & Document in JavaScript?

Window: Objects with variables, functions, history, and locations are stored in JavaScript windows.
Document: Documents also fall under the window and can be considered as properties of the window.

Q34. What is the Strict mode in JavaScript and how can it be enabled?

A strict mode introduces better error-checking into your code.
1. The strict mode does not allow you to use implicitly declared variables, assign value to read-only properties, or add properties to objects that cannot be extended.
2. To enable strict mode, add “use strict” to the beginning of a file, a program, or a function.

Q35. What are Promises? How many types of states?

It is used to handle asynchronous operations in javascript.
Before promises, callbacks were used to handle asynchronous operation. But due to limited functionality of callback, using multiple callbacks to handle async code can lead to unmanageable code.

It has four states:-
1. Pending – represents it is in pending state.
2. Fulfilled – has been fulfilled, async operation is completed.
3. Rejected – Rejected for some reason (failed).
4. Settled – either rejected or fulfilled.

So, that’s all about the Javascript top interview questions with answers. You have to practice a lot with these questions, these questions are based on the beginner to medium level of an experienced person.

I hope you enjoyed the article and if you found it useful, please share it with your friends and colleagues. If this post helps you, spread this so that other people can also benefit.

If you have any queries please feel free to post them in the comments section or anything that you wanted to ask through mail contact.

Thank you😉

Also, read

What is WhatsApp’s Zero-Day Vulnerability Leading Users into Danger? WhatsApp Call Links Features Starts Rolling Out To Users, What it Does JioPhone 5G Specs Surface: Tipped to get Snapdragon Chipset, 5,000mAh Can Moonlighting Be Allowed?- Global HR Experts’ Perspective Capgemini Off Campus Drive 2022 | Freshers | Engineering | PAN India Java Developer Salary in India – For Freshers & Experienced Flipkart Big Billion Days Sale Ends on Sept 30: Best 5G Phone Deals DA Hike: Good news, Waiting for Central Employees is over, Important Update On Dearness Allowance How will 5G India launch impact the lives of Indians? How to Check PNR Status and Live Train Status on WhatsApp