JavaScript

JavaScript Interview Questions & Answers

1) What is JavaScript?

Ans: JavaScript is a popular scripting language. It is object-based, lightweight, cross-platform translated language and is used for both client-side and server-side development.

2) Who developed JavaScript, and what was the first name of JavaScript?

Ans: JavaScript was developed by Brendan Eich, who was a Netscape programmer. JavaScript was initially called Mocha. After that, it was called Live Script and later known as JavaScript.

3) List some of the advantages of JavaScript?

Ans: Some of the advantages of JavaScript are:

  • Server interaction is less
  • Feedback to the visitors is immediate
  • Interactivity is high
  • Interfaces are richer

4) List some of the disadvantages of JavaScript?

Ans: Some of the disadvantages of JavaScript are:

  • No support for multithreading
  • No support for multiprocessing
  • Reading and writing of files is not allowed
  • No support for networking applications.

5) List some features of JavaScript?

Ans: Some of the features of JavaScript are:

  • Lightweight
  • Interpreted programming language
  • Good for the applications which are network-centric
  • Open source & Cross-platform

6) Name the types of functions?

Ans: The types of function are:

Named - These type of functions contains name at the time of definition. 

For Example:

function display()  

{  

  document.writeln("Named Function");  

}  

display(); 

Anonymous - These type of functions doesn't contain any name. They are declared dynamically at runtime.

For Example:

var display=function()  

{   

  document.writeln("Anonymous Function");   

}  

display();  

7) Can an anonymous function be assigned to a variable?

Ans: Yes, you can assign an anonymous function to a variable.

8) How to create objects in JavaScript?

Ans: There are 3 ways to create an object in JavaScript.

  • By object literal
  • By creating an instance of Object
  • By Object Constructor

For Example: create an object using object literal,

const student = {  
 
name: 'John', 
 
age: 17 
 
} 
 

9) How to create an array in JavaScript?

Ans: There are 3 ways to create an array in JavaScript.

  • By array literal
  • By creating an instance of Array
  • By using an Array constructor

For Example: create an array using array literal.
 
var a = []; 
 
        var b = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’];

10) What are the different data types present in JavaScript?

Ans: There are two types of data types in JavaScript:

  • Primitive data types
  • Non- Primitive data types

Primitive data types : The primitive data types can store only a single value, these are:

  • Number: The number data type is used to represent numeric values.
  • Boolean: The Boolean data type is used to represent a Boolean value, either false or true.
  • String: The string data type represents a sequence of characters. It is written within quotes and can be represented using a single or a double quote.
  • Null: The Null data type is used to represent a non-existent, null, or a invalid value i.e. no value at all.
  • Undefined: The Undefined data type is used when a variable is declared but not assigned. The value of this data type is undefined, and its type is also undefined.
  • Symbol: Symbol is a new data type introduced in the ES6 version of JavaScript. It is used to store an anonymous and unique value.
  • BigInt: The BigInt data type is used to store numbers beyond the Number data type limitation. This data type can store large integers and is represented by adding "n" to an integer literal.

Non-Primitive data types: To store multiple and complex values, we have to use non-primitive data types, these are:

  • Object: The Object is a non-primitive data type. It is used to store collections of data. An object contains properties, defined as a key-value pair.
  • Array: The Array data type is used to represent a group of similar values. Every value in an array has a numeric position, called its index, and it may contain data of any data type-numbers, strings, Booleans, functions, objects, and even other arrays.

11) In JavaScript what is an argument object?

Ans: The variables of JavaScript represent the arguments that are passed to a function.

12) What are the conventions of naming a variable in JavaScript?

Ans: Following are the naming conventions for a variable in JavaScript:

  • Variable names cannot be similar to that of reserved keywords. For example, var, let, const, etc.
  • Variable names cannot begin with a numeric value. They must only begin with a letter or an underscore character.
  • Variable names are case-sensitive.

13) What is the difference between JavaScript and JScript?

Ans: Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark issue. In other words, you can say JScript is the same as JavaScript.

14) What’s the difference between JavaScript and Java?

Ans: JavaScript :

  • JavaScript is an object-oriented scripting language.
  • JavaScript applications are meant to run inside a web browser.
  • JavaScript does not need compilation before running the application code.
  • JavaScript doesn't support multithreading.
  • JavaScript uses an event-based approach to concurrency.
  • JavaScript code is used in HTML web pages and requires less memory.
Java :

  • Java is an object-oriented programming language.
  • Java applications are generally made for use in operating systems and virtual machines. 
  • Java source code needs a compiler before it can be ready to run in realtime.
  • Java supports multithreading.
  • Java uses a thread-based approach to concurrency.
  • Java programs consume more memory.

