JavaScript Interview Questions and Answers

Questions

41

Last updated

Sep 5, 2024

JavaScript is a high-level programming language that is known for its dynamic, prototype-based and weakly typed characteristics. It conforms to the ECMAScript specification and is one of the core technologies of the World Wide Web. Initially only implemented client-side, JavaScript is now embedded in other types of software, including server-side in web servers and non-web programs such as PDF software and word processors. This information is often asked in JavaScript interview questions.

 

Most Frequently Asked JavaScript Interview Questions

Here in this article, we will be listing frequently asked JavaScript Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. What is JavaScript and why it is used?
Answer

JavaScript is a high-level programming language that is used to calculate, manipulate and validate data. With the help of JavaScript, we can update and change both HTML and CSS.

We can write JavaScript code in an HTML page. When a HTML page loaded with JavaScript code, the script is sent to the browser for manipulate then HTML or CSS code will be rendered. It is a client-side technology.

Q2. What are the data types available in JavaScript?
Answer

In JavaScript data types is an important concept that helps to operate on variables,JavaScript supports mainly two different kinds of data types-

  • Primitives
  • Objects
1. Primitives Data Type

It supports six data types that’s are given below.

  • Boolean: It represents only true or false based on condition.
  • Number: It can be written with or without decimals. Example var num1 = 32;
  • String: It is used to store texts and inside of either double or single quotes. Example var str_one = 'Best Interview Question';
  • Null: It is "nothing" but supposed to be something that does not exist.
  • Undefined: It has no value but variable is exists. Example var MyVariable_1;
    console.log(MyVariable_1); // undefined
  • Symbol: It is new in ES6. It is an immutable data type that have unique value.Example : const BestInterviewQuestion = Symbol(‘BestInterviewQuestion’);
2. Objects Data Type

It is a type of not primitive data Type. It is a collection of properties and these properties are stored in key and value pairs.

Q3. What are the difference between undefined and not defined in JavaScript?
Answer
  undefined Not defined
1. A variable was declared with a keyword "var" but not assigned with a value. A variable have not been declared without assignment:
2. Example :
var a = 1, b;
console.log(a) //1
console.log(b) //undefined
Example :
var a = 1, b;
console.log(f) // not defined
Q4. How to create an array in JavaScript?
Answer

In JavaScript, arrays is used to store multiple values within a single variable at a time.

Syntax for creating Arrays in JavaScript:

var arrayName = [value1, value2, value3];

Example:

var name = [‘best’,’interview’,’questions’];

We can access these values with:

var name1 = name[0]; console.log(name1); // it with display best.

Q5. What is console.log() and why it is used?
Answer

It is not a jQuery feature but a feature for debugging purposes used by developers. It is used to writes a message to the console.

console.log() accepts a parameter which can be an object, an array or any message.

Syntax : console.log(name); // here name is object, an array or variable.

$('#form').submit(function() {
     console.log(‘Your form is submitted successfully!’);
     // do something
});

Q6. How to create an object in Javascript?
Answer

There are various ways of creating an Object in JavaScript.

  • With the Object():
    Example : var name = new Object();
  • With Object.create():
    Example : var name = Object.create(null);
  • With the bracket syntactig sugar:
    Example : var name = {};
  • With a function constructor:
    Example :
    var ObjectName = function(Vname) {
        this. Vname = Vname
    }
    var NewVar = new ObjectName("BestInterviewQuestion.com");
  • With function constructor + prototype:
    Example :
    function myObj(){};
    myObj.prototype.name = "bestinterviewquestion.com";
    var Newk = new myObj();
  • With ES6 class:
    Example :
    class myObject {
        constructor(name) {
            this.name = name;
        }
    }
    var e = new myObject("bestinterviewquestion.com");
Q7. What is the difference between "var" and "let" Keywords?
Answer

Both are used for function declaration in JavaScript but the difference are given below :-

  let var
1. It can be only available inside the scope it's declared, like in for loop. It can be accessed outside the loop.
2. It is block scoped. It is function scoped
Q8. What is the difference between "==" and "==="?
Answer

The difference between "==" and "===" is as following

S.no "==" "==="
1. The operator "==" tests the abstract equality, which means before making equality comparison, it does the necessary type conversions. The operator "===" tests only strict equality, i.e., this will not perform type conversion; hence if values compared here are not the same type, it will return false.
Q9. Who introduced JavaScript?
Answer

Designed by Brendan Eich in May 1995 and developed under Netscape Communications, the

JavaScript was first released in September 1995 with the name Netscape Navigator 2.0 which was

later renamed to JavaScript. Interestingly, Eich wrote the full prototype of JavaScript in just 10 days.

Q10. Is JavaScript client side or server side?
Answer

JavaScript is a client-side language it gets executed at the user side. Whenever we browse the web, all the files from JavaScript are first fetched from the server and then performed at our side by the browser.

Q11. How do you write a comment in Javascript?
Answer

There are two types of comments we can write in JavaScript; single line comment and multiline comment. To create a single line comment, the users have to place two slashes “//” in front of text or code which they wish to have the JavaScript interpreter ignore. For multiline comments, use /* from the beginning of the comment and end it with */.

Q12. How we can get the value of an element using javascript?
Answer
Q13. What is NULL in Javascript?
Answer

In JavaScript, Null represents the absence of any object value. If a user tries to reference a null variable, he/she will get an error. It implies to no string, no number, no valid Boolean value, and no array object.

Q14. Explain the difference between call() and apply()?
Answer
S.no Call() Apply()
1. In JavaScript, call() is a predefined method used to invoke (call) methods with the use of an owner object as an argument (parameter). apply() is a method to write another way which can be used on different objects. It’s usually action similar to call() action.
Q15. What are the difference unescape() and escape() functions?
Answer
S.no unescape() escape()
1. The unescape() function uses a string as a parameter, and used to decode that string encoded by the escape() function. The escape() function in JavaScript is used to encode a string. It makes a string portable so that it can be transmitted across any network to any computer with ASCII character support.
Q16. What is the use of decodeURI() and encodeURI()?
Answer
S.no decodeURI() encodeURI()
1. The decodeURI() function works reverse to the encodeURI(), taking an encoded string and then replacing the tokens with the regular characters. encodeURI() is used to pass the string value that the user requires to convert. This function returns the URL encoded value.
Q17. What is 'use strict'?
Answer

The 'use strict' is a new ECMAScript version 5 directive. It’s a literal expression, not a statement, ignored by previous JavaScript versions. It is purposed to indicate that the code should be executed in the "strict mode."

Q18. What is NaN?
Answer

Not-a-Number or NaN is a weirdo Global Object present in JavaScript and frequently returned when failed mathematical operation happened. We can use global function isNaN() to find out if the variable is a NaN.

Q19. What is the difference between Arrow function and normal function?
Answer
S.no Arrow function Normal function
1. Introduced in ES6, it provides a concise way to write functions in the JavaScript. The context present inside arrow functions is statically or lexically defined. It’s a procedure to produce a set of statements that calculate a value or performs a task. We have to define a function in the scope from which we wish to call it, to use it.
Q20. What is a closure JavaScript?
Answer

It’s a JavaScript feature where an inner function has access to the enclosing or outer function’s variables, which is defined as a scope chain.

There are three types of scope chains:
  • Access to its own scope
  • Access to variables of outer functions
  • Access to global variables
Q21. How to count the items in an array using Javascript?
Answer

To count the number of elements in an array using JavaScript, use the following

var count = 0;

for(var i = 0; i

if(array[i] == 2)

count++;

}

Q22. What is singleton class in JavaScript? Explain
Answer

Singleton is a JavaScript object which can be instantiated one time, whereas the singleton pattern is a design pattern that restricts the reinstallation of a class to one object. It allows only a single instance of itself to be created and can give access to that created instance.

Point to be noted:- Don’t let this JavaScript Interview Question take your job opportunity. Read it twice and then go for the interview.

Q23. Explain export & import in JavaScript?
Answer
S.no Export Import
1. In JavaScript, the export statement is used when creating modules for JavaScript to export functions, primitive values or objects from the blades so they can be used by the programs with import statement which works opposite to it. The import statement is used when we import buildings which are exported by another module. All imported modules are in strict mode. This statement can’t be used in embedded scripts.
Q24. What is design pattern in JavaScript? Explain
Answer

It’s an advance object-oriented solution designed to solve commonly occurring software problems. These are reusable designs and interact with objects.

Q25. How to create a function in Javascript?
Answer

The javascript function is a block of code which can be designed according to the user to perform a particular task. A basic JavaScript function syntax is mentioned below:

function myFunction(p1, p2) {

return p1 * p2; // The function returns the product of p1 and p2

}

Q26. How can you do a character count in Javascript?
Answer

To perform a character count in JavaScript, use the following syntax:

var str = "Hello World!";

