Skip to content

surbhidighe/JavaScript-Top-Interview-Questions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

33 Commits
Β 
Β 

Repository files navigation

JavaScript interview questions


Click ⭐ if you like the project!!

Every contribution counts, regardless of its size. I value and appreciate the efforts of all contributors, from beginners to seasoned developers. Join me on this exciting journey of open-source collaboration. Together, let's build something amazing! 🀝


Contribution Guidelines

  • πŸ‘‰ Please ensure that your contributions adhere to the coding style and guidelines of this project
  • πŸ‘‰ Include clear and concise commit messages for all your commits
  • πŸ‘‰ Provide a detailed description of your changes in the pull request.
  • πŸ‘‰ Be respectful and considerate towards other contributors.

S.No Questions
1 What is JavaScript
2 What are the different data types in JavaScript
3 What are the different ways to create an Object in JavaScript
4 Difference between == and === operators
5 Is javascript single-threaded or multi-threaded
6 What are arrow functions and its features
7 What do you mean by Synthetic events
8 What is array destructuring
9 Can we combine two arrays using any es6 operators
10 Why javascript is dynamically typed language
11 Difference between Undeclared and Undefined
12 Difference between Null and Undefined
13 What is Temporal Dead Zone
14 What is IIFE
15 What is Hoisting
16 What are Cookies
17 What is memoization
18 Difference between var, let and const
19 What is a callback function
20 Is it possible to have both local and global variables with the same name
21 Difference between Local Storage and Session Storage
22 Difference between forEach() and map()
23 What is rest operator
24 What is spread operator
25 Difference between async and defer
26 What is Nullish coalescing operator
27 What is the difference between a parameter and an argument
28 What is a closure
29 Difference between function declaration and function expression
30 What are the different ways to create an array in javascript
31 Difference between window and document in javascript
32 What is strict mode in javaScript
33 What are the different ways to empty an array in javascript
34 What is NaN in javascript
35 Javascript naming convention
36 Difference between call(), apply() and bind()
37 What is the use of isNaN function
38 What is 'this' keyword in javascript
39 How do we add comments in javascript
40 What is the use of typeof operator
41 Is JavaScript case-sensitive
42 Difference between push() and unshift()
43 Difference between pop() and shift()
44 Different ways to access DOM elements in js
45 What are promises
46 What is a prototype
47 What is a callback hell
48 What is an event loop
49 ES6 and its features
50 Difference between function and method
51 What is aync and await
52 What is the role of event.preventDefault()
53 What is the use of JSON.stringify()
54 How can you stop the setTimeout
55 If Javascript is single threaded, how it supports asynchronous operations
56 What is javascript scope
57 Difference between global scope and local scope
58 What are the different ways to convert a string to an integer
59 How to find the operating system in the client machine using JavaScript
60 Name some JavaScript frameworks and libraries
61 What is event bubbling and event capturing
62 What is the role of event.stopPropagation()
63 How can we change the style of an element using javascript
64 What is object destructuring
65 Difference between an Alert Box and a Confirmation Box
66 How can we handle exceptions with javascript
67 What are the advantages of using External JavaScript
68 What is an anonymous function
69 What is a first order function
70 Different ways to access object properties in javascript
71 Difference between slice() and splice()
72 What are the escape characters in JavaScript
73 Different ways to redirect a page in javascript
74 What is the difference between innerHTML and innerText
75 How can you get current time using js
76 What is currying
77 Difference between shallow copy and deep copy
78 What is a service worker
79 What is JSON
80 How can you get all the keys of any object
81 What is a unary function
82 What is promise chaining
83 What is eval
84 How can you assign default values to variables
85 How to determine if an object is extensible or not
86 In how many ways we can make an object non-extensible
87 What is object.freeze method
88 What is object.seal method
89 How can you determine if JavaScript is disabled on a page
90 How can you compare two date objects
91 Does JavaScript support automatic type conversion
92 What is variable shadowing in javascript
93 What is ternary operator

1. What is JavaScript

  • JavaScript is a scripting language used to create dynamic and interactive websites. It is supported by all major web browsers.
  • JavaScript is basically a client-side scripting language but it can also be used on the server-side with the help of technologies such as Node.js.

πŸ” Scroll to Top

2. What are the different data types in JavaScript

Primitive Non-primitive
Boolean, NULL, undefined, BigInt, String, Number, Symbol Object, Array

πŸ” Scroll to Top

3. What are the different ways to create an Object in JavaScript

a) Object Literals: A comma-separated set of name and value pairs that is wrapped inside curly braces.
var person = {
    name: 'Surbhi',
    age: 25,
    occupation: 'Software Engineer'
}
b) Object.create method: It Creates a new object, by using an existing object as the prototype of the newly created object.
const person = {
    name: 'Surbhi',
    age: 25,
    occupation: 'Software Engineer'
}

var info = Object.create(person);
console.log(info.name); // output - Surbhi
c) Object constructor: Constructor function allows to create objects with the help of new keyword
const person = new Person();
d) using ES6: We can create object using ES6 class feature
class Person {
  constructor(name) {
    this.name = name;
  }
}
  