15) Are Java and JavaScript same?

Ans: No, Java and JavaScript are the two different languages. Java is a robust, secured and object-oriented programming language whereas JavaScript is a client-side scripting language with some limitations.

16) What are some of the built-in methods in JavaScript?

Ans: The built-in methods of JavaScript are:

  • Date() : Returns the present date and time.
  • concat() : Joins two strings and returns the new string.
  • push() : Adds an item to an array.
  • pop() : Removes and also returns the last element of an array.
  • round() : Rounds of the value to the nearest integer and then returns it.
  • length() : Returns the length of a string.

17) Is JavaScript case sensitive language?

Ans: Yes, JavaScript is a case sensitive language.

18) Is JavaScript a statically typed or a dynamically typed language?

Ans: JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.

19) If we want to return the character from a specific index which method is used?

Ans: The JavaScript string charAt() method is used to find out a char value present at the specified index.
For Example:
var str="Javatpoint" 
  
document.writeln(str.charAt(4)); 

20) What is BOM?

Ans: BOM stands for Browser Object Model. It provides interaction with the browser. The default object of a browser is a window.  The window object provides various properties like document, history, screen, navigator, location, innerHeight, innerWidth.

21) What is DOM? What is the use of document object?

Ans: DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.

22) What is the use of window object?

Ans: The window object is created automatically by the browser that represents a window of a browser. It is not an object of JavaScript. It is a browser object.

The window object is used to display the popup dialog box, these are:

  • alert() : displays the alert box containing the message with ok button.
  • confirm() : displays the confirm dialog box containing the message with ok and cancel button.
  • prompt() : displays a dialog box to get input from the user.
  • open() : opens the new window.
  • close() : closes the current window.

23) How to write a comment in JavaScript?

Ans: There are two types of comments in JavaScript.

  • Single Line Comment: It is represented by // (double forward slash)
  • Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */.

24) What is the use of history object?

Ans: The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.

  • history.back() - It loads the previous page.
  • history.forward() - It loads the next page.
  • history.go(number) - The number may be positive for forward, negative for backward. It loads the given page number.

25) What is the difference between == and ===?

Ans: The == operator checks equality only whereas === checks equality, and data type, i.e., a value must be of the same type. 

For Example:

var x = 2;
var y = "2"; 
 
(x == y) // Returns true since the value of both x and y is the same.
(x === y) // Returns false since the typeof x is "number" and typeof y is "string".

26) How to write HTML code dynamically using JavaScript?

Ans: The innerHTML property is used to write the HTML code using JavaScript dynamically.

For Example: 

document.getElementById('mylocation').innerHTML =

"<h2>This is heading using JavaScript</h2>";

27) How to write normal text code using JavaScript dynamically?

Ans: The innerText property is used to write the simple text using JavaScript dynamically.

For Example:

document.getElementById('mylocation').innerText="This is text using JavaScript";

28) What is NaN property in JavaScript?

Ans: NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number and typeof of NaN will return a Number. To check if a value is NaN, we use the isNaN() function,

29) What does the isNaN() function?

Ans: The isNan() function returns true if the variable value is not a number.

30) Difference between Client side JavaScript and Server side JavaScript?

Ans: Client-side JavaScript is embedded directly by in the HTML pages which are relevant to running in a browser. The browser interprets this script at runtime.

Server-side JavaScript also resembles client-side JavaScript. It has a relevant JavaScript which is to run in a server. The server-side JavaScript are deployed only after compilation.

31) What do you understand about cookies?

Ans: A cookie is generally a small data that is sent from a website and stored on the user’s machine by a web browser that was used to access the website. Cookies are used to remember information for later use and also to record the browsing activity on a website.

32) How would you create a cookie?

Ans: The simplest way of creating a cookie using JavaScript is as below:

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

33) How would you read a cookie?

Ans: Reading a cookie using JavaScript is also very simple. We can use the document.cookie string that contains the cookies that we just created using that string.

The document.cookie string keeps a list of name-value pairs separated by semicolons, where ‘name’ is the name of the cookie, and ‘value’ is its value. We can also use the split() method to break the cookie value into keys and values.

34) How would you delete a cookie?

Ans: To delete a cookie, we can just set an expiration date and time. Specifying the correct path of the cookie that we want to delete is a good practice since some browsers won’t allow the deletion of cookies unless there is a clear path that tells which cookie to delete from the user’s machine.

For Example:

function delete_cookie(name) { 
 
  document.cookie = name + "=; Path=/; Expires=Thu, 01 Jan 1970     00:00:01 GMT;"; 
 
}

