Top 85+ JavaScript Interview Questions and Answers for 2023

Top 85+ JavaScript Interview Questions and Answers for 2023

29 mins read14.7K Views Comment
Updated on May 26, 2023 17:48 IST

JavaScript is a popular programming language that is used to provide dynamic interactivity to websites. Today, JavaScript is one of the most in-demand skills worldwide, creating huge job opportunities for freshers as well as experienced professionals. If you want to become a JavaScript professional and are preparing for a job interview, then this JavaScript interview questions guide will help you land your dream job. This JavaScript interview questions and answers blog is divided into the following sections:

2019_09_BrutalLifeCycleJavascript.jpg

For whom this JavaScript Interview Question Answer Guide is helpful?

This JS interview questions blog is thoroughly prepared by examining the frequently asked JavaScript interview questions in multiple organizations. Anybody who is looking for a job requiring JavaScript programming language expertise will find this guide helpful.

Some profiles for which this guide is helpful are JavaScript Developer (fresher & experienced both), Front End Developer, User Interface Developer, React Native Developer, Ruby on Rails Developer, and Web Developer. 

JavaScript Basic Interview Questions for Freshers

Below are the top interview questions on javascript for freshers.

Q1. What are the major advantages of JavaScript?

Ans. JavaScript is a programing language used for the web. It can alter the HTML content, attribute values, and CSS style. It can also Show/Hide HTML elements. Some of the other advantages of JavaScript are:

Advantages Description
Speed Excellent speed as it immediately runs within the client-side browser.
Interoperability Sound functionality with other programming languages. Easily embedded into any web page.
Third-Party Add-ons Known for its extended functionality. It supports third-party add-ons to build JavaScript applications.
Rich-Interface Used to include items like a drag, drop, and sliders to present a rich interface to users/visitors.
Web Presence JS has a popular web presence. StackOverflow and GitHub extensively use JavaScript.
Versatile Capable of both Front-end (NodeJS) and Back-end development (Angular JS, React JS)

Explore popular courses on Shiksha Online: 

Popular Python Courses Top Data Structures and Algorithms Courses
Top Java Courses Top Programming Courses

Q2. How can you differentiate JavaScript from Java?

Ans. The differences between JavaScript and Java are:

Difference Java JavaScript
Language Object-Oriented Programming Language Object-Oriented Scripting Language
Platform Runs in JVM Runs on a Web Browser
Compilation Programs are compiled and Interpreted Only integrated
Support Supported by maximum operating systems Supported by web browser with different OS
Scope Uses block-based scoping Uses function-based scoping

Q3. How to create an object in JavaScript?

Ans. Objects are the building blocks of modern JavaScript and are more of a reference data type.

Object Creating Ways Code
Object() var d = new object();
Object.create () Var a = Object.create(null);
Function Constructor var Obj = function(name) {

 

this.name = name

}

var c = new Obj(“Hi”);

Q4. What is the method to change the title of a page using JavaScript?

Ans. Generally, the page title varies based on the HTML document and the element structure. We can give id to an element and use code:

document.getElementById(‘page-title-id’).innerHTML=NewTitle;

Q5. Tell some of the widely used JavaScript testing frameworks.

Ans. This is one of the popular JavaScript interview questions for freshers.

Some of the widely used JS Frameworks are –

  • Mocha
  • Jest
  • Jasmine
  • Karma (Test Runner)
  • Nightwatch
  • Puppeteer (Node Library)

Q6. Define some of the most prevalent JavaScript operators.

Ans. In JavaScript, operators are the symbols that help in performing different operations on the given data.

  • Arithmetic operators (+, -, *, /, %, ++, –)
  • Comparison operators (==, ===, !=, <,>, >=,<=)
  • Assignment operators (=, +=, -=, *=)
  • Logical operators – for

var a=10, b=20;

(a !=b) && (a<b); // RETURNS TRUE

Q7. JavaScript Functions – What do you know about it?

Ans. Something that performs a task to produce meaningful outputs is called function. JavaScripts also work on the concepts of both in-built JavaScript functions as well as user-defined functions.