let person = new Person('Surbhi');
console.log(person.name);  //output - Surbhi

πŸ” Scroll to Top

4. Difference between β€œ==” and β€œ===” operators

  • == : While comparing two operands, checks for only value
console.log(1=="1");  // output=>>>>>>>>> true
  • === : While comparing two operands, checks for value as well as data type
console.log(1==="1");  // output=>>>>>>>>> false

πŸ” Scroll to Top

5. Is javascript single-threaded or multi-threaded

  • JavaScript is Single-threaded

πŸ” Scroll to Top

6. What are arrow functions and its features

Arrow functions were introduced in ES6 (ECMAScript 2015) and provide a simpler and compact way to write functions. They are also called β€œfat arrow functions”

Syntax
const functionName = (something) => {
  return something;
}
Features of arrow functions
  1. They use a concise syntax which makes them shorter and easier to read as compared to traditional function expressions
  2. They do not bind their own this value, but instead inherit the this value from the enclosing lexical scope
  3. They do not have "prototype" property and hence cannot be used as a constructor
  4. If the arrow function body consists of a single expression, that expression will be implicitly returned, without the need for a return statement.
  5. If an arrow function has only one parameter, the parentheses around the parameter list can be omitted.

πŸ” Scroll to Top

7. What do you mean by Synthetic events

Synthetic events are objects that act as a cross-browser wrapper around a browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

πŸ” Scroll to Top

8. What is array destructuring

Array destructuring is a unique feature in JavaScript that allows you to extract array's value into new variables. For e.g.,

const arr = [1,2,3];
const [num1, num2, num3] = arr;
console.log(num1); // output =====> 1
console.log(num2); // output =====> 2

πŸ” Scroll to Top

9. Can we combine two arrays using any es6 operators

  • Yes, using Spread Operators
const arr1 = [1,2,3,4];
const arr2 = [5,6];
const arr3 = [...arr1, ...arr2]
console.log(arr3) // output =====> [1,2,3,4,5,6]

πŸ” Scroll to Top

10. Why javascript is dynamically typed language

JavaScript is a dynamically typed language, because the type of a variable is determined at runtime based on the value it holds. For e.g.,

var variable_one = "surbhi"  // "string" datatype is determined at runtime
var variable_two = 20        // "number" datatype is determined at runtime

πŸ” Scroll to Top

11. Difference between Undeclared and Undefined

Undeclared - A variable that has not been declared or doesn't exists in the code

console.log(a); // output =====> ReferenceError: a is not defined

Undefined - A variable that has been declared but not assigned a value yet

let a;
console.log(a); // output =====> undefined

πŸ” Scroll to Top

12. Difference between Null and Undefined

Null - Null means an empty value or a blank value. It is used to represent an intentional absence of value.

let demo = null;
console.log(demo); // output =====> null

Undefined - Undefined means the variable has been declared, but its value has not been assigned yet.

let demo;
console.log(demo); // output =====> undefined

πŸ” Scroll to Top

13. What is Temporal Dead Zone

A "let" or "const" variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.

In JavaScript, variables declared with let or const are hoisted to the top of the block scope, but they enter a "Temporal Dead Zone" (TDZ).

{
  // TDZ for name variable starts here
  console.log(name); // ReferenceError
  let name = "surbhi"; // End of TDZ for name
}

πŸ” Scroll to Top

14. What is IIFE

IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that is executed as soon as it is defined.

An IIFE is typically written as an anonymous function expression that is enclosed within a set of parentheses, followed by another set of parentheses that call the function. For e.g.,

(function() {
  // code goes here
})();

πŸ” Scroll to Top

15. What is Hoisting

Hoisting is a default behavior in JavaScript where variable and function declarations are moved to the top of the current scope

Variable hoisting

console.log(a);  // output =====> undefined
var a = 10;
a=10;
console.log(a);  // output =====> 10
var a;

Function hoisting

demo();  // demo console
function demo() {
	console.log('demo console'); 
}
**Note**
+ Only function declarations are hoisted, not the function expressions.
+ Only the declaration is hoisted, not the initialization. 

πŸ” Scroll to Top

16. What are Cookies

In javascript, a cookie is a piece of data, stored in small text files, on the user's computer by the browser. Cookies are set, read and deleted using the document.cookie property

//**Set a cookie**
document.cookie = "username=surbhi";

//**Read a cookie**
let cookie_variable = document.cookie; 

//**Delete a cookie** (set the expiration date to a past date/time)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

πŸ” Scroll to Top

17. What is memoization

Memoization is a technique used in JavaScript to optimize the performance of functions by caching the results of expensive function calls, based on their input parameters. For e.g., If a function is called multiple times with the same input parameters, then it will perform the same calculations each time. By memoizing the function, we can use the cached result.

function memoizedAdd(num1, num2) {
  let cache = {};
  return function (a, b) {
    const key = num1 + ' and ' + num2;
    if (key in cache) {
      console.log('Retrieving from cache:', key);
      return cache[key];
    } else {
      console.log('Calculating result:', key);
      const result = num1 + num2;
      cache[key] = result;
      return result;
    }
  };
}