35) Define closure?

Ans: A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives a function access to its outer scope.

For Example:

var num = 10;  

function sum()   

{  

document.writeln(num+num);  

}   

sum(); 

36) What's the difference between event.preventDefault() and event.stopPropagation() methods in JavaScript?

Ans: In JavaScript, the event.preventDefault() method is used to prevent the default behavior of an element.

On the other hand, the event.stopPropagation() method is used to stop the propagation of an event or stop the event from occurring in the bubbling or capturing phase.

37) What is the difference between undefined value and null value?

Ans: Undefined value- A value that is not defined and has no keyword is known as undefined value.

Null value: A value that is explicitly specified by the keyword "null" is known as a null value.

38) What is the difference between Undefined and Undeclared in JavaScript?

Ans: Undefined means a variable has been declared but a value has not yet been assigned to that variable.

Undeclared means a variables that are not declared or that do not exist in a program or application.

39) What is this [[[]]]?

Ans: This is a three-dimensional array.

40) What is the difference between Session storage and Local storage?

Ans: Session storage- The data stored in session storage gets expired or deleted when a page session ends.

Local storage: Websites store some data in local machine to reduce loading time; this data does not get deleted at the end of a browsing session.

41) What is the difference between View state and Session state?

Ans: View state is specific to a page in a session whereas Session state is specific to a user or browser that can be accessed across all pages in the web application.

42) What are the pop-up boxes available in JavaScript?

Ans: The pop-up boxes are:

  • Alert Box
  • Confirm Box
  • Prompt Box

43) What is negative infinity?

Ans: Negative Infinity is a number in JavaScript which can be derived by dividing the negative number by zero. 

For example:

var num= -5;  

function display()  

{  

  document.writeln(num/0);  

}  

display();  

//expected output: -Infinity 

44) How can we detect OS of the client machine using JavaScript?

Ans: The navigator.appVersion string can be used to detect the operating system on the client machine.

45) Is JavaScript faster than ASP script?

Ans: Yes, because it doesn't require web server's support for execution.

46) What is this keyword in JavaScript?

Ans: The this keyword is a reference variable that refers to the current object.

47) How to handle exceptions in JavaScript?

Ans: By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript supports try, catch, finally and throw keywords for exception handling.

48) How to validate a form in JavaScript?  

Ans: For Example,

<script>  


function validateform(){  


var name=document.myform.name.value;  


var password=document.myform.password.value;  
  
if (name==null || name==""){  


  alert("Name can't be blank");  


  return false;  


}else if(password.length<6){  


  alert("Password must be at least 6 characters long.");  


  return false;  


  }  
}  

</script>  

<body>   
 
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >   
 
Name: <input type="text" name="name"><br/>   
 
Password: <input type="password" name="password"><br/>   
 
<input type="submit" value="register">   
 
</form>

</body> 

49) What is the requirement of debugging in JavaScript?

Ans: JavaScript didn't show any error message in a browser. However, these mistakes can affect the output. The best practice to find out the error is to debug the code. The code can be debugged easily by using web browsers like Google Chrome, Mozilla Firebox.

To perform debugging, we can use any of the following approaches:

  • Using console.log() method.
  • Using debugger keyword.

50) What is the use of debugger keyword in JavaScript?

Ans: JavaScript debugger keyword sets the breakpoint through the code itself. The debugger stops the execution of the program at the position it is applied. Now, we can start the flow of execution manually. If an exception occurs, the execution will stop again on that particular line.

51) What is the role of a strict mode in JavaScript?

The JavaScript strict mode is used to generates silent errors. It provides "use strict"; expression to enable the strict mode.

52) What is the use of Math object in JavaScript?

The JavaScript math object provides several constants and methods to perform a mathematical operation.

53) What is the use of a Date object in JavaScript?

The JavaScript date object can be used to get a year, month and day. You can display a timer on the webpage by the help of JavaScript date object.

54) What is the use of a Number object in JavaScript?

The JavaScript number object enables you to represent a numeric value. It may be integer or floating-point.

55) What is the use of a Boolean object in JavaScript?

The JavaScript Boolean is an object that represents value in two states: true or false.

56) What is the use of a Set object in JavaScript?

The JavaScript Set object is used to store the elements with unique values. The values can be of any type i.e. whether primitive values or object references.

57) What is the use of a WeakSet object in JavaScript?

The JavaScript WeakSet object is the type of collection that allows us to store weakly held objects. Unlike Set, the WeakSet are the collections of objects only. It doesn't contain the arbitrary values. The WeakSet has add(), delete() and has() methods.