Some of the common JavaScript Functions rules are:

  • It should begin with the keyword function
  • User-defined functions must have a unique name

Q8. What are some of the JavaScript data types?

Ans. Generally, there are 7 data types in JavaScript:

  • Number let n =789;
  • String let str = “Hello”;
  • Boolean (‘True’ and ‘False’)
  • Null let gender = null;
  • Undefined (for unassigned values)
  • Objects and Symbols (for complex data structures)
  • Typeof operator (returns type of argument)

To know more, read our blog – Introduction to JavaScript Data Types With Examples 

Q9. Describe different types of errors present in JavaScript.

Ans. In JavaScript, there are three different types of errors in programming.

  • Parsing errors – Also called Syntax errors, these errors occur at interpretation time in JavaScript. It only affects the tread in which this error occurs, leaving other threads unaffected.
  • Run-time errors – Errors that appear at the time of execution and are also defined as exceptions.
  • Logical errors – These are some of the most difficult types of errors and occur whenever there are flaws in logic that drive the script. Catching these errors is a very difficult task.

Q10. Can you redirect a page to another page using JavaScript? How?

Ans. Yes, it is possible to redirect a page to another page or URL using JavaScript by using location, replace, and location.assign.

Q11. Define JavaScript and mention some of its features.

Ans. This is one of the top JavaScript interview questions for freshers in 2022

JavaScript Definition – Initially known as LiveScript, JavaScript is an almost two decades old dynamic programming language used for web pages allowing client-side interaction.

Some Exceptional JavaScript features are-

  • Highly useful while using forms
  • Platform independent
  • Unique built-in features for handling date and time
  • Includes rich interfaces like drag and drop

Check out the top Database and SQL Courses 

Q12. State the major difference between a programming language and a scripting language. Also tell, JavaScript is which form of language?

Ans. Programming languages are designed to take full usage of any language, and at the same time, scripting languages are designed to fast-pace the coding. JavaScript is a scripting language.

Some of the major differences between both the languages are-

Scripting Language Programming Language
Uses Interpreter Uses Compiler
Supports Script Consists of instructions for a computer
Combines existing components Develops from Scratch
Needs another program to run Runs independently

Explore more about Programming Courses, Skills and Careers, read our blog – what is Programming?

Q13. What is the difference between Primitives and Objects in JS?

Ans. In JavaScript, values are of two types – Primitives and Objects. Some common differences between both are:

Objects Primitives
Mutable at the time of coding Immutable
Have a unique identity No individual identity
Compared by reference Compared by Value

Q14. What do you understand about the prompt() method?

Ans. Whenever you want to display a dialog with an optional message that prompts the user to input some text, the prompt() method is used. All major browsers including Google Chrome, Internet Explorer, and Firefox., support this

Q15. In JavaScript, what is ‘This’ keyword?

Ans. In JavaScript, the keyword ‘this’ refers to the object it belongs to and gives different values depending upon its usage.

For Example:

  • In method – refers to own object
  • Alone – refers to the global object
  • Function – undefined (in strict mode)

Q16. What are the types of JavaScript Function Scope?

Ans. Basically, the scope circumscribes the variable’s visibility. Talking about JavaScript, functions are first-class objects holding properties like an object. The only difference is that these functions can be called, unlike other objects. JavaScript covers majorly two types of Function Scope:

  • Local Scope – Variables defined inside the functions are called local to the function.
  • Global Scope – The outside area of all functions is considered global.

Q17. What is the difference between JavaScript keywords – var and let.

Ans. In JavaScript, var and let are used for variable deceleration, but var is known as function scope whereas, let is known as block scoped.

Q18. What do you mean by Hoisting in JS?

Ans. The concept of hoisting stands for uplifting the variable and functions on the top of their scope before the code execution takes place. In the JavaScript mechanism, no matter wherever the functions are declared, they are taken on the topmost position, immaterial of their scope – global or local.

Q19. Name a few built-in methods.

Ans. JavaScript has several built-in methods which are classified as:

  • Number Methods – constructor(), toExponential(), toFixed()
  • Boolean Methods – toSource(), toString(), valueOf()
  • Date Methods – Date(), getFullYear(), getHours()
  • Math Methods – abs(), exp(), log()