var n = str.length;

Q27. How to clone an object in Javascript?
Answer
There are three types of cloning available in JavaScript.
  • Deep copy using iteration
  • Converting to JSON and back
  • Using Object.assign
Q28. How to get value of an element by class in JavaScript ?
Answer
Q29. How we can add title of the page by JavaScript?
Answer

To change the title of a web page using JavaScript, we have to use the following syntax:

document.title = 'Your desired title';

Q30. What is the importance of JavaScript?
Answer

It is a client side technology, it is mainly used for gives client side validation, but it have lot of features which are given below;

  • It is an object-based scripting language.
  • It helps the user more control over the browser.
  • JavaScript Handling dates and time also.
  • It also helps to Detect the client's browser and Operating System.
  • JavaScript is light weighted & case sensitive.
  • All most JavaScript control statements syntax is same as syntax of control statements in C programming language.

 

These JavaScript Interview Questions can be beneficial in your interviews.

Q31. How to get the current URL with JavaScript?
Answer

var currentLocation = window.location;

Q32. What is the difference between push() and concat() in JavaScript?
Answer
Q33. What are the difference between JavaScript and jQuery?
Answer
On the basis of functioning

JavaScript is a scripting language which is compatible with all the major browsers and used to create interactive web-based applications. While jQuery is a framework which is the fastest JavaScript library used for the simplification of HTML document.

Time and simplicity

JavaScript is complex because it consumes the time of developers as it is important for the developers if they are using JavaScript then they have to create their own script. In the case of jQuery, developers need not write scripting as it already exists in the libraries.

Animation support

With JavaScript, it cannot be possible for the developer to use animation. On the other hand, jQuery allows the developers to use unbuild animations to make the applications interactive and attractive.

Featural aspects

JavaScript programming language is a combination of the European Manufacturing Association Script (ECMA) and Document Object Model (DOM). While on the other hand jQuery has a Document Object Model (DOM).

Interactivity feature

With the use of JavaScript, developers can make web pages more useful by suppling immediate feedback. While in case of jQuery developer can create web-based applications which becomes easier for the developer to customize the application as per the user's requirement.

Q34. What is the difference between let, var and const?
Answer

With JavaScript, the user can declare variables with three keywords, which are let, var, and const. The terms var let and const are somewhat confusing. We will explain all 3 variables with the help of examples.

The difference between the variables var, let as well as const is described below in different ways.

  • Scope
  • Hoisting
  • Reassign the value
  • Redeclaration of the variable

NOTE: If you want to read more about the difference between var, let as well as const then you can visit here.

Q35. What is the difference between arrow and normal functions?
Answer

The main differences between arrow function and normal function are based on some parameters like.

  • Syntax
  • Arguments that are binding.
  • "this" keyword is used to describe the use.
  • Utilizing a keyword that is new.
  • No duplicates of identified parameters.

Syntax of normal functions

// Function declaration
function printHello(name) {
   return `Hey ${name}`;
}

NOTE: If you want to read more about Regular vs Arrow functions then you can visit here.

// Function expression
const printHello = function(name) {
  return `Hey ${name}`;
}

Syntax of arrow functions

const printHello = (name) => `Hey ${name}`;

Q36. How to check if value exists in array JavaScript?
Answer

1. Using includes()

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.includes("Mango"));

2. Using indexof()

const fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits.indexOf("Orange") !== -1) {  
   alert("Yes, the value exists!")  
} else {
   alert("No, the value is absent.")  
}

Q37. What would be the output of the code below?

var variable1 = ["red", "green", "blue", "yellow"];
var variable2 = null;
console.log('This is a type of - ', typeof(variable1));
console.log('This is a type of - ', typeof(variable2));

Answer

This is a type of -  object
This is a type of -  object

Q38. How do you check the type of a variable?
Answer

typeof

Example

var x = 12345; 
console.log(typeof x)
x = 'string'; 
console.log(typeof x)
x = { key: 'value' };
console.log(typeof x)

Answer

number
string
object

Q39. What is the output of below code?

if (Math.round(null) > 0.5) {
  var x = 1;
} else {
  var x = 2;
}
console.log(x);

Answer

2

Q40. What is the output of code snippet?

const x = [];
x = 5;
console.log(x);

Answer

It will give an error like "TypeError: Assignment to constant variable".

Q41. What is the output of below code snippet?

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
const bigNumbers = numbers.map(number => {
  return number * 2;
});
console.log(bigNumbers);

Answer

[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]