JavaScript-100-objective-based-questions
This document contains 100 commonly asked JavaScript interview questions with their answers. These questions cover various aspects of JavaScript including data types, operators, functions, OOP, asynchronous programming, and more.
Table of Contents
- Basic JavaScript Questions (Questions 1-25)
- Variables and Scope (Questions 26-35)
- Functions and Closures (Questions 36-50)
- Error Handling (Questions 51-57)
- Object-Oriented Programming (Questions 58-62)
- Web APIs & Asynchronous JavaScript (Questions 63-67)
- Arrays and Data Manipulation (Questions 68-80)
- Event Loop and Performance (Questions 81-88)
- DOM Manipulation and Best Practices (Questions 89-100)
Basic JavaScript Questions
1. Can we connect JavaScript Directly with Actual Database. can you give reason of it ?
a) Yes;b) No;c) Sometime;d) Some DatabaseView Answer
-
Answer: b) No
2. Which of the following is NOT a JavaScript data type?
a) Stringb) Booleanc) Floatd) UndefinedView Answer
-
Answer: c) Float
3. Which symbol is used for single-line comments in JavaScript?
a) //b) /*c) #d) <!--View Answer
-
Answer: a) //
4. What will typeof null return ?
a) "null"b) "object"c) "undefined"d) "string"View Answer
-
Answer: b) "object"
5. How to make immutable object in JavaScript
a) final var ={name:'Anil'}b) const user={name:'Anil'}c) var user={name:'Anil'}; Object.freeze(user);c) There is no way to make immutable objectView Answer
-
Answer: c) var user={name:'Anil'}; Object.freeze(obj);
6. Operators & Expressions What will 2 + “2” evaluate to ?
a) 4b) "22"c) NaNd) ErrorView Answer
-
Answer: b) "22"
7.Which operator is used for strict equality in JavaScript ?
a) ==b) !==c) =d) !=View Answer
-
Answer: b) !==
8. What does !!“false” evaluate to ?
a) trueb) falsec) undefinedd) ErrorView Answer
-
Answer: a) true
9. What is the result of 5 == “5” ?
a) trueb) falseView Answer
-
Answer: a) true
10. What is the result of type of “5 ” === ” 5” ?
a) trueb) falseView Answer
-
Answer: b) false
11. Which loop is guaranteed to execute at least once ?
a) for loopb) while loopc) do-while loopd) None of the aboveView Answer
-
Answer: c) do-while loop
12. Output of this for loop loop
for (;;) { console.log("Loop");}a) Infinit Loopb) Loop will not executec) Errord) Only Run onceView Answer
-
Answer: a) Infinit Loop
13. What will console.log(typeof NaN); print ?
a) "number"b) "NaN"c) "undefined"d) "object"View Answer
-
Answer: a) "number"
14. Output of below statment
let x = null;let y = null;console.log(x + y);a) nullb) objectc) 0d) undefinedView Answer
-
Answer: c) 0
15. What will console.log(typeof function(){}); return ?
a) "function"b) "object"c) "undefined"d) "null"View Answer
-
Answer: a) "function"
_ 16. What will console.log(typeof function(){}(); return? _
a) "function"b) "object"c) "undefined"d) "null"View Answer
-
Answer: c) "undefined"
17. What is the default return value of a function in JavaScript if no return statement is used ?
a) nullb) undefinedc) falsed) 0View Answer
-
Answer: b) undefined
18. Which type of function executes immediately after its definition ?
a) Anonymous functionb) Named functionc) IIFE (Immediately Invoked Function Expression)d) Arrow functionView Answer
-
Answer: c) IIFE
19 Output of below statement
console.log(x);let x = 5;a) 5b) undefinedc) ReferenceErrord) NaNView Answer
-
Answer: c) ReferenceError
20. How do you create an object in JavaScript ?
a) let obj = {};b) let obj = new Object();c) Both a and bd) None of the aboveView Answer
-
Answer: c) Both a and b
21 How do you access a property in an object ?
a) obj[property]b) obj.propertyc) Both a and bd) None of the aboveView Answer
-
Answer: c) Both a and b
22. Which method is used to add a new element at the end of an array ?
a) push()b) pop()c) shift()d) unshift()View Answer
-
Answer: a) push()
23 What will console.log([1,2,3].length); return ?
a) 2b) 3c) 4d) undefinedView Answer
-
Answer: b) 3
24 How do you remove first 2 element of an array?
a) pop()b) shift()c) unshift()d) splice()View Answer
-
Answer: d) splice()
25 Which keyword allows block-scoped variable declarations ?
a) varb) letc) constd) Both b and cView Answer
-
Answer: d) Both b and c
26 Which of the following is true about const variables?
a) Their values cannot be changedb) They cannot be reassignedc) They are always immutabled) All of the aboveView Answer
-
Answer: b) They cannot be reassigned
27. What is the output of console.log(typeof([])); ?
a) "object"b) "array"c) "undefined"d) "null"View Answer
-
Answer: a) "object"
28 What is a template literal in JavaScript ?
a) A type of arrayb) A string enclosed in backticks (` `)c) A special functiond) A new ES6 data typeView Answer
-
Answer: b) A string enclosed in backticks (` `)
29. What will console.log(…”Hello”); output ?
a) "H e l l o"b) ["H", "e", "l", "l", "o"]c) Syntax Errord) undefinedView Answer
-
Answer: a) "H e l l o"
** 30. How do you define an arrow function ?**
a) const add = (a, b) => a + b;b) const add = function(a, b) { return a + b; };c) Both a and bd) None of the aboveView Answer
-
Answer: a) const add = (a, b) => a + b;
31 What does the spread operator … do in JavaScript ?
a) Combines arraysb) Expands iterable elementsC) All of the aboveView Answer
-
Answer: C) All of the above
** 32. What will console.log([…new Set([1, 2, 2, 3])]); return ?**
a) [1, 2, 3]b) [1, 2, 2, 3]c) Set {1, 2, 3}d) {1, 2, 3}View Answer
-
Answer: a) [1, 2, 3]
33. Which statement about arrow functions is true ?
a) They do not bind thisb) They can be used as constructorsc) They have a prototype propertyd) They support arguments keywordView Answer
-
Answer: a) They do not bind this
**34 Output of follow code? **
function tryFruits(...fruits) { console.log(...fruits);}
tryFruits("apple", "banana", "grapes");a) ['apple', 'banana', 'grapes']b) {'apple', 'banana', 'grapes'}c) 'apple 'banana grapes'd) 'apple'View Answer
-
Answer: a) ['apple', 'banana', 'grapes']
35. What is the purpose of JavaScript Promises ?
a) Handle synchronous codeb) Handle asynchronous operationsc) Block execution until resolvedd) Replace all callbacksView Answer
-
Answer: b) Handle asynchronous operations
36. Which state is NOT valid for a Promise ?
a) Pendingb) Fulfilledc) Rejectedd) RunningView Answer
-
Answer: d) Running
37. Use of Await keyword ?
a) wait for an asynchronous operation to finish before continuing the executionb) make promisec) atop executiond) all of aboveView Answer
-
Answer: a) wait for an asynchronous operation to finish before continuing the execution
38. Which method selects an element by ID?
a) document.getElementofId()b) document.getElementById()c) document.selectElementById()d) document.selectById()View Answer
-
Answer: b) document.getElementById()
39 Which event is triggered when an input field loses focus ?
a) clickb) blurc) focusd) changeView Answer
-
Answer: b) blur
40. Which method adds an event listener to an element ?
a) element.addEventListener()b) element.attachEvent()c) element.onEvent()d) element.setEventListener()View Answer
-
Answer: a) element.addEventListener()
41. What does event.preventDefault() do ?
a) Stops the default action of an eventb) Stops event propagationc) Prevents event from being attachedd) None of the aboveView Answer
-
Answer: a) Stops the default action of an event
43. What is localStorage used for?
a) Storing session datab) Storing data persistently in the browserc) Making API requestsd) Caching imagesView Answer
-
Answer: b) Storing data persistently in the browser
44 Which method converts a JavaScript object into a JSON string?
a) JSON.stringify()b) JSON.parse()c) toJSON()d) parseJSON()View Answer
-
Answer: a) JSON.stringify()
45 What will console.log(parseInt(“10px”)) return ?
a) 10b) NaNc) "10px"d) ErrorView Answer
-
Answer: a) 10
46. Which method executes a function repeatedly with a time interval ?
a) setInterval()b) setTimeout()c) repeat()d) setLoop()View Answer
-
Answer: a) setInterval()
47. How do you check if a variable is an array ?
a) typeof x === "array"b) x.isArray()c) Array.isArray(x)d) x instanceof ObjectView Answer
-
Answer: c) Array.isArray(x)
** 48. What is a closure in JavaScript?**
a) A function inside another function that has access to its parent’s scopeb) A block of code that runs automaticallyc) A way to define private variablesd) Both a and cView Answer
-
Answer: d) Both a and c
49. Which of the following is true about closures ?
a) Closures have access to their own scopeb) Closures have access to their parent function's scopec) Closures have access to global scoped) All of the aboveView Answer
-
Answer: d) All of the above
50.What will this code output?
function outer() { let count = 0; return function inner() { count++; console.log(count); };}const counter = outer();counter();counter();a) 1 2b) 0 1c) 1 1d) ErrorView Answer
-
Answer: a) 1 2
51. Which statement about var and let is true ?
a) Both are function-scopedb) var is function-scoped, let is block-scopedc) Both are block-scopedd) var allows redeclaration, let doesn’tView Answer
-
Answer: b) var is function-scoped, let is block-scoped
52. What will console.log(x); var x = 10; output?
a) 10b) undefinedc) ReferenceErrord) NaNView Answer
-
Answer: b) undefined
53. Which statement is used for error handling in JavaScript ?
a) try...catchb) throwc) finallyd) All of the aboveView Answer
-
Answer: d) All of the above
54 What happens if an error occurs inside the try block ?
a) The script stops executionb) The error is caught in the catch blockc) The script crashesd) The error is ignoredView Answer
-
Answer: b) The error is caught in the catch block
55. What will console.log(x); inside a try block with no catch or finally do?
a) Print undefinedb) Print nullc) Throw a ReferenceErrord) NothingView Answer
-
Answer: c) Throw a ReferenceError
56. Which method is used to generate a custom error ?
a) throw new Error()b) console.error()c) generateError()d) raiseError()View Answer
-
Answer: a) throw new Error()
57. What will finally do in a try-catch-finally block ?
a) Execute only if no error occursb) Execute only if an error occursc) Always executed) None of the aboveView Answer
-
Answer: c) Always execute
58. OOP (Object-Oriented Programming) in JavaScript Which keyword is used to create a class in JavaScript?
a) classb) functionc) Classd) new ClassView Answer
-
Answer: a) class
59. What is the purpose of the constructor method in a class ?
a) To create private variablesb) To initialize object propertiesc) To call another classd) None of the aboveView Answer
-
Answer: b) To initialize object properties
60. Which keyword is used for inheritance in JavaScript ?
a) implementsb) extendsc) inheritsd) prototypeView Answer
-
Answer: b) extends
61. Which method in a class is used to call the parent class constructor ?
a) parent()b) super()c) this()d) constructor()View Answer
-
Answer: b) super()
62 Which statement about JavaScript classes is true ?
a) They support multiple inheritanceb) They are syntactic sugar over prototypesc) They can be redeclaredd) They do not support inheritanceView Answer
-
Answer: b) They are syntactic sugar over prototypes
63 Web APIs & Asynchronous JavaScript
Which API is used for making HTTP requests in JavaScript?a) XMLHttpRequestb) Fetch APIc) Axiosd) All of the aboveView Answer
-
Answer: d) All of the above
64. Which method sends a GET request using Fetch API ?
a) fetch(url)b) fetch(url, { method: 'GET' })c) Both a and bd) None of the aboveView Answer
-
Answer: c) Both a and b
65. What does navigator.geolocation.getCurrentPosition() do ?
a) Gets user’s IP addressb) Gets user’s locationc) Opens a Google Maps paged) None of the aboveView Answer
-
Answer: b) Gets user’s location
66. Which storage API stores data persistently ?
a) localStorageb) sessionStoragec) cookiesd) All of the aboveView Answer
-
Answer: a) localStorage
67. How can you set an interval in JavaScript ?
a) setTimeout()b) setInterval()c) setRepeat()d) Interval()View Answer
-
Answer: b) setInterval()
68 Which method removes an element from an array ?
a) splice()b) slice()c) remove()d) delete()View Answer
-
Answer: a) splice()
69. Which JavaScript engine is used in Google Chrome ?
a) SpiderMonkeyb) V8c) Chakrad) NitroView Answer
-
Answer: b) V8
70. Which method converts a string into a number ?
a) parseInt()b) Number()c) + (unary plus)d) All of the aboveView Answer
-
Answer: d) All of the above
71. Which function generates a random number between 0 and 1 ?
a) Math.random()b) random()c) generateRandom()d) Math.rand()View Answer
-
Answer: a) Math.random()
72. Which of the following is a falsy value in JavaScript ?
a) "false"b) "0"c) undefinedd) "undefined"View Answer
-
Answer: c) undefined
73 What will console.log([] == false); return ?
a) trueb) falsec) undefinedd) ErrorView Answer
-
Answer: a) true
74. Which of the following is NOT a primitive data type in JavaScript ?
a) Numberb) Stringc) Objectd) SymbolView Answer
-
Answer: c) Object
75 How do you deep clone an object in JavaScript ?
a) Object.assign({}, obj)b) JSON.parse(JSON.stringify(obj))c) obj.clone()d) obj.copy()View Answer
-
Answer: b) JSON.parse(JSON.stringify(obj))
76. What is the output of console.log(2 + “2” - 1); ?
a) "21"b) 21c) "22"d) 1View Answer
-
Answer: b) 21
77. Which method is used to filter elements from an array ?
a) map()b) filter()c) reduce()d) slice()View Answer
-
Answer: b) filter()
78 Which function combines array elements into a single value ?
a) reduce()b) map()c) join()d) concat()View Answer
-
Answer: a) reduce()
79. What does the following code return ?
console.log([1, 2, 3].map((num) => num * 2));a) [2, 4, 6]b) [1, 4, 9]c) [1, 2, 3]d) [2, 3, 4]View Answer
-
Answer: a) [2, 4, 6]
80. Which of the following is NOT an immutable operation?*
a) map()b) filter()c) splice()d) concat()View Answer
-
Answer: c) splice()
81. What is the event loop in JavaScript ?
a) A process that handles function callsb) A mechanism that allows async operationsc) A feature that prevents infinite loopsd) A method to execute codeView Answer
-
Answer: b) A mechanism that allows async operations
82. Which of the following executes first in the event loop ?
a) setTimeout()b) setInterval()c) Promise.resolve().then()d) console.log()View Answer
-
Answer: d) console.log()
83. Which queue does setTimeout() use in JavaScript ?
a) Microtask queueb) Callback queuec) Event loop queued) Execution stackView Answer
-
Answer: b) Callback queue
84. What will be the output of this code ?
console.log("A");setTimeout(() => console.log("B"), 0);console.log("C");a) A B Cb) A C Bc) B A Cd) C A BView Answer
-
Answer: b) A C B
85. Which of the following is a best practice in JavaScript ?
a) Using == instead of ===b) Avoiding global variablesc) Using var instead of letd) Nesting loops as deep as possibleView Answer
-
Answer: b) Avoiding global variables
86. What does “debouncing” do in JavaScript?
a) Delays function execution until a pause in eventsb) Executes a function immediatelyc) Runs a function continuouslyd) None of the aboveView Answer
-
Answer: a) Delays function execution until a pause in events
87. What does “throttling” do?
a) Executes a function only at fixed intervalsb) Prevents a function from runningc) Removes unnecessary function callsd) Stops event propagationView Answer
-
Answer: a) Executes a function only at fixed intervals
88. Which of the following improves JavaScript performance ?
a) Minifying JavaScript filesb) Using lazy loadingc) Avoiding unnecessary DOM manipulationsd) All of the aboveView Answer
-
Answer: d) All of the above
89. What is the best way to check if a variable is null or undefined ?
a) if (x == null)b) if (typeof x === "null")c) if (x === null || x === undefined)d) if (x == undefined)View Answer
-
Answer: c) if (x === null || x === undefined)
90. What does document.createElement(‘div’) do ?
a) Creates and appends a divb) Creates a div but does not append itc) Selects an existing divd) Deletes all div elementsView Answer
-
Answer: b) Creates a div but does not append it
91. Which API is used to create animations in JavaScript ?
a) WebGLb) requestAnimationFrame()c) animateCSS()d) window.setInterval()View Answer
-
Answer: b) requestAnimationFrame()
92. Which function removes whitespace from both ends of a string ?
a) trim()b) slice()c) removeSpace()d) strip()View Answer
-
Answer: a) trim()
93. Which method removes the last element from an array ?
a) pop()b) shift()c) splice()d) removeLast()View Answer
-
Answer: a) pop()
94. What is the output of the following code ?
console.log(myFunc);function myFunc() { return "Hello";}A) undefinedB) ReferenceError: myFunc is not definedC) [Function: myFunc]D) TypeError: myFunc is not a functionView Answer
-
Answer: c) ƒ myFunc() { return "Hello"; }
95. Which of the following is an example of a higher-order function ?
a) A function that returns another functionb) A function with a return type of voidc) A function that has a loop insided) A function that only contains if-else statementsView Answer
-
Answer: a) A function that returns another function
96. Which method is used to handle asynchronous functions in JavaScript ?
a) setTimeout()b) Promise.then()c) async/awaitd) All of the aboveView Answer
-
Answer: d) All of the above
97. Which of the following is NOT true about closures ?
a) A closure allows a function to retain access to variables from its outer scope.b) Closures are created every time a function is invoked.c) Closures help in data encapsulation.d) Closures cannot access global variables.View Answer
-
Answer: d) Closures cannot access global variables.
98. What will be the output of the following code ?
const obj = { value: 42, getValue: () => { return this.value; },};console.log(obj.getValue());a) 42b) undefinedc) ReferenceErrord) nullView Answer
-
Answer: b) undefined
99 What will be the output of the following asynchronous function ?
async function foo() { return "Hello";}console.log(foo());a) "Hello"b) Promise { "Hello" }c) undefinedd) ErrorView Answer
-
Answer: b) Promise { "Hello" }
100. What is currying in JavaScript?
a) A technique where a function is transformed into a sequence of unary (one-argument) functions.b) A method to execute functions asynchronously.c) A way to cache function results for optimization.d) A technique to convert a function into a class.View Answer
-
Answer: a) A technique where a function is transformed into a sequence of unary functions.