Confused about whether to learn Python or Java? Read our blog  – Python Vs Java and find out which is better to learn.

Q20. How can you submit a form using JS?

Ans. To submit a simple form, the below code will work.

document.form[0].submit();

Q21. What do you mean by control flow and error handling in JS?

Ans. In JavaScript, control flow stands for a process that ensures that an appropriate order is followed to execute statements in a script. It also ensures that one must read not only the entire code but also check the program structure and how that structure affects execution.

Whereas, error handling in JS means catching an error using “try..catch” Initially, the code try functions in a way that if the code is error-free, the catch function will be ignored. But in case any error is found, try execution is paused, and control(err) begins.

Q22. What is DOM in JS?

Ans. DOM stands for Document Object Modeling, which is a language allowing dynamic accessing and modifying the content in any document. Level of abstractions DOM has in JavaScript:

  • DOM Level 1
  • DOM Level 2
  • DOM Level 3
  • Scalable Vector Graphics
  • Mathematical Mark-up Language

Q23. What is BOM in JS?

Ans. BOM stands for Browser Object Model. It is an extensive representation of elements provided by the browser like document, location, history, and frames exposed to JavaScript. It includes the properties and methods for JavaScript to interact with the web browser. The window is the top-level object in the BOM, representing the browser window. It contains all other browser objects, including the properties and methods that can be used to control the Web browser. The important BOM objects are document, history, screen, navigator, location, and frames.

You can call all the functions of the window by specifying the window or directly. To access the document, one can use a code document or window.document. 

2020_11_BOM.jpg

Q24. What is a JavaScript string?

Ans. Whenever we want to store or manipulate text, we use JavaScript strings. We need JavaScript String methods to work with strings.

Q25. In JavaScript, what does an Anonymous function do?

Ans. The function that has no defined name is called an anonymous function in JavaScript. One can easily use this function by replacing expression. This anonymous function can also be assigned to a variable. Further, this function can also be moved as an argument to a different function.

Q26. In JavaScript, how can you validate null or empty values?

Ans. This is one of the top Javascript interview questions and answers for freshers. 

It is essential to check the condition that any user has added any value in the given field. The below code will help:

// If the length is 0 then imitate helper message

function required(inputtx)

{

if (inputtx.value.length == 0)

{

alert(“message”);

return false;

}

return true;

}

Q27. List some of the Design Patterns in JS.

Ans. Whenever somebody wants to reuse solutions for regularly occurring problems in software designing, Design Patterns will solve the purpose.

The latest Design Patterns in JS are:

  • Module Design pattern
  • Revealing Module pattern
  • Prototype Design pattern
  • Revealing Prototype pattern
  • Observer Design pattern
  • Singleton

Q28. Define the usage of Set objects in JavaScript.

Ans. Set objects in JavaScript are the source to store elements having unique values, including both primitive as well as object reference values.

Q29. Explain Deep vs shallow object copying in JavaScript.

Ans.

  • Deep Coping – This means that all the values of the existing/original variables are copied to a new variable and, thus, disconnected from the existing variables.
  • Shallow Coping – When commanded for shallow coping, not all the existing variables are disconnected, and some values or sub-values are still connected to the original.

Also Read: Top Python Interview Questions and Answers

Let’s move on to some intermediate and advanced-level top JavaScript interview questions for 2023.

Intermediate-Level JavaScript Interview Questions 

Q30. How to formulate a cookie using JS?

Ans. A cookie is a set of data saved on the computer and accessed by the browser.

Step to create a JavaScript cookie :

document.cookie = “cookiename=John”; expires = date”;

Q31. Once a cookie is created, how to read a cookie using JS?

Ans. In the case of JavaScript, cookies can be read as:

Var x = document.cookie;

Q32. In HTML, how many ways are there to involve JS?

Ans. For this javascript interview question, your reply should be –