const add = memoizedAdd();
console.log(add(2, 3)); // "Calculating result:", "2 and 3", output ========> 5
console.log(add(2, 3)); // "Retrieving from cache:", "2 and 3" output ========> 5

πŸ” Scroll to Top

18. Difference between var, let and const

In javascript, there are 3 ways to declare a variable - var, let, and const. However, they have some differences in their behavior and scope.

var let const
Function scoped Block scoped Block scoped
Can be re-declared in the same scope Can not be re-declared in the same scope Can not be re-declared in the same scope
Can be updated in the same scope Can be updated in the same scope Can not be updated in the same scope
Hoisted to the top of their scope Hoisted to the top but are not initialized Hoisted to the top but are not initialized
Can be declared without being initialized Can be declared without being initialized Can not be declared without being initialized

πŸ” Scroll to Top

19. What is a callback function

A callback function is a function that is passed as an argument to another function. The function that receives the callback as an argument can then invoke the callback at any time during its execution.

function message(callback) {
    console.log('Hi, i am message function');
    callback();
}
// callback function
function callBackFun() {
    console.log('Hey, I am a callback function');
}
// passing callback function as an argument to message function
message(callBackFun);

πŸ” Scroll to Top

20. Is it possible to have both local and global variables with the same name

Yes, we can have both with the same name. But when we do this, the local variable will take precedence over the global variable within the scope of the function or block of code in which it is declared.

However, outside of that scope, the global variable will still be accessible using its name.

let a = 10;
function Demo(){
let a = 20;
console.log(a, "local scope");
}
Demo();
console.log(a, "global scope");

πŸ” Scroll to Top

21. Difference between Local Storage and Session Storage

Local storage and session storage are web storage provided by web browsers to store data on the client-side

Local Storage - Data stored in local storage will persist even after the browser window is closed or the user navigates away from the website and it is available across all windows and tabs of the same origin.

Session Storage - Data stored in session storage will be deleted when the browser window is closed or the session ends and it is available only within the same window or tab that created the data.

πŸ” Scroll to Top

22. Difference between forEach() and map()

map() and forEach() are array methods that can be used to iterate over an array. map()

  1. map() method receives a function as an argument, executes it once for each array element and returns a new array
  2. It is generally used when we need to modify/change data, because it returns a new array with the transformed data
  3. It is chainable because we can attach sort(), filter() etc. after performing a map() method on an array
const arr = [1,2,3,4,5]
let result = arr.map(x => x * x)
console.log(result)   // output ========> [1,4,9,16,25]

forEach()

  1. forEach() method receives a function as an argument, executes it once for each array element but returns undefined.
  2. It is generally used when we just need to iterate over an array
  3. It is not chainable
const arr = [1,2,3,4,5]
let result = arr.forEach(x => x * x)
console.log(result)   // output ========> undefined

πŸ” Scroll to Top

23. What is rest operator

  1. The rest operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
  2. It is used in function parameters and allows you to represent an indefinite number of arguments as an array
function addition(...numbers) {
  return numbers.reduce((a,b)=>a+b);
}
console.log(addition(1, 2, 3, 4)); // output ========> 10
  1. It collects all the remaining arguments passed to a function into an array
function profile(name, designation,...location) {
  return location
}
console.log(profile("surbhi","SE","India","Indore","M.P")); // output ========> ["India", "Indore", "M.P"]

πŸ” Scroll to Top

24. What is spread operator

  1. The spread operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
  2. It allows an iterable to be spread into individual elements
const arr = [1, 2, 3, 4,5];
console.log(...arr); // output ======> 1, 2, 3, 4, 5
  1. It can be used to copy the elements of an existing array into a new array, or to concatenate arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);  // output =======> [1, 2, 3, 4, 5, 6]
  1. It can be used to copy the properties of an existing object into a new object
const obj1 = { a:1, b:2 };
const obj2 = { c:3 };
const obj3 = { ...obj1, ...obj2 }; 
console.log(obj3); // output ========> { a: 1, b: 2, c: 3 }

πŸ” Scroll to Top

25. Difference between async and defer

async and defer are the attributes used with the script tag in HTML to load javaScript files.

Async - The script is loaded in parallel to the HTML parsing, and executed as soon as it is available i.e., it executes the script immediately after it is loaded. It can be useful for scripts that don't depend on the DOM.

Defer - The script is loaded in parallel to the HTML parsing, and executed after the page is completely loaded i.e., it waits until the page has finished parsing. It can be useful for scripts that depend on the DOM.

πŸ” Scroll to Top

26. What is Nullish coalescing operator

  1. The nullish coalescing (??) operator is a logical operator
  2. It allows you to check if a value is either null or undefined
  3. It returns its right-hand side operand if its left-hand side operand is null or undefined, otherwise returns its left-hand side operand
console.log((null || undefined) ?? "foo"); // output ========>  "foo"
console.log("hello" ?? "foo");		   // output ========>  "hello" 

πŸ” Scroll to Top

27. What is the difference between a parameter and an argument

Parameter - A parameter is a variable that is defined during a function declaration or definition. It represents a value that the function or method expects to receive as an input.

Argument - An argument is the actual value that is passed to a function or method when it is called.