58) What is the use of a Map object in JavaScript?

The JavaScript Map object is used to map keys to values. It stores each element as key-value pair. It operates the elements such as search, update and delete on the basis of specified key.

59) What is the use of a WeakMap object in JavaScript?

The JavaScript WeakMap object is a type of collection which is almost similar to Map. It stores each element as a key-value pair where keys are weakly referenced. Here, the keys are objects and the values are arbitrary values. The WeakMap has get(), set() and has() methods.

60) What are the falsy values in JavaScript, and how can we check if a value is falsy?

Those values which become false while converting to Boolean are called falsy values.

const falsyValues = ['', 0, null, undefined, NaN, false];   

61) What do you understand by hoisting in JavaScript?

Hoisting is the default behavior of JavaScript where all the variable and function declarations are moved on top. In simple words, we can say that Hoisting is a process in which, irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.

example :

hoistedVariable = 12;

console.log(hoistedVariable);

var hoistedVariable;

62) Explain passed by value and passed by reference.

In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference.

In pass-by value in JavaScript, a copy of the original variable is created, so any changes made to the copied variable do not affect the original variable. In pass-by reference in JavaScript, we pass the reference of the actual parameter. No copy is created in the memory.

63) Explain Scope and Scope Chain in javascript.

Scope in JS determines the accessibility of variables and functions at various parts of one’s code.

In general terms, the scope will let us know at a given part of code, what are variables and functions we can or cannot access.

There are three types of scopes in JS:

  • Global Scope
  • Local or Function Scope
  • Block Scope

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

call() : call() method call a function with the given 'this' value that takes arguments separately/individualy.
apply() : apply() method call a function with the given 'this' value that takes arguments as an array.
bind() : bind() method call a function with the given 'this' value which is provided as a parameter.

65) Implicit Type Coercion in javascript (in detail with examples)

When the value of one data type is automatically converted into another data type, it is called Implicit type coercion in javascript.

66) Self Invoking Functions

Self Invoking Functions is an automatically invoked function expression followed by (), where it does not need to be requested. Nevertheless, the declaration of the function is not able to be invoked by itself.  

67) What are callbacks?

A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.

Functions that are used as an argument to another function are called callback functions. 

68) What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.

Example of a curried function:

function add (a) { return function(b){ return a + b; } } add(3)(4

69) What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned. 

70) What is recursion in a programming language?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result. 

71) Advantages of using External JavaScript?

  • External Javascript allows web designers and developers to collaborate on HTML and javascript files.
  • It also enables you to reuse the code.
  • External javascript makes Code readability simple

72) Types of errors in JavaScript?

Javascript has two types of errors, Syntax error, and Logical error.

73) Use of a constructor function (with examples)

Constructor functions are used to create single objects or multiple objects with similar properties and methods.

Example:

function Person(name,age,gender)

{

  this.name = name;

  this.age = age;

  this.gender = gender;

}

var person1 = new Person("Vivek", 76, "male");

console.log(person1);

var person2 = new Person("Courtney", 34, "female");

console.log(person2);

74) Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
Higher-order functions are a result of functions being first-class citizens in javascript.

Examples of higher-order functions:

function higherOrder(fn) { fn(); } higherOrder(function() { console.log("Hello world") });

75) What are the different ways an HTML element can be accessed in a JavaScript code?

Here are the ways an HTML element can be accessed in a JavaScript code:

  • getElementByClass(‘classname’): Gets all the HTML elements that have the specified classname.
  • getElementById(‘idname’): Gets an HTML element by its ID name.
  • getElementbyTagName(‘tagname’): Gets all the HTML elements that have the specified tagname.
  • querySelector(): Takes CSS style selector and returns the first selected HTML element.

76) What is a Temporal Dead Zone?

Temporal Dead Zone is a behavior that occurs with variables declared using let and const keywords before they are initialized.

77) Difference between Async/Await and Generators 

  • Async/Await
  • Async-await functions are executed sequentially one after another in an easier way.
  • Async/Await function might throw an error when the value is returned.
  • Generators
  • Generator functions are executed with one output at a time by the generator’s yield by yield. 
  • The ‘value: X, done: Boolean’ is the output result of the Generator function.

78) What is the difference between Event Capturing and Event Bubbling?

Event Capturing

Event Bubbling

This process starts with capturing the event of the outermost element and then propagating it to the innermost element.

This process starts with capturing the event of the innermost element and then propagating it to the outermost element.

No comments:

Post a Comment

Your Gateway to Technical Interview Success! Welcome to  InterviewNexus , where preparation meets opportunity.  I'm here to simplify you...