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

Programming & Frameworks

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

Top 60+ JavaScript Interview Questions and Answers for 2024

Last updated on Feb 29,2024 839.4K 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 want to learn the skills that are required. You can gain in-depth information and prepare for your interviews with our JavaScript Interview Questions, JavaScript training, and Java Certification.

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
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 JS Interview 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.

Got a question for us? Please mention it in the comments section of “JavaScript Interview Questions and Answers” blog and we will get back to you or you can also join our Java Training in Bangalore.

edureka

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
5 Comments
  • Md Owais Nazi says:

    Questions and answers are good but if there will be an example with code that it will be like awesome.

  • Very good article you publish helpful these question and answer are also important for java script learning students.

  • Arushi Vohra says:

    This post was really useful in terms of the information provided and the various level-wise questions. We have compiled the most important javascript interview topics list for anyone preparing for the Javascript interview.

  • Touseef Baba says:

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

    Kindly hire a PROFESSIONAL and make articles.

  • Mihailo Stefanovic says:

    Q41
    First wi will see an Exception: SyntaxError: unexpected token: identifier
    Because we must use tupeof not Typeof. When we fix that error we’ll see:

    Exception: SyntaxError: expected expression, got ‘<' Because there is stray tag. When we fix that there goes:Exception: ReferenceError: y is not defined Because you declare var Y but use y. After we fix that bug we’ll see: 1undefinedYour questions are either careless or diabolically hard.Q45 Exception: SyntaxError: unexpected token: identifier Delete != delete Exception: SyntaxError: unexpected token: identifier X != x Exception: ReferenceError: output is not defined Output != output And after all these fixes we got 0 in console.Why do you care so little about code?Q46 Output != output X.Foo != X.fooQ47 Exception: SyntaxError: unexpected token: identifier Because there is missing ; Should be: delete Emp1.company; Exception: ReferenceError: employee is not defined Employee != employeeEmp1 != emp1Exception: ReferenceError: Console is not definedAnd after all these fixes we get xyzQ48 Exception: SyntaxError: unexpected token: identifier is it Function or function? Who knows… Fix that and no error. No output also. Needs console.log(typeof Bar()); And then output number… Why? Because this works. Function can have one name, but many aliases…Dude, it’s 2019! Why are you teaching people like this???

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 60+ JavaScript Interview Questions and Answers for 2024

edureka.co