function Demo(parameter1, parameter2){
 something------
 something------
}
Demo(argument1, argument2);

πŸ” Scroll to Top

28. What is a closure

A closure is a combination of a function and the environment in which it was created(lexical scope). It gives you access to an outer function's scope from an inner function even if the outer function has returned

function Demo() {
  let name = "Surbhi";
  function displayName() {
    console.log(name);
  }
  return displayName;
}

const result = Demo();
result();

πŸ” Scroll to Top

29. Difference between function declaration and function expression

Function Declaration

  1. A function declaration defines a function using the function keyword, followed by the function name
  2. We can call a function, declared using a function declaration, before it is defined. Because it is hoisted to the top of its scope
  3. It does not require a variable assignment
function Message() {
  console.log("Welcome Message"); // output ========> Welcome Message
}
Message();

Function Expression

  1. A function Expression is similar to a function declaration without the function name
  2. We can not call a function, declared using a function expression, before it is defined
  3. It can be stored in a variable assignment
const Message = function() {
  console.log("Welcome Message"); // output ========> Welcome Message
}
Message();

πŸ” Scroll to Top

30. What are the different ways to create an array in javascript

  1. Using the array literal notation
const arr = [1,2,3,4,5];
  1. Using the Array() constructor
const arr = new Array(1, 2, 3, 4, 5);

πŸ” Scroll to Top

31. Difference between window and document in javascript

window object - window is the topmost object. It represents the browser window or tab containing a DOM document. It provides various properties and methods to manipulate the browser window, such as window.alert(), window.confirm(), and window.location.

document object - document represents the HTML document that is being displayed in the window. It provides properties and methods to manipulate the HTML elements in the document, such as document.title, document.getElementById(), and document.createElement().

πŸ” Scroll to Top

32. What is strict mode in JavaScript

  1. Strict mode was introduced in ECMAScript 5
  2. It performs additional checks on your code to prevent certain types of bugs and errors that may go unnoticed e.g., using undeclared variables, using duplicate property names in objects
  3. It can be enabled at either the global level or at the function level
  4. It can't be apply to block statements enclosed in {} braces
  5. To invoke strict mode, put the exact statement β€œuse strict”; or β€˜use strict’;

πŸ” Scroll to Top

33. What are the different ways to empty an array in javaScript

Using length property

let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); // output ========> []

Assigning it to a new empty array

let arr = [1,2,3,4,5];
arr = [];
console.log(arr); // output ========> []

Using the splice() method

let arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // output ========> []

πŸ” Scroll to Top

34. What is NaN in javascript

  1. In Javascript, NaN stands for "Not a Number"
  2. It is a global property that represents an unrepresentable mathematical result
  3. It is returned when a mathematical operation has no meaningful result. E.g., dividing zero by zero, multiplying/dividing a non-numeric value by a number etc.
console.log(0/0);                  // output ========> NaN
console.log("a"*1);                // output ========> NaN
console.log("a"/1)		   // output ========> NaN
console.log(Math.sqrt(-1));	   // output ========> NaN
console.log(parseInt("blabla"));   // output ========> NaN

πŸ” Scroll to Top

35. Javascript naming convention

  1. Use camelCase (lowercase for the first word, then uppercase for subsequent words) for variable and function names
  2. Use PascalCase for class names (uppercase for the first letter of each word)
  3. Use "is" or "has" as prefixes for boolean variables
  4. Use UPPERCASE for constants
  5. Use descriptive and meaningful names for your variables, functions, and classes.
//variable
let firstName = "Surbhi";

//function
function displayName() {
 return "Surbhi Dighe";
}
displayName();

//boolean
let isLoading = false;
let hasName = true;

//constants
let SECONDS = 60;

//class
class DisplayName { 
  constructor(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
  }
}
var name = new DisplayName('Surbhi', 'Dighe');

πŸ” Scroll to Top

36. Difference between call(), apply() and bind()

call(), apply(), and bind() methods are used to attach a function into an object and call the function as if it belonged to that object.

call() - call() is used to invoke a function immediately with a specified this value and allows you to pass the arguments one by one

let person = {name: 'Surbhi'};
function printName(message) {
    console.log(message + ' ' + this.name);   // output ========> "Hello Surbhi"
}
printName.call(person, 'Hello'); 

apply() - apply() is used to invoke a function immediately with a specified this value and allows you to pass the arguments as an array

let person = {name: 'Surbhi'};
function printName(message) {
    console.log(message + ' ' + this.name);   // output ========> "Hello Surbhi"
}
printName.apply(person, ['Hello']); 

bind() - bind() returns a new function (which can be invoked anytime), with a specified this value and allows you to pass in arguments

let person = {name: 'Surbhi'};
function printName(message) {
    console.log(message + ' ' + this.name);   // output ========> "Hello Surbhi"
}
let sayHello = printName.bind(person, "Hello"); 
sayHello();

πŸ” Scroll to Top

37. What is the use of isNaN function

isNaN() is a built-in JavaScript function. It takes a single argument and returns true if the argument is not a number, otherwise it returns false.

let num1 = 5;
let num2 = "hi";