There are three ways to include JavaScript in HTML:

  • Sandwich the JavaScript code by defining a pair <script></script> tags of HTML
  • Create an external JavaScript file to define <script data-original=”Script.js”></script> in HTML
  • Directly code the JavaScript into an HTML element

Q33. Differentiate Cookies, LocalStorage, and sessionStorage.

Ans. Cookies – Cookies are those small sets of data, consisting of a name and value, stored by a web browser. JavaScript facilitates cookie creation, retrieval, and deletion via an intuitive interface.

LocalStorage – A unique type of web storage, which allows JS websites to store and obtain data in the browser without any specified expiry date.

SessionStorage – Saves data only for one session, and when the tab is closed, it’s deleted.

Features Cookies localStorage sessionStorage
Data Size 4 KB 5 MB 5 MB
Blockable Yes Yes Yes
Auto-expiration Yes No Yes
Data Transferred on HTTP request Yes No No

Q34. What is the major difference between == and === operators?

Ans. It is one of the favorite javaScript interview questions asked by an interviewer for the profile of web developers.

The major difference between == Operator and === Operator is that === considers type of variables whereas == makes corrections based on the values of variables. === is strictly an equality operator.

Also explore:

Q35. Define isNaN in JS.

Ans. isNaN is a function that determines whether a value is NaN (not-a-number) or not. It is used for defining a function true if in case the argument is not a number. returns true if the value equates to NaN. Otherwise, it returns false.

Syntax:

isNaN(value)

Q36. Which method is used to remove focus from the specified object in JS?

Ans. The Blur method removes focus from the specified object in JS. 

Q37. How to enable Strict mode in JS?

Ans. In JavaScript programming language, when strict mode is enabled, it adds compulsions. This function is used for solving some of the mistakes hindering the efficiency of the JavaScript engines. The code is:

functions myfunction()

{

“use strict”,

var v = “ Strict Mode Enabled”;

}

Q38. What is event bubbling in terms of JS?

Ans. Event bubbling, as well as event capturing, is one of the widely used terminologies in JS, and that is why interviewers compulsorily ask the meaning of this jargon.

In JS, the Event Flow process is evolved by three concepts:

  • Event capturing
  • Event Target
  • Event Bubbling

The event starting from the target element to its parent element and further-reaching its ancestors is called event bubbling. Generally, all the browsers have event bubbling as their default flow of the event.

Also Read: Top Java Interview Questions and Answers

Q39. How will you move an element in lowercase to uppercase from an array?

Ans. Use the method – toUpperCase to return the string value to uppercase.

Q40. If you need to calculate the Fibonacci series in JS, what will you do?

Ans. Fibonacci series is a pattern in which each given value is the sum of the previous two, and it starts with 0,1.

Method:

  • use function fib(n),
  • Declare var a=0 and b=1
  • Use this condition (var i=0; i<n; i++)
  • Use var temp = a+b;
  • Next make a=b
  • And b=temp;
  • }
  • Return a;

The series will come like 0,1,1,2,3,5…

Q41. Define the output for *2 in JS.

Ans. NaN will be the output as *2 is undefined.

Q42. What are screen objects and their properties?

Ans. Objects used to read the information available on the client’s screen are called screen objects. Some of the properties are:

  • AvailHeight
  • AvailWidth
  • ColorDepth

Q43. Explain pop() and shift() methods

Ans. The pop() method removes the last element from an array and returns it. The array on which it is called is then altered. The pop() method is similar to the shift() method. The only difference is that the Shift() method works at the array’s start. Shift() method removes an item from the beginning of an array and returns the removed item.

In both methods, the length of the array is changed. The return value of the pop and shift methods is the removed item. 

Pop() example: Remove the last element of an array:

var fruits = [“Apple”, “Orange”, “Banana”, “Strawberry”];

fruits.pop();

Output: 

Before pop: Apple, Orange, Banana, Strawberry

After pop: Apple, Orange, Banana

Shift() example: Remove the first element of an array:

var fruits = [“Apple”, “Orange”, “Banana”, “Strawberry”];

fruits.shift();

Output:

Before shift: Apple, Orange, Banana, Strawberry

After shift: Orange, Banana, Strawberry

