Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Top 90+ JavaScript Interview Questions and Answers for 2025

Last updated on Dec 06,2024 872K Views

A Data Science Enthusiast with in-hand skills in programming languages such as... A Data Science Enthusiast with in-hand skills in programming languages such as Java & Python.
1 / 2 Blog from Interview Questions

As of 2024, there are approximately 370.8 million JavaScript libraries and functions detected on the web. Additionally, JavaScript is detected on around 6.5 million of the top million websites. All leading web browsers support JavaScript, demonstrating its ubiquity in the web development domainToday, 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.

So, this is the perfect time to get started if you want to pursue a career in JavaScript and learn the required skills. Our JavaScript Interview Questions, JavaScript training, and Java Training program can help you gain in-depth information and prepare for your interviews.

JavaScript Interview Questions and Answers | Full Stack Web Development Training | Edureka

This Edureka video on “JavaScript Interview Questions” will help you to prepare yourself for JavaScript Interviews.Learn about the most important JavaScript interview questions and answers and know what will set you apart in the interview process.

The JavaScript interview questions are divided into three sections:

Let’s begin with the first section.

Beginner Level JavaScript Interview Questions for Freshers

Q1. 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.

Q2. What is the difference between Java & JavaScript?

JavaJavaScript
Java is an OOP programming language.JavaScript is an OOP 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.

Q3. What are the data types supported by JavaScript?

The data types supported by JavaScript are:
String- This data type is used to represent a sequence of characters.
Example:

var str = "Akash Sharma"; //using double quotes
var str2 = 'David Matt'; //using single quotes

Number- This datatype is used to represent numerical values.
Example:

var x = 25; //without decimal
var y = 10.6; //with decimal

Boolean- This datatype is used to represent the boolean values as either true or false.
Example:

var a = 4;
var b = 5;
var c = 4;
(a == b) // returns false
(a == c) //returns true

Symbol- This datatype is a new primitive data type introduced in JavaScript ES6. Symbols are immutable (they cannot be modified) and one-of-a-kind.
Example:

// two symbols with the same description

const value1 = Symbol('hello');
const value2 = Symbol('hello');

console.log(value1 === value2); // false

Null- It indicates a value that does not exist or is invalid.
Example:

var a = null;

Object- It is used to store collection of data.
Example:

// Object
const student = {
firstName: 'Arya',
Roll number: 02
};

Q4. What are the features of JavaScript?

Features - JavaScript Interview Questions

Following are the features of JavaScript:

  • It is a lightweight, interpreted programming language.
  • It is designed for creating network-centric applications.
  • It is complementary to and integrated with Java.
  • It is an open and cross-platform scripting language.

Q5. 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.

Q6. What are the advantages of JavaScript?

JavaScript advantages - JavaScript interview questionsFollowing 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.

Check out Java Interview Questions to learn more about Java!

Q7. 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
};

Q8. Define anonymous function.

In JavaScript, an anonymous function is a function that does not have a name. It is typically used for short, one-off tasks where naming the function is not essential.

Example:

function(parameters) {
// body of the function
}

Q9. 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];

Q10. 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
}

Web Development Full Course for Beginners

 

Q11. 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.
If you wish to learn JavaScript and build your own applications, then check out our Full Stack developer course online, which comes with instructor-led live training and real-life project experience.
It includes training on Web Development, jQuery, Angular, NodeJS, ExpressJS and MongoDB.

 

Q12. 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. For example −


function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(7); //==> "number", 1
func("1", "2", "3"); //==> "string", 3

Q13. 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.

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

In JavaScript, this keyword refers to the object it belongs to. Depending on the context, this might have several meanings. This pertains to the global object in a function and the owner object in a method, respectively.

Q15. What is Callback?

A simple JavaScript function that is sent as an option or parameter to a method is called a callback. The function is called “call back” because it is meant to be invoked after another function has completed running. Functions are objects in JavaScript. This means that other functions can return functions and accept functions as arguments.

CallBack - Edureka

Q16. 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.

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

Built-in MethodValues
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.

Q18. 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.

Q19. 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.

Q20. 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-

Syntax :


document.cookie = "key1 = value1; key2 = value2; expires = date";

Q21. 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.

 

Q22. 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.

Q23. Explain call(), apply() and, bind() methods.

In JavaScript, the `call()`, `apply()`, and `bind()` methods are used to manipulate the execution context and binding of functions. They provide ways to explicitly set the value of `this` within a function and pass arguments to the function.

  1. `call()`: The `call()` method allows you to invoke a function with a specified `this` value and individual arguments passed in as separate parameters. It takes the context object as the first argument, followed by the function arguments.

“`javascript

function greet(name) {

  console.log(`Hello, ${name}! My name is ${this.name}.`);

}

const person = {

  name: ‘John’

};

greet.call(person, ‘Alice’);

// Output: Hello, Alice! My name is John.

“`

In this example, `call()` is used to invoke the `greet()` function with the `person` object as the execution context and the argument `’Alice’`.

  1. `apply()`: The `apply()` method is similar to `call()`, but it accepts arguments as an array or an array-like object. It also allows you to set the `this` value explicitly.

“`javascript

function greet(name, age) {

  console.log(`Hello, ${name}! I am ${age} years old.`);

  console.log(`My name is ${this.name}.`);

}

const person = {

  name: ‘John’

};

 

greet.apply(person, [‘Alice’, 25]);

// Output: Hello, Alice! I am 25 years old.

//         My name is John.

“`

In this example, `apply()` is used to invoke the `greet()` function with the `person` object as the execution context and an array `[‘Alice’, 25]` as the arguments.

  1. `bind()`: The `bind()` method creates a new function that has a specified `this` value and, optionally, pre-defined arguments. It allows you to create a function with a fixed execution context that can be called later.