console.log(isNaN(num1));	// output ========> false
console.log(isNaN(num2));	// output ========> true

πŸ” Scroll to Top

38. What is 'this' keyword in javascript

The value of 'this' is determined by the context in which it is used. In general, 'this' keyword refers to the object it belongs to. The 'this' keyword in JavaScript can have different values depending on where it is used -

  1. If it is used inside a method, then it refers to the object that it belongs to
  2. If it is used inside any function or alone (i.e outside any function or method), then it referes to the global object
  3. If it is used in the context of an event handler, such as a click event, then it refers to the element that triggered the event

πŸ” Scroll to Top

39. How do we add comments in javascript

Single-line comments - Add comments using 2 forward slashes //

// this is a single line comment

Multi-line comments - Enclose the text between /* and */

/*
This is a
multiline comment
example
*/

πŸ” Scroll to Top

40. What is the use of typeof operator

The typeof operator returns a string that indicates the data type of the variable/value.

let var1 = "Surbhi";
let var2 = 10;
console.log(typeof var1);	// output ========> "string"
console.log(typeof var2);       // output ========> "number"

πŸ” Scroll to Top

41. Is JavaScript case-sensitive

Yes, JavaScript is a case-sensitive language. For e.g., the variables firstName and firstname are considered to be two different variables.

let firstName = "Surbhi";
console.log(firstname);         // output ========> Uncaught ReferenceError: firstname is not defined

πŸ” Scroll to Top

42. Difference between push() and unshift()

Both are used to add elements to an array, but they add elements in different ways.

push() - It adds one or more elements to the end of an array and returns the new length of the array.

let arr = [1,2,3,4];
let newArr = arr.push(5,6,7);
console.log(newArr); 		// output ========> 7
console.log(arr);		// output ========> [1, 2, 3, 4, 5, 6, 7]

unshift() - It adds one or more elements to the beginning of an array and returns the new length of the array.

let arr = [1,2,3,4];
let newArr = arr.unshift(5,6,7);
console.log(newArr);		// output ========> 7
console.log(arr);		// output ========> [5, 6, 7, 1, 2, 3, 4]

πŸ” Scroll to Top

43. Difference between pop() and shift()

Both are used to remove elements from an array, but they remove elements in different ways.

pop() - It removes the last element of an array and returns the removed element.

let arr = [1,2,3,4];
let newArr = arr.pop();
console.log(newArr);		// output ========> 4
console.log(arr);		// output ========> [1,2,3]

shift() - It removes the first element of an array and returns the removed element.

let arr = [1,2,3,4];
let newArr = arr.shift();
console.log(newArr);		// output ========> 1
console.log(arr);		// output ========> [2,3,4]

πŸ” Scroll to Top

44. Different ways to access DOM elements in js

getElementById - This method is used to get an element by its ID.

getElementsByClassName - This method is used to get a collection of elements by their class name.

getElementsByTagName - This method is used to get a collection of elements by their tag name.

querySelector - This method is used to get the first element that matches a specified CSS selector.

querySelectorAll - This method is used to get a collection of elements that match a specified CSS selector.

πŸ” Scroll to Top

45. What are promises

In JavaScript, promises are used to handle asynchronous operations. The code does not directly or immediately return a value. Instead, it returns a promise that, it will eventually get resolved or rejected. A promise can have three possible states:

Pending - The initial state, before the promise is resolved or rejected.

Resolved - When a promise has been successfully completed and a value is returned.

Rejected - When a promise has been failed and an error is returned.

let promise = new Promise((resolve, reject) => {
  const result = AsynchronousTaskFunction();
  if (result) {
    resolve(result);
  } else {
    reject(new Error('Operation failed'));
  }
});

promise.then(result => {
  console.log(result, "It is resolved");
}).catch(error => {
  console.error(error, "It is rejected");
});

πŸ” Scroll to Top

46. What is a prototype

Every object in JavaScript has a built-in property, which is called its prototype. All JavaScript objects inherit properties and methods from a prototype.

It allows us to add properties and methods to all instances of a given object type.

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.city = "Indore"
var person1 = new Person('John', 30);
console.log(person1);			

πŸ” Scroll to Top

47. What is a callback hell

Callback hell is a situation in which callback functions are nested inside each other at several levels, making the code difficult to read, write, and maintain.

asyncFunc1(function(response1) {
  asyncFunc2(response1, function(response2) {
    asyncFunc3(response2, function(response3) {
      asyncFunc4(response3, function(response4) {
       asyncFunc5(response4, function(response5) {
        // ... and so on
        });
      });
    });
  });
});

πŸ” Scroll to Top

48. What is an event loop

The event loop is a key mechanism in JavaScript that provides an illusion of being multithreaded despite being single-threaded, allowing for non-blocking, asynchronous processing of events and callbacks.It monitors both the callback queue and the call stack.

If the call stack is not empty, the event loop waits until it is empty

If the call stack is empty it places the next function from the callback queue to the call stack

πŸ” Scroll to Top

49. ES6 and its features

ES6 stands for ECMAScript 6, also known as ECMAScript 2015. It is the sixth major version of the ECMAScript language specification for JavaScript. Below are some of the significant features of ES6

Arrow functions, template literals, block-scoped variables (let and const), default function parameters, array and object destructing, promises, rest and spread operators, classes.

πŸ” Scroll to Top

50. Difference between function and method

method - A method is a function associated with an object.

let obj = {
name:"Surbhi",
greet: function(){     
return `Hi ${this.name}`
}
}
console.log(obj.greet());

function - A function is a self-contained block of code that can be defined and called independently of any object.

function sum(a, b) {
  return a + b;
}
sum(2,4);

πŸ” Scroll to Top

51. What is aync and await

async/await is a feature in JavaScript that allows us to write asynchronous code that looks more like synchronous code. "await" works only inside "async" functions

"async" ensures that a function returns a promise and "await" pause the execution of the function until a promise is resolved or rejected.

const getData = async () => {
  const response = await fetch('https://api.openweathermap.org/data/2.5/weather?q=New%20York&appid=YOUR_API_KEY');
  const data = await response.json();
  console.log(data);
}
getData();

πŸ” Scroll to Top

52. What is the role of event.preventDefault()

The preventDefault() method is used to stop the default action of an element.

E.g., when a user submits a form, the browser sends the form data to the URL specified in the action attribute. In some cases, we may want to prevent this default behavior.

πŸ” Scroll to Top

53. What is the use of JSON.stringify()

JSON.stringify() method is used to convert a JavaScript object or value into an equivalent JSON string.

const obj = { firstname: "Surbhi", lastname: "Dighe" };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // output ========> {"firstname":"Surbhi","lastname":"Dighe"}

πŸ” Scroll to Top

54. How can you stop the setTimeout

You can use the clearTimeout method. This method takes the id returned by setTimeout and cancels the timer.

const timerId = setTimeout(() => {
  console.log('setTimeout is done');
}, 5000);
clearTimeout(timerId);

πŸ” Scroll to Top

55. If Javascript is single threaded, how it supports asynchronous operations

JavaScript is single-threaded, means it can execute only one task at a time. Still, it supports asynchronous operations using the Web API provided by the browser.

πŸ” Scroll to Top

56. What is javascript scope

In JavaScript, scope refers to the current context of your code. This context determines visibility and accessibility of variables, functions, and objects within a certain part of the code. Generally, there are two types of scope in JavaScript - global scope and local scope.

πŸ” Scroll to Top

57. Difference between global scope and local scope

Global scope - Global scope refers to the variables, functions, and objects that are defined outside of any function or block. They can be accessible from any part of the code.

let name = "Surbhi";
function printName() {
  console.log(name);  		// output ========> Surbhi
}
printName();

Local scope - Local scope refers to the variables, functions, and objects that are defined inside any function or block. They can be accessible only within the function or block where they are defined.

function printName() {
  let name = "Surbhi;
  console.log(name); 		// output ========> Surbhi
}
printName();
console.log(name); 		// ReferenceError: name is not defined

πŸ” Scroll to Top

58. What are the different ways to convert a string to an integer

1. parseInt() - This function takes a string and an optional radix (a number between 2 and 36 that represents the base in a numeral system) as its arguments.

console.log(parseInt("20"));		// output ========> 20
console.log(parseInt("52", 8));		// output ========> 42

2. unary plus operator (+) - This operator converts a string into a number and it should be placed before the operand.

console.log(+"10");			// output ========> 10

3. Number() - It is a built-in function which converts its argument to a number. If the argument is a string that contains non-numeric characters, then it returns NaN.

Number("10");				// output ========> 10
Number("abc");    			// output ========> NaN

πŸ” Scroll to Top

59. How to find the operating system in the client machine using JavaScript

We can use the navigator.platform property to find out the operating system of the client machine

console.log(navigator.platform); 	// output ========> 'Linux x86_64'

πŸ” Scroll to Top

60. Name some JavaScript frameworks and libraries

Frameworks - Angular, Ember.js, Vue.js, Meteor, Next.js

Libraries - React, Backbone.js

πŸ” Scroll to Top

61. What is event bubbling and event capturing

Event bubbling and Event Capturing are two different mechanisms used for handling event propagation in the HTML DOM API. When an event is triggered on an element which is inside another element, and both elements have an event listener attached to them , the event propagation mode determines the order in which the elements receive the event.

Event Bubbling - The event is first triggered on the innermost element and then propagated/bubbles up to its parent elements and eventually to the outermost element in the DOM hierarchy.

Event Capturing - The event is first triggered on the outermost element and then propagated/bubbles down to its child elements and eventually to the innermost element in the DOM hierarchy.

πŸ” Scroll to Top

62. What is the role of event.stopPropagation()

This method is used to stop the event from propagating up or down the DOM hierarchy.

πŸ” Scroll to Top

63. How can we change the style of an element using javascript

To change the style of an element using JavaScript, we can use the style property of the element's DOM object.

document.getElementById("myDiv").style.backgroundColor = "red";

πŸ” Scroll to Top

64. What is object destructuring

Object destructuring allows you to extract properties from an object and assign them to variables.