Q44. What are the disadvantages of using innerHTML in JavaScript?

Ans. InnerHTML is a popular property as it offers a simple way to completely replace the contents of an HTML element. However, it has some disadvantages. The following are the disadvantages of using innerHTML in JavaScript:

  1. One of the disadvantages is that the content is replaced everywhere. Whether you append or modify content using innerHTML, all the content is replaced and all the DOM nodes inside that element have to be re-parsed and recreated.
  2. Even after using +=like “innerHTML = innerHTML + ‘html'”, the old content is replaced by HTML. This happens because string concatenation just does not scale when dynamic DOM elements need to be created as the plus’ and quote openings and closings become difficult to track.
  3. It preserves event handlers attached to any DOM elements. If you set innerHTML, it will not automatically reattach event handlers to the new elements that are created. You will have to add them manually. It can create a memory leak on some browsers.
  4. It does not support appending to innerHTML. Usually, += is used for appending in JavaScript. However, on appending to an Html tag using innerHTML, the whole tag is re-parsed and recreated. 
  5. The innerHTML process is slow as its contents are slowly built. The parsed contents and elements are also re-parsed.

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

var Employee =

{

company: ‘abc’

}

var Emp1 = Object.create(employee);

delete Emp1.company Console.log(emp1.company);

Ans. The output of the given code will be abc. 

In the given code, the prototype property of Emp1 object is company. The delete operator will not delete the prototype property. Emp1 object does not have a company as its own property. But the company property can be deleted directly from the Employee object using delete Employee.company.

Q46. What is the role of event.preventDefault() method?

Ans. The event.preventDefault() method notifies the user agent that default action s should not be performed if the event does not get explicitly handled.

Syntax: 

event.preventDefault();

Q47. How to check if the event.preventDefault() method was used in an element?

Ans. If we use the event.preventDefault() method, it will return a boolean indicating that event.preventDefault() was called in a particular element.

Q48. What are the different methods and properties in Windows Objects?

 Ans. All the global JavaScript objects are members of the window object. The following are the methods and properties in windows objects: 

Methods in windows objects:

Methods Description
Alert() Displays specified popup messages with an OK button.
Confirm() Displays a dialog box with a specified message, along with an OK and a Cancel button.
Close() Closes the current window.
moveTO() Moves the current window.
Prompt() Displays a dialog box that prompts the user for input.
Open() Opens the current window.
resizeTo() Resizes the current window.
setTimeout() Performs an action after a specified time, like calling a function, evaluating expressions, etc.

Properties in windows objects:

Property Descriptions
innerHeight Returns the height of the browser window.
innerWidth Returns the width of the browser window.
name Specifies the window name.

Also Read: Learn PHP: Courses To Jumpstart Your Programming Career

Advanced Level JavaScript Interview Questions and Answers

Q49. Highlight the major difference between Call & Apply.

Ans. call() method refers to a method that takes the owner object as an argument. To use a method on different objects, we use the call method.

Parameters that a call function considers:

  • objectInstance – holding the instance of the object
  • arguments: considers comma as a separate argument

apply method is something that helps in writing the method to be used on separate objects.

Parameter of a method function:

  • objectInstance – holds an instance of an object
  • arrayOfArguments – call method considers an array of arguments

So the major difference between the two functions is that unlike the call function, the ‘method’ uses an array of arguments.

Q50. In JavaScript, append a new element at the end of the array.

Ans. To append an element in a JavaScript array, we use push(), and to remove an array, pop() is used.

Syntax:

array.push(item1, item2, …, itemX)

Q51. Empty an Array in JS.

Ans. Several ways to empty an array:

  • arrayList = []
  • length = 0;
  • while(arrayList.length)

{

arrayList.pop();

}

Q52. What will the statement declare?

var myArray = [[[]]];

Ans. It will declare that its a three-dimensional array.

Q53. Define Escape character in JavaScript.

Ans. If you want to write some special character without overlapping the application, the escape character will do the task. The backslash character (the escape characters) is used for employing special characters (‘’, “”, ‘, &)

Example: document. write “I am a “healthy” girl”