“`javascript

function greet() {

  console.log(`Hello, ${this.name}!`);

}

const person = {

  name: ‘John’

};

const greetPerson = greet.bind(person);

greetPerson();

// Output: Hello, John!

“`

In this example, `bind()` is used to create a new function `greetPerson` with the `person` object as the fixed execution context. When `greetPerson()` is called, it prints `”Hello, John!”`.

The key difference between `call()`, `apply()`, and `bind()` lies in how they handle function invocation and argument passing. While `call()` and `apply()` immediately invoke the function, `bind()` creates a new function with the desired execution context but doesn’t invoke it right away.

These methods provide flexibility in manipulating function execution and context, enabling the creation of reusable functions and control over `this` binding in JavaScript.

Q24. Explain Hoisting in JavaScript.

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the actual code execution takes place. This means that you can use variables and functions before they are declared in your code.

However, it is important to note that only the declarations are hoisted, not the initializations or assignments. So, while the declarations are moved to the top, any assignments or initializations remain in their original place.

In the case of variable hoisting, when a variable is declared using the `var` keyword, its declaration is hoisted to the top of its scope. This means you can use the variable before it is explicitly declared in the code. However, if you try to access the value of the variable before it is assigned, it will return `undefined`.

 

For example:

 

“`javascript

console.log(myVariable);  // Output: undefined

var myVariable = 10;

console.log(myVariable);  // Output: 10

“`

 

In the above example, even though `myVariable` is accessed before its declaration, it doesn’t throw an error. However, the initial value is `undefined` until it is assigned the value of `10`.

 

Function declarations are also hoisted in JavaScript. This means you can call a function before it is defined in the code. For example:

 

“`javascript

myFunction();  // Output: “Hello, World!”

 

function myFunction() {

  console.log(“Hello, World!”);

}

“`

In this case, the function declaration is hoisted to the top, so we can call `myFunction()` before its actual declaration.

It’s important to understand hoisting in JavaScript to avoid unexpected behavior and to write clean and maintainable code. It is recommended to declare variables and functions at the beginning of their respective scopes to make your code more readable and prevent potential issues related to hoisting.

Q25. What is the difference between exec () and test () methods in JavaScript?

The `exec()` and `test()` methods are both used in JavaScript for working with regular expressions, but they serve different purposes.

 

  1. `exec()` method: The `exec()` method is a regular expression method that searches a specified string for a match and returns an array containing information about the match or `null` if no match is found. It returns an array where the first element is the matched substring, and subsequent elements provide additional information such as captured groups, index, and input string.

 

“`javascript

const regex = /hello (w+)/;

const str = ‘hello world’;

const result = regex.exec(str);

 

console.log(result);

// Output: [“hello world”, “world”, index: 0, input: “hello world”, groups: undefined]

“`

 

In this example, the `exec()` method is used to match the regular expression `/hello (w+)/` against the string `’hello world’`. The resulting array contains the matched substring `”hello world”`, the captured group `”world”`, the index of the match, and the input string.

 

  1. `test()` method: The `test()` method is also a regular expression method that checks if a pattern matches a specified string and returns a boolean value (`true` or `false`) accordingly. It simply indicates whether a match exists or not.

 

“`javascript

const regex = /hello/;

const str = ‘hello world’;

const result = regex.test(str);

 

console.log(result);

// Output: true

“`

 

In this example, the `test()` method is used to check if the regular expression `/hello/` matches the string `’hello world’`. Since the pattern is found in the string, the method returns `true`.

In summary, the main difference between `exec()` and `test()` is that `exec()` returns an array with detailed match information or `null`, while `test()` returns a boolean value indicating whether a match exists or not. The `exec()` method is more suitable when you need to extract specific match details, while `test()` is useful for simple pattern verification.

Q26. What is the difference between the var and let keywords in JavaScript?

The var and let keywords are both used to declare variables in JavaScript, but they have some key differences.

Scope

The main difference between var and let is the scope of the variables they create. Variables declared with var have function scope, which means they are accessible throughout the function in which they are declared. Variables declared with let have block scope, which means they are only accessible within the block where they are declared.

For example, the following code will print the value of x twice, even though the second x is declared inside a block:

JavaScript

var x = 10;

{

var x = 20;

console.log(x); // 20

}

console.log(x); // 10

 

If we change the var keyword to let, the second x will not be accessible outside the block:

JavaScript

let x = 10;

{

let x = 20;

console.log(x); // 20

}

console.log(x); // ReferenceError: x is not defined

 

Hoisting

Another difference between var and let is that var declarations are hoisted, while let declarations are not. Hoisting means that the declaration of a variable is moved to the top of the scope in which it is declared, even though it is not actually executed until later.

For example, the following code will print the value of x even though the x declaration is not actually executed until the console.log() statement:

JavaScript

var x;

console.log(x); // undefined

x = 10;

 

If we change the var keyword to let, the console.log() statement will throw an error because x is not defined yet:

JavaScript

let x;

console.log(x); // ReferenceError: x is not defined

x = 10;

 

Redeclaration

Finally, var declarations can be redeclared, while let declarations cannot. This means that you can declare a variable with the same name twice in the same scope with var, but you will get an error if you try to do the same with let.

For example, the following code will not cause an error:

JavaScript

var x = 10;

x = 20;

console.log(x); // 20

 

However, the following code will cause an error:

JavaScript

let x = 10;

x = 20;

console.log(x); // ReferenceError: x is not defined

The var and let keywords are both used to declare variables in JavaScript, but they have some key differences in terms of scope, hoisting, and redeclaration. In general, it is recommended to use let instead of var, as it provides more predictable and reliable behavior.