const fullname = {
  firstName: 'Surbhi',
  lastName: 'Dighe',
};
const { firstName, lastName } = fullname;
console.log(firstName); 		// output ========> 'Surbhi'
console.log(lastName); 			// output ========> 'Dighe'

πŸ” Scroll to Top

65. Difference between an Alert Box and a Confirmation Box

Alert Box - It has only one button, typically labeled "OK" and it is used to display a message to the user.

Confirmation Box - It has two buttons, typically labeled "OK" and "Cancel" and it is used to ask the user to confirm an action.

πŸ” Scroll to Top

66. How can we handle exceptions with javascript

In JavaScript, we can handle exceptions using a try-catch block. The try block contains the code that might throw an exception, and the catch block contains the code that handles the exception if it occurs.

try {
  const name = "Surbhi";
  console.log(firstname)
} catch (error) {
  console.log("Error: " + error);  // output ========> Error: ReferenceError: firstname is not defined
}

πŸ” Scroll to Top

67. What are the advantages of using External JavaScript

  • Improve the load time of web pages
  • Ease of editing
  • Code reusability
  • Separation of Code

πŸ” Scroll to Top

68. What is an anonymous function

An anonymous function is a function that does not have a name. It is common to assign anonymous functions to a variable or use them as callback functions.

const sayHi = function() {
  console.log("Hi there!!");
};
sayHi();

πŸ” Scroll to Top

69. What is a first order function

A first order function is a function that does not take any other functions as arguments and does not return any function as its result.

function sayHello() {
  console.log("A first order function")
}
sayHello();

πŸ” Scroll to Top

70. Different ways to access object properties in javascript

Dot notation - It uses dot (.) to access the object properties.

object.propertyName

Bracket notation - It uses bracket "[ ]" to access the object properties.

object[propertyName]

Object destructuring - It creates variables that correspond to the object properties.

const obj1 = {name : "surbhi", designation : "SE"}
const {name , designation} = obj1;
console.log(name, designation)   	// output ========> "Surbhi","SE"

πŸ” Scroll to Top

71. Difference between slice() and splice()

slice() - This method creates a new array by copying a specified section of an existing array and returns that new array. This operation does not modify the original array in any way.

const arr=[1,2,3,4,5];
const result = arr.slice(2)
console.log(arr);		// output ========> [1, 2, 3, 4, 5]
console.log(result);		// output ========> [3, 4, 5]

splice() - This method is used to add or remove elements from an array. It modifies the original array and returns an array containing the removed elements (if any).

const arr=[1,2,3,4,5];
const result = arr.splice(2)
console.log(arr); 		// output ========> [1, 2]
console.log(result);		// output ========> [3, 4, 5]

πŸ” Scroll to Top

72. What are the escape characters in JavaScript

When working with special characters such as ampersands (&), apostrophes ('), double quotes (" "), and single quotes (' '). JavaScript requires the use of escape characters, which are often represented by the backslash (). These escape characters instruct JavaScript to interpret the special characters correctly. Below are some common escape characters in JavaScript:

  • \n - Represents a newline character.
  • \t - Represents a tab character.
  • ' - Represents a single quote character.
  • " - Represents a double quote character.
  • \ - Represents a backslash character.
  • \r - Represents a carriage return character.

πŸ” Scroll to Top

73. Different ways to redirect a page in javascript

location.href - It is used to navigate to a new page and add it to the browser's history.

window.location.href = "https://www.example.com";

location.replace - It is used to replace the current page with a new page without adding it to the history.

window.location.replace("https://www.example.com");

πŸ” Scroll to Top

74. What is the difference between innerHTML and innerText

innerHTML retrieves or modifies the HTML content of an element, including its tags, while innerText only retrieves or modifies the text content of an element, excluding any HTML tags.

//HTML code
<div id="example">Hello <strong>world</strong>!</div>

//Javascript code
let result = document.getElementById("example").innerHTML;
console.log(result); 		// output ========> "Hello <strong>world</strong>!"
//HTML code
<div id="example">Hello <strong>world</strong>!</div>

//Javascript code
let result = document.getElementById("example").innerText;
console.log(result); 		// output ========> "Hello world!"

πŸ” Scroll to Top

75. How can you get current time using js

To get the current time using JavaScript, you can use the built-in Date object.

let currentTime = new Date();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
console.log(`Current time is ${hours}:${minutes}:${seconds}`); // output ========> "Current time is 16:7:22"

πŸ” Scroll to Top

76. What is currying

Currying is the process of breaking down a function that takes multiple arguments into a series of functions that take a single argument.

const add = (a, b) => {
  return a + b;
}
const curryingAdd = (a) => (b) => a + b;
console.log(add(5, 4)); 			// output ========> 9
console.log(curryingAdd(5)(4));			// output ========> 9

πŸ” Scroll to Top

77. Difference between shallow copy and deep copy

shallow copy - It creates a new object that points to the same memory location as the original object. Therefore, any changes made to the original object will also be reflected in the shallow copy. It can be done using the spread operator or object.assign() method.

deep copy - It creates a completely new object with its own memory space. This means that any changes made to the original object will not be reflected in the deep copy. It can be done using the JSON.parse() and JSON.stringify() methods.

πŸ” Scroll to Top

78. What is a service worker

A service worker is a kind of web worker that operates in the background of a web page, decoupled from the primary browser thread, and capable of executing diverse tasks. It is essentially a JavaScript file that is associated with a web page and executes independently, without depending on the user interface.

πŸ” Scroll to Top

79. What is JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

{
"users":[
    {"name":"Test1", "age":"20"},
    {"name":"Test2", "age":"30"},
    {"name":"Test3", "age":"40"}
]
}

πŸ” Scroll to Top

80. How can you get all the keys of any object

The Object.keys() method returns an array containing all the keys of the object

const obj1 = {
  name: 'Surbhi',
  city: 'Indore'
};
const keys = Object.keys(obj1);
console.log(keys); 			// output ========> ["name", "city"]

πŸ” Scroll to Top

81. What is a unary function

A unary function is a function that takes only one argument

function greet(message){
console.log(message, "unary function example");
}

πŸ” Scroll to Top

82. What is promise chaining

Promise chaining is the term used to describe the process of executing a series of asynchronous tasks one after another in a specific order

fetch('API_URL')
  .then(response => response.json())
  .then(data => printData(data))
  .then(anotherData => printAnotherData(anotherData))
  .then(finalData => printFinalData(finalData))

πŸ” Scroll to Top

83. What is eval

The eval() is a method of the JavaScript global object and it takes a string as an argument and evaluates it.

console.log("10" + "20"); 		// output ========> 30

πŸ” Scroll to Top

84. How can you assign default values to variables

You can assign default values to variables using the || operator. If the variable on the left-hand side of the || operator is falsy (e.g. null, 0, undefined, NaN, empty string, false), the expression on the right-hand side of the || operator will be returned.

const var1 = undefined || 'default value';
console.log(var1); 			// output ========> "default value"
const var1 = "surbhi" || 'default value';
console.log(var1);			// output ========> "surbhi"

πŸ” Scroll to Top

85. How to determine if an object is extensible or not

Object.isExtensible() method is used to determine if an object is extensible or not. It returns true if new properties can be added to the object otherwise it returns false.

const obj1 = { name: 'surbhi' };
console.log(Object.isExtensible(obj1));		// output ========> true

πŸ” Scroll to Top

86. In how many ways we can make an object non-extensible

  • Object.preventExtensions()
  • Object.seal()
  • Object.freeze()

πŸ” Scroll to Top

87. What is object.freeze method

  • Object.freeze makes the object immutable
  • Can not add new properties to existing object
  • Can not delete or modify existing properties
const obj = {
  property1: 'value 1',
  property2: 'value 2',
};
Object.freeze(obj);
obj.property1 = 'new value';    // This will not modify the existing property
obj.property3 = 'value 3'; 	// This will not add new property to the object
console.log(obj);		// output ========> { property1: "value 1", property2: "value 2" }

πŸ” Scroll to Top

88. What is object.seal method

  • Object.seal makes the object immutable
  • Can not add new properties or delete existing properties
  • Can modify existing properties.
const obj = {
  property1: 'value 1',
  property2: 'value 2',
};
Object.seal(obj);
obj.property1 = 'new value';    // This will modify the existing property
obj.property3 = 'value 3'; 	// This will not add new property to the object
console.log(obj);		// output ========> { property1: "new value", property2: "value 2" }

πŸ” Scroll to Top

89. How can you determine if JavaScript is disabled on a page

<noscript> tag is used to determine if JavaScript is disabled on a page. It provides alternative content that should be displayed when JavaScript is not supported or disabled in the user's browser.

<noscript>
  <p>JavaScript is disabled in your browser.</p>
</noscript>
<script>
  console.log("JavaScript is enabled on page");
</script>

πŸ” Scroll to Top

90. How can you compare two date objects

getTime() method is used to compare two date objects.

let date1 = new Date();
let date2 = new Date(date1);
console.log(date1.getTime() < date2.getTime());		// output ========> false
console.log(date1.getTime() > date2.getTime()); 	// output ========> false
console.log(date1.getTime() === date2.getTime()); 	// output ========> true

πŸ” Scroll to Top

91. Does JavaScript support automatic type conversion

Yes, JavaScript supports automatic type conversion. It refers to the implicit conversion of one data type to another by the JavaScript engine.

πŸ” Scroll to Top

92. What is variable shadowing in javascript

Variable shadowing means a variable declared in a local scope has the same name as a variable declared in an outer scope. The inner variable "shadows" the outer variable and the outer variable is said to be shadowed.

let x = 10; 
function Demo() {
  let x = 20; 
  console.log(x); 	// output ========> 20
}
myFunction();
console.log(x); 	// output ========> 10

πŸ” Scroll to Top

93. What is ternary operator

The ternary operator is a shorthand conditional operator that allows you to write a compact if-else statement in a single line.

condition ? expression1 : expression2;

It is evaluated from left to right. If the condition is true, the result of the entire expression is expression1, otherwise it's expression2.

let number = 20 ;
let result = number >= 15 ? "output 1" : "output 2";
console.log(result); 	// output ========> output 1

πŸ” Scroll to Top