Q54. Why do popular JS libraries wrap the entire content of the JS source file in a function book?

Ans. Generally, there are two popular reasons for wrapping JavaScript libraries in a function book:

  • Avoid polluting the global scope
  • Avoid overriding existing variables

This practice is majorly used in jQuery plugins and is exercised by the most popular JavaScript libraries.

Q55. Give the output of the below code.

var Student =

{

college: ‘abc’

}

var Stud1 = Object.create(Student);

delete Stud1.college Console.log(Stud1.college);

Ans. The output will be abc

Description:

  • college is the Prototype property of Stud1
  • The operator that is used in code ‘delete’ doesn’t delete the prototype property
  • Stud1 don’t have college as its own property
  • To delete college property directly from the object Student use delete Student.college

Check out the Top JavaScript Interview Questions and Answers

Q56. Give the output of the below code:

var Output = (function(a)

{

Delete A;

return A;

}

)(0);

console.log(output);

Ans. The output will be 0.

As ‘A’ is a local variable and not an object, and delete operators leave local variables unaffected.

Q57. How do we add/remove properties to objects dynamically in JS?

Ans. We can add a property to an object by using:

object.property_name =value

To delete a property, we can use:

object.property_name

Example:

   let user = new Object();

    // adding a property

    user.name=’John’;

    user.age  =22;

    console.log(user);

    delete user.age;

    console.log(user);

Q58. How to get inner Html of an element in JS?

Ans. To get inner Html of an element in JavaScript, we can use InnerHTML property of HTML DOM.

Example:

This is inner Element

<script type=”text/javascript”>

var  inner= document.getElementById(“inner”).innerHTML ;

console.log(inner); // Inner Element

document.getElementById(“inner”).innerHTML = “Html changed!”;

var  inner= document.getElementById(“inner”).innerHTML ;

console.log(inner); // Html changed!

</script>

Q59. What is the procedure to remove duplicate values from a JSarray?

Ans. First, we can check whether a duplicate value exists or not by using array.indexOf method. Let’s see the given example to remove duplicate values.

let duplicates = [‘Spain’,’Russia’,’Russia’,’China’,’America’,’New Jersy’];

function removeDuplicatesValues(arr){

    let unique_array = [];

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

        if(unique_array.indexOf(arr[i]) == -1){

            unique_array.push(arr[i])

        }

    }

    return unique_array

}

console.log(removeDuplicatesValues(duplicates));

Q60. What will be the output of the code?

var Employee = {

company: ‘CompanyNW’

}

var emp0 = Object.create(Employee);

delete emp0.company

document.write(emp0.company);

Ans. The output of the given code would be CompanyNW. Where emp0 object has company as its prototype property. The delete operator will not delete prototype property.

Q61. How do we create blink text using JS?

Ans. Syntax:

<html>  

   <body>           

   <script>

     var str1 = “Upskill your Learning”;

     var response = str1.blink();

     document.write(response)

    </script>        

   </body>

</html>

Q62. How can we read elements of an array?

Ans. Syntax:

var num1 = [0, 1, 2, 3, 4];

for (var i = 0; i < num1.length; i++) {

   document.write(num1[i]);

}

Q63. What is the possible way to give a comment?

Ans. Syntax:

Single line comment – // Single-line comments.