Q27. Why do we use the word “debugger” in JavaScript?

“Debugger” in JavaScript is a tool or feature that helps writers find and fix mistakes in their code. It lets them stop the code from running, look at the variables, and analyse phrases to find bugs or strange behaviour and fix them. The word “debugger” comes from the idea of getting rid of “bugs” or mistakes, which is how early engineers fixed problems with hardware.

Q28. Explain Implicit Type Coercion in JavaScript.

In JavaScript, implicit type coercion is when values are automatically changed from one data type to another while the code is running. It happens when numbers of different types are used in actions or comparisons. JavaScript tries to change the numbers into a type that the action can use. Implicit pressure can be helpful, but it can also make people act in ways you didn’t expect, so it’s important to know how it works.

Q29. Is JavaScript a statically typed or a dynamically typed language?

Javascript is a dynamically typed language , because variable types are determined at runtime,rather than being explicitly declared and enforced at compile time as in statically typed languages.

You can assign different types of values to the same variable without causing a type error,as the language determines the type based on the value at the moment it is assigned.

Q30. What is an Immediately Invoked Function in JavaScript?

An immediately Invoked Function Expression(IIFE) is a function in javascript that is defined and executed after it is created.

Often used to create a local scope  for variables,preventing them from polluting the global scope.

It typically involves wrapping a function expression in parentheses,followed by another set of parentheses to execute it.


(function(){

Var localvariable = “hello world”;

console.log(localvariable);

})();

Q31. What are some advantages of using External JavaScript?

1. Scalability:

When your project grows, maintaining and scaling become necessary. In that case, we use external Javascript rather than inline script.

2. Performance:

When the project is live on a browser, browsers can cache external javascript files. When the file is downloaded,it can be stored locally, reducing load times for subsequent page loads and improving the performance.

3. Reusability:

External javascript files can be reused across multiple HTML pages,so you don’t have to duplicate your code.This not only saves time but helps maintain consistency across your website.

4. Organization :

Javascript in separate files helps keep your HTML document clean and organized.You can easily locate your file.

5. Security:

If your Javascript is in an external file, it sometimes helps prevent certain types of attack, such as cross-site scripting (XSS).

Q32. Explain Scope and Scope Chain in JavaScript.

Scope refers to the accessibility of variables, functions, and objects in a particular part of the code.

This also determines where the elements can be accessed and manipulated.

Two main types of scope are:

1. Global scope:

Variables and functions which are defined in global scope are accessible throughout the entire script.

For eg:


Var globaledureka =”Hello everyone welcome”;

 

Function someFun(){

console.log(globaledureka);

}

 

someFun();

2. Local scope:

Variables which are declared within a function are only accessible within that function.

Fro eg:


Function somefun() {

Var localed=”hello everyone ”;

console.log(localed);

}

 

somefun();

console.log(localed);

3. Scope Chain:

This is a mechanism in JavaScript that is used to resolve variable names when they are accessed.

The scope chain ensures that javascript has a structured way to resolve variables and handle variable lookups (especially in cases where variables have the same name but different scopes).

For eg:


Var edureka =” I am good at coding”;

Function outerfunc(){

Var outer =”I am a machine learning beginner”;

 

Function innerfunc(){

 

Var inner =”I am a artificial intelligence beginner”;

 

console.log(inner);

console.log(outer);

console.log(global);

 

}

innerfunc();

 

}

outerfunc();

Q33. What are object prototypes?

Object prototypes in JavaScript are a fundamental concept that enables inheritance and the sharing of properties and method objects.

The prototype object can have its own prototype. Forming a chain known as the prototype chain.

Key points:

1.prototype property(‘_proto_’);

Every javascript object has an internal property called ‘_proto_’ or([[prototype]]);

2. Prototype object:

Prototype objects provide shared properties and methods  to other objects.

3. Constructor function and prototype:

For eg:


Function edureka(mess){

this .mess=mess;

}

edureka.prototype.edML=function{

console.log(“hello,welcome to the company ${this.mess}”);

};

Var AP=new edureka(“Ap”);

AP.edML();

Q34. What are the types of errors in javascript?

Errors in javascript can be broadly classified into several types and each represents a different kind of problem.

1. Syntax Errors:

If your language does not follow the javascript languages syntax rules.


if(true{

console.log(“this will cause a syntaxerror”);

}

2. Reference Errors

When variables that has not been declared or is out of scope is referred by script;

Foreg:

console.log(nonExistentVariable)

3. Type errors

When an operation is performed on a value of an inappropriate type,such as calling a non-function as a function or accessing a property on an undefined value.

For eg:


Var edureka=34

num.toUpperCase();

4. Range Errors:

When the numeric value is outside the allowable range then this error occurs.

For eg:


Ver edureka=1;

edureka.toExponential(500);

5. URI errors:

When there is an incorrect use of global URI handling function like ‘decodeURIComponent()’ or ‘encodeURIComponent()’

decodeURIComponent(‘%’);

6. Eval Errors(not commonly encountered ):

If eval function is used improperly.

But ‘EvalError’ objects are not commonly used and are kept for compatibility with older version of javascript.

7. Aggregate Errors:

When multiple errors occurred simultaneously.

They were introduced in ECMAScript 2021 and can be used in conjunction with ‘promise.any()’ and similar cases.

Q35. What is memoization?

Memoization is used for optimization and  to speed up your execution by storing the results of  function calls and reusing those outputs when the same inputs occur again.This will also reduce the time complexity.

For eg:

Memoization Fibonacci function:


Function memoi(fn)

{

Const cache={};

return  function(...args){

Const key=JSON.stringify(args);

if(cache[key]){

return  cache[key];

}

Const result = fn(...args);

Cache[key] = result;

return  result;

 

};

}

 

Const fibonacci=memoize(function(n))

{

if(n<=1) return n;

Return fibonacci(n-1)+fibonacci(n-2);

});

console.log(fibonacci(10));

Q36. What is recursion in a programming language?

When a function calls itself again and again in a program is called recursion.

Recursion is used to solve complex problems by breaking them into smaller problem and solving them individually.

Key concepts are:

Base case:

This means a condition where you have to stop in a recursion.

Recursive case:

This part reduces the problem into subproblems and then you can solve them efficiently.

For eg:

factorial problem using javascript:


Function facto(n){

if(n<=1){

Return 1;

}

Return n*fact(n-1);

}

console.log(facto(5));

Q37. What is the use of a constructor function in JavaScript?

A constructor function is a different type of function used to create and work with objects.

constructor function helps implement object-oriented programming concepts in JavaScript.

Key Features are creating instances, initialization, inheritance and prototype naming conventions.

For eg:


function edureka(name, age) {

this.name = name;

this.age = age;

}

&nbsp;

edureka.prototype.greet = function() {

console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);

};

var AP = new edureka("AP", 40);

var john = new edureka("john", 5);

&nbsp;

AP.greet();

john.greet();

Q38. What is DOM?

The document object model (DOM) is a programming interface for web documents.

It represents the structure of a document as a tree of objects, such as elements, attributes, and text.

DOM allows programming languages,like Javascript,to interact with the content,structure,and style of a document, such as HTML or XML.

Features are tree structure, objects and properties, dynamic interaction, events, cross-platform and language-independent.

For eg:

<!DOCTYPE html>

<html>

<head>

<title>DOM Example</title>

</head>

<body>

<h1 id=”heading”>hi edureka!</h1>

<button onclick=”changeText()”>C text</button>

<script>

function changeText() {

// Access the h1 element by its id

var heading = document.getElementById(“heading”);

// Change the text content of the h1 element

heading.textContent = “Text has been changed!”;

}

</script>

</body>

</html>

 

DOM provides the methods ‘getElementById()’ and ‘textContent’ to manipulate the document dynamically.

Q39. Which method is used to retrieve a character from a certain index?

There are several methods to retrieve a character from a certain index in a string.

Most Commonly used are:

1. charAt()::

You must have used this in Java programming, which also works the same.


const str = "Hello, edureka!";

const char = str.charAt(4);

console.log(char);

2. Bracket Notation::

For eg:


const str = "Hello, edureka!";

const char = str[4];

console.log(char);

Q40. What do you mean by BOM?

The browser object model(BOD) allows developers to interact with the browser itself, outside of the content of the webpage.

Key Components of the BOM

  1. Window object
  2. Navigator object
  3. Location object
  4. History object
  5. Screen object

Uses of BOM

  • Manipulating the browser window
  • Interacting with the browser
  • Accessing browser-specific features

The BOM is not standardized,which means its implementation can vary between different browsers.

Q41. What is the distinction between client-side and server-side JavaScript?

                    client -side               server-side
Executed in the users web browserExecuted on the web server
HTML,CSS,JAVASCRIPTPHP,PYTHON,RUBY,JAVA
Enhances user experience and dynamic elementsManage data storage and retrieval
User can modify the code ,can view itCode is hidden from user and runs on server
Limited by security constraints of the browserCan securely manage sensitive data and perform protected operations.

We hope these basic JavaScript Interview Questions for Freshers will help you get the basic understanding and prepare for the 1st phase of the interview.

Want to upskill yourself to get ahead in your career? Check out this video

Intermediate Level JS Interview Questions and Answers

Q42. 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.

Q43. 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:
(i) getElementById(‘idname’): Gets an element by its ID name
(ii) getElementsByClass(‘classname’): Gets all the elements that have the given classname.
(iii) getElementsByTagName(‘tagname’): Gets all the elements that have the given tag name.
(iv) querySelector(): This function takes css style selector and returns the first selected element.

Q44. 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:

  • Inline
  • Internal
  • 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.

Q45. Explain Higher Order Functions in javascript.

Higher-order functions in JavaScript are functions that can take other functions as inputs or return functions as their outputs. They make it possible to use strong functional programming methods that make code more flexible, reused, and expressive. By treating functions as first-class citizens, they make it possible to abstract behaviour and make flexible code structures.

Q46. 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.

Q47. 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.

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

Storage - Edureka

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.

Q49. 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.

Q50. What is currying in JavaScript?

Currying is a JavaScript functional programming approach that converts a function with many parameters into a succession of functions that each take one argument. It allows you to use only a portion of the inputs, allowing you to create functions that may be used several times and are specialized.

Q51. What is the difference between null & undefined?

Here is a declared ambiguous variable with no value assigned to it. Null, on the other hand, is an assigned value. As an alternative to that variable, one can use an empty variable. Also, there are actually two different types: undefined is an object, while null is a type in and of itself.

Q52. 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.

Q53. Name some of the JavaScript Frameworks

JavaScript Frameworks - JavaScript interview questionsA 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:

Q54. What is the difference between window & document in JavaScript?

WindowDocument
JavaScript window is a global object which holds variables, functions, history, location.The document also comes under the window and can be considered as the property of the window.

Q55. 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

Q56. 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.

Q57. 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.

Q58. 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 these two very different names can call you.

Q59. 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.

For example-


parseInt("4F", 16)

Q60. 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.

Q61. 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-

//------ lib.js ------</span>
export const sqrt = Math.sqrt;</span>
export function square(x) {</span>
return x * x;</span>
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}

//------ main.js ------</span>
 { square, diag } from 'lib';
console.log(square(5)); // 25
console.log(diag(4, 3)); // 5

Now with this, we have reached the final section of JS Interview Questions.

Advanced JavaScript Interview Questions for Experienced Professionals

Q62. What are arrow functions?

Arrow function or we can say “fat arrow function ” is a special type of way to write a function in javascript.

They were first introduced in ECMAScript 6(ES6).It also provide a shorter syntax compared to that of traditional ones.

Syntax

Const edureka = (parameter1,parameter2,….) => {

//function body

};

For eg::

Const mul =(a,b) => a*b;

console.log(mul(23,34));

Q63. What do mean by prototype design pattern?

The prototype design pattern is a creational pattern used in software development.

With the help of prototype design patterns, objects can create clones of themselves. This is very easy and simple to use.

Key features are prototype interface, concrete prototype, client.

It works first when a prototype is created then concrete prototype is made doing some changes then final cloning is done.

For eg:


class Proedureka {

constructor(course) {

this.course = course;

}

&nbsp;

clone() {

return new Prototype(this.course);

}

&nbsp;

getName() {

return this.course;

}

}

&nbsp;

const prototype1 = new Prototype("Prototype 1");

const prototype2 = prototype1.clone();

&nbsp;

console.log(prototype1.getName());

console.log(prototype2.getName());

Q64. The benefits of using prototype design patterns are performance, flexibility, and reduced subclassing.

You can take its use cases as

1. Resource-intensive Object

2. Object state

3. Avoiding Constructor Overhead

Q65. What is the rest parameter and spread operator?

The rest parameter and spread operator are features  in ECMAScript 6 (ES6) that provide a more concise and flexible way to handle function arguments, arrays, and objects.

Syntax-

Function functionName(…args){

//your statements

}

 

For eg::

For rest parameter


function sum(...numbers) {

return numbers.reduce((total, num) => total + num, 0);

}

&nbsp;

console.log(sum(0,9,8));

console.log(sum(6,4));

Q66. What is the use of promises in javascript?

Promises are a powerful tool for managing asynchronous operations. They guide us to handle tasks that have more time complexity, such as fetching data from a server, reading a file, and executing a complex computation, without hindering the execution of the program.

Key concepts of promises in javascript are::

1. Asynchronous operations

2. Promise States

3. Chaining and composition

 

Basic Syntax


const myPr = new Promise((resolve, reject) => {

// Asynchronous operation

const success = true;

&nbsp;

if (success) {

resolve("successful!");

} else {

reject("failed!");

}

});

You can take use cases as

1. Fetching data

2. Sequential Asynchronous operations

3. Error handling

Advantages of promises in javascript are::

1. Avoiding callback hell

2. Error propagation

3. Composability

Q67. What are classes in javascript?

Classes provide a clear and structured way of creating an object.

For eg::


class edureka {

constructor(course, code) {

this.course = course;

this.code = code;

}

&nbsp;

myed() {

console.log(`Hello, my edureka course&nbsp; is ${this.course} and I my course code is&nbsp; ${this.code} .`);

}

}

&nbsp;

const person1 = new edureka("Machine Learning", 003);

person1.myed();

Q68. What are generator functions?

Special type of function allows you to define an iterative algorithm by writing a single function whose execution can be paused and resumed.

This feature provides a powerful way to work with asynchronous operations,sequences and also lazy evaluations.

It is denoted by ‘function*’

1. Key features are pausing and resuming execution

2. Iteration

3. Lazy evaluation

Syntax::


function* generatorFunction() {

yield value1;

yield value2;

...

}

For eg::


const myedgene = generatorFunction();

console.log( myedgene.next());

console.log( myedgene.next());

console.log( myedgene.next());

For eg::

generating sequence of numbers–


function* numGenerator() {

let ednum = 1;

while (true) {

yield ednum++;

}

}

&nbsp;

const numbers = numGenerator();

console.log(numbers.next().value);

console.log(numbers.next().value);

console.log(numbers.next().value);

Use Cases can be

1. Iterating over data

2. Asynchronous programming

3. Cooperative concurrency

4. Lazy evaluation

Q69. Explain WeakSet in JavaScript.

Weakset is a collection type that allows you to store weakly held objects.

“Set”:-it lets you store unique values

“Weak”:-weak nature

Key feature are

  1. Only store objects
  2. Weak references
  3. No iteration
  4. No size property

For eg::


let ws = new WeakSet();

let obj1 = { a: 1 };

let obj2 = { b: 2 };

&nbsp;

ws.add(obj1);

ws.add(obj2);

&nbsp;

console.log(ws.has(obj1));

console.log(ws.has(obj2));

&nbsp;

ws.delete(obj1);

console.log(ws.has(obj1));

Q70. Why do we use callbacks?

callbacks are functions that are passed as arguments to other functions and are initiated after a certain event or task has been done.

They are fundamental concepts in JavaScript.

Reasons to use callbacks:

1. handling asynchronous operations

Like APIcalls,Timers,Event Handling.

2. modularity and reusability

For eg::


function executeWithLogging(action, callback) {

console.log("Starting action...");

callback(action);

console.log("Action completed.");

}

&nbsp;

executeWithLogging("Task 1", task => console.log(`Executing ${task}`));

executeWithLogging("Task 2", task => console.log(`Running ${task}`));

3. custom control flow

For eg::


function performTask(task, onSuccess, onError) {

try {

if (task === "fail") throw new Error("Task failed");

onSuccess("Task completed successfully");

} catch (error) {

onError(error);

}

}

&nbsp;

performTask(

"task1",

successMessage => console.log(successMessage),

errorMessage => console.error(errorMessage)

);

4. event driven

Foreg::


document.getElementById("myButton").addEventListener("click", function() {

console.log("Button was clicked!");

});

5. Avoiding blocking code::

In environments like node.js used for server-side javascript.

 

Q71. Explain WeakMap in javascript.

Weakmap  is a collection type that stores key-value pairs, where the keys are objects and the values can be any arbitrary values

The keys in weakmap are held weakly meaning they do not prevent garbage collection if there are no other references to the object.

Key features are

1. only objects as keys

2. weak references

3. no enumeration or iteration

4. non-enumerable

5. methods like

set(key,value)

get(key)

has(key)

delete (key)

For eg::


let edurekaweakMap = new edurekaWeakMap();

let obj1 = {};

let obj2 = {};

&nbsp;

edurekaweakMap.set(obj1, "Object 1 value");

edurekaweakMap.set(obj2, "Object 2 value");

&nbsp;

console.log(edurekaweakMap.get(obj1));

console.log(edurekaweakMap.has(obj2));

&nbsp;

edurekaweakMap.delete(obj1);

console.log(edurekaweakMap.has(obj1));

Q72. What is Object Destructuring?

It is a syntax feature in javascript that allows the user to extract properties from object and assign them to variables in a more legible way.

Syntax


const edureka = { course: "ML", code: 090, job: "Engineer" };

const { course, code, job } = edureka;

&nbsp;

console.log(course);

console.log(code);

console.log(job);

Use Cases and benefits are::

1. concise code

2. avoid repeated access

3. function parameters

It is a powerful feature in javascript that simplifies the extraction and assignment of object properties,making the code more readable and maintainable.

Q73. Difference between prototypal and classical inheritance

                prototype             Classical inheritance
Property chain,Dynamic inheritance,object.createClasses and instances,inheritance,constructor function
flexible,simplicityFamiliar syntax,clear structure
Readability,inheritance depthLess flexibility,boilerplate code
Uses object.createUses class,extends,super

Q74. What is a Temporal Dead Zone?

Refers to the period between creation of a variable’s scope and the point where the variable is actually declared and initialized.


function example() {

console.log(ed);

let ed = 10;} example();

Key features of temporal dead zone are::

1. Scope and initialization

2. error handling

3. var VS let /const:var

The Temporal Dead Zone is an important concept for understanding the behavior of “let”  and  “const” declarations in JavaScript.

Q75. What do you mean by JavaScript Design Patterns?

Javascript design patterns are the best practices for common problems in software design and architecture.

These provide guidance for structuring code,improving code maintainability and making is more efficient and scalable.

Common designs are as follows::

  1. Module pattern
  2. Singleton pattern
  3. Factory pattern
  4. Observer pattern
  5. Decorator pattern
  6. Prototype pattern
  7. Command pattern

The benefits of using design patterns are as follows:

  1. Reusability
  2. Maintainability
  3. Scalability
  4. Best practice

Q76. Is JavaScript a pass-by-reference or pass-by-value language?

Javascript is a pass-by-value language

Pass by value::

So when the value is passed in a function in javascript as a pass by value then it sends a copy of it and the original value doesn’t get affected if the passed value is changed.

For eg::


function passbyvalue(x) {

x = 100;}

&nbsp;

let a = 200;

updateValue(a);

console.log(a);

Alternative is pass-by-reference

When you pass a value in a function then a copy of its reference goes and if any change occurs to the pass value then the original value also gets  changed.

For eg::


function passbyrefer(obj) {

obj.name = 'DATA SCIENCE';

}

&nbsp;

let course = { name: 'ML' };

updateObject(course);

console.log(course.name);

Q77. Difference between Async/Await and Generators usage to achieve the same functionality.

                         Async/Await                            Generators
Uses async function and await expressionUses function* and yield
Uses try/catch block for error handlingtry/catch inside the generator for error handling
More readable and conciseLess intuitive due to management of yield.
Automatically handles control flow;awaits promise resolutionRequire manual iteration with next() and throw() methods.

Q78. What is the role of deferred scripts in JavaScript?

It provides a way to control the loading and execution order of scripts in a webpage.

Play a crucial role in optimizing the performance of web pages.

Key Features::

  1. Non-blocking execution
  2. Execution order
  3. Improved performance
  4. Compatible

For eg::


<!DOCTYPE html>

<html>

<head>

<title>Deferred Scripts Example</title>

</head>

<body>

<h1>hi users welcome to edureka courses!</h1>

&nbsp;

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22script1.js%22%20defer%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22script2.js%22%20defer%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

&nbsp;

</body>

</html>

Q79. What has to be done in order to put Lexical Scoping into practice?

To effectively use lexical scoping in javascript follow these steps::

  • Learn how scope works and how variables are resolved based on their position..
  • Closures are to be used inorder to  retain access to variables from an outer scope.
  • Block scoping with  “let” and “const” to manage variables within specific blocks.
  • Get familiar with variable shadowing and avoid confusion by using distinct names when necessary.
  • Leverage closures for data privacy and encapsulation.

Q80. 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.

  • 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.
  • You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.

Q81. What is a prompt box in JavaScript?

A prompt box is a box that 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 typically used when you want the user to put a value before looking at a page. To move further, the user must click “OK” or “Cancel” in the prompt box that displays after entering an input value.

Java Full Course – 10 Hours | Java Full Course for Beginners | Java Tutorial for Beginners | Edureka

🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”)
This Edureka Java Full Course will help you understand the various fundamentals of Java programm…

Q82. 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 code executes at run time, and the statement inside the if condition is evaluated during run time.

Q83. What is the difference between Call & Apply?

The call() method calls a function with a given this value and arguments provided individually.

Syntax-


fun.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value, and arguments provided as an array.

Syntax-


fun.apply(thisArg, [argsArray])

Q84. How to empty an Array in JavaScript?

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

Method 1 –


arrayList = []

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.

Method 2 –


arrayList.length = 0;

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.

Method 3 –


arrayList.splice(0, arrayList.length);

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

Method 4 –


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

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

Q85. What will be the output of the following code?


var Output = (function(x)
{
Delete X;
return X;
}
)(0);
console.log(output);

The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don’t affect local variables.

Q86. What do you mean by Self Invoking Functions?

JavaScript functions that execute instantly upon definition without requiring an explicit function call are referred to as self-invoking functions, or immediately invoked function expressions (IIFE).

When you create a function that invokes itself, you may use parentheses or other operators to invoke it immediately after enclosing the function declaration or expression in parenthesis.
A self-invoking function looks like this:

“`javascript
(function() {
// Function body
})();
“`

In this example, the function is defined inside parentheses `(function() { … })`. The trailing parentheses `()` immediately invoke the function. Because it lacks a reference to be called again, the function is only ever run once before being deleted.
In order to keep variables, functions, or modules out of the global namespace, self-invoking functions are frequently used to establish a distinct scope. Code enclosed in a self-invoking function allows you to define variables without worrying about them clashing with other variables in the global scope.
Using a self-invoking procedure to establish a private variable is illustrated in the following example:

“`javascript
(function() {
var privateVariable = ‘This is private’;
// Other code within the function
})();
“`

This means that the variable {privateVariable} cannot be viewed or changed from outside of the self-invoking function and can only be accessed within its scope.
Another technique to run code instantly and give you a chance to assign the result to a variable or return values is by using self-invoking functions:

“`javascript
var result = (function() {
// Code logic
return someValue;
})();
“`

The outcome of the self-invoking function is designated to the `result} variable in this instance. This preserves a clear separation of scope and lets you carry out computations, initialize variables, or run code immediately.

Self-invoking functions offer a useful technique for creating isolated scopes and executing code immediately without cluttering the global scope. They are commonly used in modular patterns to avoid naming collisions or leaking variables.

Q87. What will be the output of the following code?


var X = { Foo : 1}; 
var Output = (function() 
{ 
delete X.foo; 
return X.foo; 
} 
)(); 
console.log(output);

The output would be undefined. An object’s property can be removed using the delete operator. In this case, object x holds the property foo. Since the function is self-invoking, we shall remove the foo property from object x. The outcome is still being determined when we attempt to reference a removed property after doing this.

Q88. What will be the output of the following code?


var Employee =
{
company: 'xyz'
}
var Emp1 = Object.create(employee);
delete Emp1.company Console.log(emp1.company);

The output would be xyz. Here, emp1 object has company as its prototype property. The delete operator doesn’t delete prototype property. emp1 object doesn’t have company as its own property. However, we can delete the company property directly from the Employee object using delete Employee.company.

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


//nfe (named function expression)
var Foo = Function Bar()
{
return 7;
};
typeof Bar();

The output would be Reference Error. A function definition can have only one reference variable as its function name.

Q90. 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.

Q91. 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"

Get the list of angular interview questions with answers , if you are looking for a job javascript with angular.

JavaScript Coding Interview Questions

Q92. Guess the outputs of the following codes:


<!DOCTYPE html>

<html>

<body>

&nbsp;

<h2>My first edureka experience</h2>

<p>The courses of edureka are the best in terms of experiences </p>

&nbsp;

<p id="demo"></p>

&nbsp;

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Adocument.getElementById(%22demo%22).innerHTML%20%3D%2089%2B90%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

&nbsp;

</body>

</html>

Q93. Guess the outputs of the following code:


<!DOCTYPE html>

<html>

<body>

&nbsp;

<h1>My time with edureka students</h1>

<p>so smart and intelligent students </p>

&nbsp;

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Adocument.write(99%2B12)%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

&nbsp;

</body>

</html>

Q94. Guess the output of the following code:


<!DOCTYPE html>

<html>

<body>

&nbsp;

<h1>how was your day while learning edureka courses</h1>

<p>it was the best day i can have with</p>

&nbsp;

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%0Awindow.alert(23%2B90)%3B%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

&nbsp;

</body>

</html>

Q95. Write a function that performs binary search on a sorted array.


function edBS(arr, x)

{

let low = 0;

let high = arr.length - 1;

let mid;

while (high >= low) {

mid = low + Math.floor((high - low) / 2);

&nbsp;

if (arr[mid] == x)

return mid;

&nbsp;

if (arr[mid] > x)

high = mid - 1;

&nbsp;

else

low = mid + 1;

}

return -1;

}

&nbsp;

arr = new Array(1,4,7,20,80,90);

x = 80;

n = arr.length;

result = edBS(arr, x);

if (result == -1)

console.log("There is no such element please try again")

else

{

console.log("you got the position very good lerners "

+ result);

}

Output

You got the position very good lerners 4

Q96. Implement a function that returns an updated array with r right rotations on an array of integers a.


function ed_rotate_print(arr,d,n)

{

var blank=new Array(n);

d=d%n;

let k = 0;

&nbsp;

for (let i = d; i < n; i++) {

blank[k] = arr[i];

k++;

}

&nbsp;

for (let i = 0; i < d; i++) {

temp[k] = arr[i];

k++;

}

for (let i = 0; i < n; i++) {

console.log(blank[i]+" ");

}

}

&nbsp;

let array = [ 0,9,8,7,6,5,4 ];

let n = array.length;

let d = 2;

ed_rotate_print((arr, d, n);

Q97. Write the code for dynamically inserting new components.


<!DOCTYPE html>

<html lang="en">

&nbsp;

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content=

"width=device-width, initial-scale=1.0">

&nbsp;

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%0Ahtml%2C%0A%0Abody%20%7B%0A%0Aheight%3A%20200%25%3B%0A%0Awidth%3A%20200%25%3B%0A%0A%7D%0A%0A%26nbsp%3B%0A%0A.button%20%7B%0A%0Adisplay%3A%20flex%3B%0A%0Aalign-items%3A%20center%3B%0A%0Ajustify-content%3A%20center%3B%0A%0A%7D%0A%0A%26nbsp%3B%0A%0A.tasks%20%7B%0A%0Adisplay%3A%20flex%3B%0A%0Ajustify-content%3A%20center%3B%0A%0Aalign-items%3A%20center%3B%0A%0Aflex-direction%3A%20column%3B%0A%0Amargin-top%3A%2020px%3B%0A%0A%7D%0A%0A%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />

</head>

&nbsp;

<body>

<div class="button">

<button id="addTask">Add task</button>

</div>

<div class="tasks"></div>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%0A%26nbsp%3B%0A%0Alet%20task%20%3D%20document.getElementsByClassName(%22tasks%22)%3B%0A%0Alet%20addTask%20%3D%20document.getElementById(%22addTask%22)%3B%0A%0AaddTask.addEventListener('click'%2C%20function%20()%20%7B%0A%0Afor%20(let%20i%20%3D%200%3B%20i%20%3C%20task.length%3B%20i%2B%2B)%20%7B%0A%0Alet%20newDiv%20%3D%20document.createElement(%22div%22)%3B%0A%0AnewDiv.setAttribute(%22class%22%2C%20%22list%22)%3B%0A%0AnewDiv.innerText%20%3D%20%22New%20Div%20created%22%3B%0A%0Atask%5Bi%5D.append(newDiv)%3B%0A%0A%7D%0A%0A%7D)%0A%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

</body>

&nbsp;

</html>

Q98. Write the code given If two strings are anagrams of one another, then return true.


function areAnagrams(s1, s2) {

return s1.split('').sort().join('')

=== s2.split('').sort().join('');

}

&nbsp;

let str1 = "listen";

let str2 = "silent";

&nbsp;

if (areAnagrams(str1, str2)) {

console.log("True");

} else {

console.log("False");

}

&nbsp;

str1 = "gram";

str2 = "arm";

&nbsp;

if (areAnagrams(str1, str2)) {

console.log("True");

} else {

console.log("False");

}

With this, we have come to the end of the JavaScript interview questions and answers blog. You can also check Java Collection Interview Questions for more. I Hope these questions will help you in your interviews. In case you have attended interviews in the recent past, do paste those interview questions in the comments section and we’ll answer them. You can also comment below if you have any questions in your mind, which you might face in your JavaScript interview.

FAQs

What are the primitive data types in JavaScript?

Primary data types are basic types of data that does not have objects and methods::

1.string:for char values.

let edureka=”hi welcome to this course”;

2.Number:for integer value in javascript

For eg::


let number1=90

let number2=3.14

3.BigInt::for integer with arbitrary precision

For eg::


let bigInt=12345678900987654321234566789900

4.Boolean::for the logical entity either true or false;

For eg::


let istrue=true

let isfalse=false;

5.Undefined:: a variable declared but not assigned.

For eg::


let x;

console.log(x);

6.NULL::intentional absence of any object value.

For eg::


let y=null;

7.symbol

Represents unique and immutable identifiers.

let sym=symbol(&ldquo;example&rdquo;);

How do you explain ‘hoisting’ in JavaScript?

During the compilation time before the code is executed where variable are moved to the top of their containing scope(either global or function scope)

The hosting works like variable declaration then function declaration then ‘let’ and ‘const’ declarations

1.variable hosting


console.log(edureka);

var edureka = 1000000;

console.log(edureka);

2.function hosting


sayedureka();

function sayedureka() {

console.log("hi welcome to this course");

}

3.hosting with ‘let’ and ‘const’


console.log(edureka);

let edureka = 100000;

console.log(course);

const edurekacourse = 200000;

What’s the difference between ‘===’ and ‘==’?

In javascript::

“=== “ is strict equality

console.log(45 === 45);

console.log(95 === ’95’);

console.log(null === null);

console.log(undefined === null);

“==” is loose equality

For eg::


console.log(&lsquo;edureka&rsquo; == &lsquo;edureka&rsquo;);

console.log(100 == 'edureka');

console.log(null == undefined);

console.log(&lsquo; ' == false);

How can you loop through the elements of an array?

We can loop in different ways in javascript

1.for loop::


let edarr=[5,7,9,0,4,5];

for(let i=0;i<array.length;i++){

console.log(array[i]);

}

2.for…of loop


let edarr=[2,3,5,7,8,9];

for(let element of array){

console.log(element);

}

3.forEach method


let edarr = [1,3,5,7,9];

array.forEach(function(element,index){

console.log(element);

});

4.for…in loop


let edarr=[0,8,6,4,2];

for(let index in array){

console.log(array[index]);}

Got a question for us? Please mention it in the comments section and we will get back to you.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 22nd February,2025

22nd February

SAT&SUN (Weekend Batch)
View Details
Comments
4 Comments
  • Very good article you publish helpful these question and answer are also important for java script learning students.

  • Most of the questions are outdated and no longer asked in Interview.

    Kindly hire a PROFESSIONAL and make articles.

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Top 90+ JavaScript Interview Questions and Answers for 2025

edureka.co