Multiple line comments – /* Multi Line Comment

Q64. Mention HTML DOM mouse events.

Ans. Following are the HTML DOM mouse events:

  1. onclick
  2. ondblclick
  3. mouseout
  4. mouseover
  5. Mouseup
  6. mousemove
  7. mousedown

Check out the 10 Most-Popular Programming Languages

Q65. How do we get the primitive value of a string in?

Ans. In Javascript, we can use the valueOf() method to get the primitive value of a string.

Syntax:

var myVar= “Naukri”

console.log(myVar.valueOf())

Q66. How do we create an array?

Ans. Following are three different ways to create an array in Javascript:

  • By array literal
    usage:
    var myArray=[value1,value2…valueN];
  • By creating instance of Array
    usage:
    var myArray=new Array();
  • By using an Array constructor
    usage:
    var myArray=new Array(‘value1′,’value2′,…,’valueN’);

Q67. What is the possible way to give default arguments in function?

Ans. Syntax:

function print(arr = [], direction = ‘A1`) {

  document.write(‘Array Printing’, arr, direction)

}

print([1, 2, 3, 5])

print([1, 2, 3], ‘A2’)

Q68. What is the procedure to merge two arrays?

Ans. Syntax:

var arr1 = [1,2,3]

var arr2 = [4,5,6,7]

var mergedArrays = […arr1, …arr2]

document.write(‘Merged arrays’, mergedArrays)

Q69. Explain Loops in JavaScript.

Ans. In JavaScript, Loops are used to execute a block of code repeatedly. Loops offer a quick and easy way to repeat an action. They execute the same lines of code a specific number of times or as long as a specific condition is true. JavaScript supports the following types of loops:

1. for loop: loops through a block of code a number of times

Syntax:

for(statement1; statement2; statment3)

{

lines of code to be executed

}

2. for-in loop: It is used to loop the object through properties.

Syntax:

for (variablename in objectname)

{

lines of code to be executed

}

3. while loop: loops through a block of code while a specified condition is true.

Syntax:

while(condition)

{

lines of code to be executed

}

4. do/while loop: loops through a block of code while a specified condition is true. It is similar to the while loop. The only difference is that in the do/while loop, the block of code gets executed once even before checking the condition.

Syntax:

<pre>

do

{

block of code to be executed

} while (condition)

Q70. How do we target a particular frame from a hyperlink?

Ans. We can target a particular frame from a hyperlink by consisting the name of the required frame and can use ‘target’ attribute in it.

<a href=”/newpage.htm” target=”newframe”>>New Page</a>

Q71. Name the method we can use to read and write a file in JavaScript?

Ans. JavaScript extensions can be used to read and write a file such as for opening of a file –

fh = fopen(getScriptPath(), 0);

Q72. Explain what are Screen objects?

Ans. Screen objects hold information from the client’s screen. It is also used to display screen width, pixelDepth, height, etc. Let’s look at the properties of screen objects-

  • AvailWidth: Provides the width of the client’s screen
  • AvailHeight: Provides the height of the client’s screen
  • ColorDepth: Provides the bit depth of images on the client’s screen
  • Width: Provides the total width of the client’s screen, including the taskbar
  • Height: Provides the total height of the client’s screen, including the taskbar

Explore the Top Universities Offering Free Online Programming Courses 

Q73. What does the below-given statement specify?

Ans. var myArray = [[[]]];

It specifies a three-dimensional array.

Q74. What syntax we can use to hide JavaScript codes from old browsers that don’t support JavaScript?

Ans. We can use given codes for hiding JavaScript codes from old browsers:

Use “<!–” without the quotes in the code after the <script> tag.

Use “//–>” without the quotes in the code before the <script> tag.

These codes are not treated by old browsers whereas a browser that supports Javascript, it will take the “<!–” and “//–>” as one-line comments.

Q75. Write the output of undefined * 2 in Javascript?

Ans. The output of undefined * 2 is “nan”. 

Q76. How we can add or remove properties to objects?

Ans. We can add a property to an object with the help of object.property_name =value and delete object.property_name is used to delete a property.

Syntax:

   let user = new Object();

    // add a property

    user.name=’John’;

    user.age  =21;

    console.log(user);

    delete user.age;

    console.log(user);

Q77. Explain “use strict”.

Ans. In Javascript, “use strict” is used to enforce the code in strict mode where we can’t use any variable without declaring it. “use strict” was not considered by earlier versions of Javascript.

Q78. How do we convert Javascript date to ISO standard?

Ans. To convert Javascript date to ISO standard, we can use toISOString() method. It will convert a JavaScript Date object into a string, using the ISO standard.

Syntax:

var date = new Date();

var n = date.toISOString();

console.log(n);

Q78. Explain the difference between attribute and property?

Ans. Attributes provide details about elements such as ID, type, and value. Property is the value assigned to the property. It includes type=”text”, value=’Name’, and more.

Q80. Can we do 301 redirects in JavaScript?

Ans. We cannot do 301 redirects in JavaScript as it totally runs on the client machine. 301 is the response code that is sent by the server as a response. 

Q81. Explain what is a callback in JS.

Ans. A callback is used as a JavaScript function transferred to some method as an argument or option. It can make events like if any state is matched then can trigger to some other function.

Explore the top PHP Interview Questions and Answers

Q82. When we can use of JSON.stringify()?

Ans. We use this method to convert JavaScript JSON data to a string.

Q83. What is functional programming?

Ans. Functional programming is a programming paradigm that involves software development based on fundamental principles such as avoiding the shared state, composing pure functions, and avoiding mutable data and side effects. It is declarative instead of imperative. 

Q84. What is a pure function?

Ans. A pure function when given the same input will always return the same output without any side effects. These functions are essential for React+Redux apps, functional programming, and reliable concurrency. They are completely independent of the outside state and are immune to the entire class of bugs that have to do with the shared mutable state. They are easy to reorganize in the code which makes programs more flexible and adaptable to future changes.

Q85. What is Memoization in JS?

Ans. Memoization is a kind of caching system where the return value of a function gets cached depending on its parameters. If the parameter of that function is not changed, then it returns the cached version of the function.

Q86. What is the use of Constructor functions in JS?

Ans: Constructor functions are used to create objects in javascript. It is used when we want to create multiple objects having similar properties and methods.

Q87. What is negative infinity in JS?

Ans. In JS, negative infinity is a number that can be calculated by dividing a negative number by zero.

Q88. What are undeclared and undefined variables in JS?

Ans. In JS, undead variables are those variables those that do not exist in a program and are not declared. On the other hand, undefined variable are those variables that are declared in the program but have not been given any value.

Q89. What is a prompt box in JS?

Ans. In JS, a promt box is a simple box that allows the user to enter input by providing a text box.

Q90. Explain Implicit Type Coercion in javascript.

Implicit type coercion, also known as type conversion, is a feature of JavaScript that automatically converts one data type to another without the programmer’s explicit instructions. It occurs when an operator or a function expects operands of a certain type, but the provided operands are different.

Conclusion

We hope this list of JavaScript interview questions for freshers and JavaScript interview questions for experienced candidates will help you ace your next JavaScipt interview and land your dream job.

FAQs

Which method is used to remove focus from the specified object in JS?

The Blur method removes focus from the specified object in JS.

Can you redirect a page to another page using JavaScript? How?

Yes, it is possible to redirect a page to another page or URL using JavaScript by using location, replace, and location.assign.

What is the difference between JavaScript keywords var and let.

In JavaScript, var and let are used for variable deceleration, but var is known as function scope whereas, let is known as block scoped.

What do you mean by Hoisting in JS?

The concept of hoisting stands for uplifting the variable and functions on the top of their scope before the code execution takes place. In the JavaScript mechanism, no matter wherever the functions are declared, they are taken on the topmost position, immaterial of their scope - global or local.

What is a JavaScript string?

Whenever we want to store or manipulate text, we use JavaScript strings. We need JavaScript String methods to work with strings.

In JavaScript, what does an Anonymous function do?

The function that has no defined name is called an anonymous function in JavaScript. One can easily use this function by replacing expression. This anonymous function can also be assigned to a variable. Further, this function can also be moved as an argument to a different function.

Define the usage of Set objects in JavaScript.

Set objects in JavaScript are the source to store elements having unique values, including both primitive as well as the object reference values.

How will you move an element in lowercase to uppercase from an array?

Use the method u2013 toUpperCase to return the string value to uppercase.

Explain use strict.

In Javascript, Use strict is used to enforce the code in strict mode where we cannot use any variable without declaring it. Use strict was not considered by earlier versions of Javascript.

Can we do 301 redirects in JavaScript?

We cannot do 301 redirects in Javascript as it totally runs on the client machine. 301 is the response code that is sent by the server as a response.

Explain what is a callback in JS.

A callback is used as a JavaScript function transferred to some method as an argument or option. It can make events like if any state is matched then can trigger to some other function.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio