Java Script MCQs
Q.1 Identify the error in this function:
function multiply(a, b) {
console.log(a * b);
}
A. It does not return any value
B. It returns the wrong value
C. Syntax error
D. No error
Q.2 What does the following function return?
function checkEven(number) {
return number % 2 === 0;
}
console.log(checkEven(3));
A. true
B. false
C. 3
D. Error
Q.3 Consider the following code snippet:
function greet() {
return ‘Hello World’;
}
console.log(greet());
What is the output?
A. ‘greet’
B. ‘Hello World’
C. undefined
D. Error
Q.4 What is the result of trying to extend the length of an array using a function in JavaScript?
function extendArray(arr) {
arr.push(5);
}
let myArr = [1, 2, 3];
extendArray(myArr);
console.log(myArr.length);
A. 3
B. 4
C. 5
D. Error
Q.5 Which of the following is true about arrow functions in JavaScript?
A. They do not have their own this context
B. They can be used as constructors
C. They must have a return statement
D. They are the same as traditional functions
Q.6 In JavaScript, what is a callback function?
A. A function that runs after the page loads
B. A function passed as an argument to another function
C. A function that calls itself
D. A function that performs an HTTP request
Q.7 What will be the output of this function call?
function sum(a, b) {
return a + b;
}
console.log(sum(3, 4));
A. 3
B. 4
C. 7
D. Error
Q.8 How do you define a function in JavaScript?
A. function = myFunc() {}
B. function: myFunc() {}
C. function myFunc() {}
D. myFunc() = function {}
Q.9 What is the purpose of a function in JavaScript?
A. To store data
B. To repeat a task multiple times
C. To encapsulate code that performs a specific task
D. To create web pages
Q.10 Find the error in the following code:
for (let i = 0; i <= 5; i++) {
if(i % 2 == 0) continue;
console.log(i);
}
A. It doesn’t print any number
B. It only prints odd numbers
C. It only prints even numbers
D. Syntax error
Q.11 Identify the problem in this code:
let i = 0;
while (i < 3) {
console.log(i);
}
A. Infinite loop
B. Syntax error
C. Logical error
D. No output
Q.12 Consider the following code:
let x = 5;
let result = (x > 3) ? ‘Yes’ : ‘No’;
console.log(result);
What is the output?
A. ‘Yes’
B. ‘No’
C. true
D. false
Q.13 What is the output of this code snippet?
for (let i = 0; i < 3; i++) {
console.log(i);
}
A. 012
B. 123
C. 0-1-2
D. 1-2-3
Q.14 In a for loop, what are the three optional expressions, separated by semicolons?
A. Initializer, Condition, Incrementer
B. Condition, Incrementer, Initializer
C. Incrementer, Initializer, Condition
D. Condition, Initializer, Incrementer
Q.15 What will be the output of the following code?
let a = 2;
if(a > 3) {
console.log(‘Yes’);
} else {
console.log(‘No’);
}
A. Yes
B. No
C. Undefined
D. Error
Q.16 In a switch statement, what keyword is used to terminate a case in JavaScript?
A. end
B. break
C. stop
D. exit
Q.17 Which of the following is not a loop structure in JavaScript?
A. while
B. for
C. if
D. do-while
Q.18 What does the if statement in JavaScript do?
A. Declares a variable
B. Executes a block of code based on a condition
C. Prints a message to the console
D. Loops through a block of code
Q.19 Which statement is used to execute a block of code multiple times in JavaScript?
A. for
B. if
C. return
D. break
Q.20 What is the output of the following code snippet?
let x = ‘Hello’;
let y = ‘World’;
console.log(x + ‘ ‘ + y);
A. HelloWorld
B. ‘Hello World’
C. ‘Hello’ ‘World’
D. Hello World
Q.21 What is the output of the following code snippet?
var a = 10;
console.log(a);
A. 10
B. ’10’
C. undefined
D. null
Q.22 Which operator is used to check both the value and the type of a variable in JavaScript?
A. ==
B. ===
C. !=
D. !==
Q.23 Which of the following is an example of a loosely typed language?
A. Java
B. C++
C. JavaScript
D. Python
Q.24 What will be the output of the following code?
console.log(typeof null);
A. ‘object’
B. ‘null’
C. ‘undefined’
D. ‘number’
Q.25 What does the undefined value in JavaScript represent?
A. An unassigned variable
B. A null value
C. A logical false
D. An error condition
Q.26 Which data type in JavaScript is used to represent logical values?
A. String
B. Boolean
C. Number
D. Undefined
Q.27 In JavaScript, which of the following is a valid variable name?
A. 2names
B. $name
C. -name
D. name2
Q.28 Which keyword is used for declaring a variable in JavaScript that can be reassigned?
A. const
B. var
C. let
D. static
Q.29 What is the purpose of JavaScript in web development?
A. To structure web pages
B. To style web pages
C. To add interactivity and dynamic content to web pages
D. To store data on the server
Q.30 Which of the following is a correct syntax to display “Hello World” in an alert box using JavaScript?
A. alertBox(‘Hello World’);
B. alert(‘Hello World’);
C. msgAlert(‘Hello World’);
D. displayAlert(‘Hello World’);
Q.31 What will be the result of the following code if the HTML has multiple p tags?
let paragraphs = document.getElementsByTagName(‘p’);
for(let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = ‘blue’;
}
A. All p tags turn blue
B. Only the first p tag turns blue
C. A TypeError occurs
D. No change in p tags
Q.32 Consider this code:
let items = document.querySelectorAll(‘.item’);
console.log(items.length);
What does it output if there are three elements with class item in the HTML?
A. 3
B. ‘item’
C. undefined
D. Error
Q.33 What is the output of this code if the HTML contains an element with id demo and text ‘Hello’?
document.getElementById(‘demo’).textContent = ‘Hi’; console.log(document.getElementById(‘demo’).textContent);
A. ‘Hello’
B. ‘Hi’
C. undefined
D. Error
Q.34 What is the difference between innerHTML and textContent properties in DOM manipulation?
A. innerHTML can include HTML tags; textContent cannot
B. textContent is faster than innerHTML
C. textContent can include HTML tags; innerHTML cannot
D. There is no difference
Q.35 How can you change the text content of an HTML element in the DOM using JavaScript?
A. element.textContent = ‘new text’
B. element.innerHTML = ‘new text’
C. Both A and B
D. Neither A nor B
Q.36 Which JavaScript method is used to select an HTML element by its ID?
A. getElementById()
B. querySelector()
C. getElementsByClassName()
D. getElementsByTagName()
Q.37 What does DOM stand for in web development?
A. Document Object Model
B. Data Object Management
C. Direct Object Manipulation
D. Display Object Model
Q.38 Identify the error in this object method:
let obj = {
greet: function() {
return ‘Hello, ‘ + name;
}
};
console.log(obj.greet());
A. name is not defined
B. greet is not a function
C. Syntax error
D. No error
Q.39 Find the issue in this object definition:
let obj = { ‘1a’: 10, b: 20 };
console.log(obj.1a);
A. Invalid property name
B. Syntax error in console.log
C. Incorrect value assignment
D. No error
Q.40 Given the following code, what is printed to the console?
let obj1 = { a: 1 };
let obj2 = { a: 1 };
console.log(obj1 === obj2);
A. true
B. false
C. null
D. Error
Q.41 Consider the code:
let person = { name: ‘Alice’, age: 25 };
delete person.age; console.log(person.age);
What is the output?
A. ‘Alice’
B. 25
C. undefined
D. Error
Q.42 What is the output of the following code snippet?
let obj = { a: 1, b: 2 };
console.log(obj.a);
A. 1
B. 2
C. undefined
D. Error
Q.43 What is the result of accessing a property that doesn’t exist on an object?
A. null
B. undefined
C. 0
D. Error
Q.44 What is the purpose of the this keyword in JavaScript objects?
A. Refer to the global object
B. Refer to the current object
C. Create a new object
D. Duplicate an object
Q.45 How do you create a new object in JavaScript?
A. Object.create()
B. new Object()
C. Both A and B
D. Neither A nor B
Q.46 In JavaScript, what is a method?
A. A predefined function
B. A loop inside an object
C. A function stored as an object property
D. An external library function
Q.47 What will be the output of console.log(typeof {})?
A. ‘object’
B. ‘array’
C. ‘null’
D. ‘undefined’
Q.48 How do you access the value of a property in a JavaScript object?
A. object{propertyName}
B. object[propertyName]
C. object.propertyName
D. Both B and C
Q.49 Spot the mistake in this code snippet:
let data = [1, 2, 3];
delete data[1];
console.log(data[1]);
A. undefined is logged instead of 2
B. 2 is not deleted
C. Syntax error
D. No error
Q.50 Identify the issue in this array declaration:
let numbers = new Array(-5);
A. Negative size
B. Syntax error
C. Logical error
D. No error
Q.51 Consider the following code:
let arr = [1, 2, 3];
arr[5] = 5;
console.log(arr.filter(x => x === undefined).length);
What is the output?
A. 0
B. 2
C. 3
D. 5
Q.52 What will be the output of this code snippet?
let numbers = [1, 2, 3];
numbers[10] = 11;
console.log(numbers.length);
A. 3
B. 4
C. 11
D. 10
Q.53 What is the output of the following code?
let fruits = [‘apple’, ‘banana’, ‘mango’];
console.log(fruits[1]);
A. apple
B. banana
C. mango
D. undefined
Q.54 What is the output of this code snippet?
let arr = [10, 20, 30, 40];
let newArr = arr.map(x => x / 10);
console.log(newArr);
A. [1, 2, 3, 4]
B. [10, 20, 30, 40]
C. [0.1, 0.2, 0.3, 0.4]
D. Error
Q.55 Which of the following array methods in JavaScript does not change the original array?
A. sort()
B. splice()
C. forEach()
D. push()
Q.56 In JavaScript, how can you check if a variable is an array?
A. typeof variable
B. variable.isArray()
C. Array.isArray(variable)
D. variable instanceof Array
Q.57 What does the splice method do in an array?
A. Copies a portion of an array
B. Concatenates arrays
C. Changes the content of an array
D. Finds an element in an array
Q.58 How do you find the length of an array in JavaScript?
A. array.size()
B. array.length
C. array.count()
D. length(array)
Q.59 Which method is used to add an element to the end of an array in JavaScript?
A. push()
B. unshift()
C. pop()
D. shift()
Q.60 What is wrong with this function declaration?
function power(base, exponent) {
if (exponent == 0) return 1;
else return base * power(base, exponent – 1);
} console.log(power(2));
A. It doesn’t handle the case when exponent is not provided
B. It returns the wrong value
C. It causes an infinite loop
D. Syntax error
Q.61 Identify the error in this code:
try {
let result = ‘Result’;
console.log(result);
} catch(e) {
console.log(e);
} finally {
console.log(reslt);
}
A. Misspelled variable in the finally block
B. Error in the try block
C. Error in the catch block
D. No error
Q.62 What will happen when this code is executed?
try {
null.foo();
}
catch(e) {
console.log(e.name);
} finally {
console.log(‘Done’);
}
A. Logs ‘TypeError’ and ‘Done’
B. Logs ‘ReferenceError’ and ‘Done’
C. Only logs ‘Done’
D. Causes a fatal error
Q.63 What will this code output?
try {
let x = y;
} catch(e) {
console.log(typeof e);
}
A. ‘undefined’
B. ‘object’
C. ‘string’
D. ‘error’
Q.64 What is the output of this code?
try {
console.log(‘Start’);
throw new Error(‘An error occurred’);
console.log(‘End’);
} catch(e) {
console.log(‘Caught an error’);
}
A. ‘Start’ ‘End’ ‘Caught an error’
B. ‘Start’ ‘Caught an error’
C. ‘Caught an error’
D. ‘Start’ ‘An error occurred’
Q.65 What is the difference between a SyntaxError and a ReferenceError in JavaScript?
A. A SyntaxError occurs for mistakes in the code’s syntax, while a ReferenceError occurs for illegal or invalid references to variables
B. A SyntaxError occurs when variables are not found, while a ReferenceError occurs for syntax mistakes
C. A SyntaxError is a runtime error, while a ReferenceError is a compile-time error
D. No difference
Q.66 What does the finally block in a try…catch statement do?
A. It runs only if no errors occur
B. It runs after the try and catch blocks, regardless of the result
C. It runs as a cleanup process
D. It checks for any remaining errors
Q.67 Which statement is used to manually throw an exception in JavaScript?
A. throw
B. error
C. exception
D. raise
Q.68 What type of error is thrown when an undefined variable is used in JavaScript?
A. SyntaxError
B. TypeError
C. ReferenceError
D. RangeError
Q.69 What is the purpose of the try…catch statement in JavaScript?
A. To test code for errors
B. To speed up code execution
C. To declare variables
D. To loop through arrays
Q.70 Spot the error in this code:
fetch(‘https://api.example.com/data’)
.then(response => console.log(response.json()));
A. Improper use of response.json()
B. Missing catch for error handling
C. The URL is incorrect
D. There is a syntax error
Q.71 Identify the issue in this fetch request:
fetch(‘https://api.example.com/data’, {
method: ‘GET’,
body: JSON.stringify({id: 1})
});
A. GET requests should not have a body
B. The URL is incorrect
C. The method should be POST
D. There is a syntax error
Q.72 How does this code handle errors when using the Fetch API?
fetch(‘https://api.example.com/data’)
.then(response => {
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
return response.json();
})
.catch(error => console.error(‘Fetch error:’, error));
A. It logs errors to the console
B. It redirects the user to an error page
C. It retries the fetch request
D. It sends an error report to the server
Q.73 What will this Fetch API code snippet do?
fetch(‘https://api.example.com/update’, {
method: ‘POST’,
body: JSON.stringify({name: ‘Alice’})
})
.then(response => response.json())
.then(data => console.log(data));
A. Retrieves data from the URL
B. Updates data at the URL and logs the response
C. Deletes data at the URL
D. Submits data to the URL and logs the response
Q.74 What does the following JavaScript code do?
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => console.log(data));
A. Sends data to ‘https://api.example.com/data’
B. Requests data from ‘https://api.example.com/data’ and logs it
C. Creates a new resource at ‘https://api.example.com/data’
D. Deletes data from ‘https://api.example.com/data’
Q.75 What is the difference between the Fetch API and XMLHttpRequest?
A. Fetch can only send asynchronous requests
B. Fetch returns a promise, making it easier to work with asynchronous operations
C. XMLHttpRequest is faster than Fetch
D. Fetch cannot handle responses in JSON format
Q.76 What is the purpose of the Fetch API in JavaScript?
A. To send data to a server
B. To manipulate the DOM
C. To retrieve resources asynchronously over the network
D. To store data in the browser
Q.77 What is the main advantage of using AJAX in a web application?
A. Faster server response time
B. Increased security
C. Reduced server load and asynchronous requests
D. Simpler coding requirements
Q.78 What does AJAX stand for in web development?
A. Asynchronous JavaScript And XML
B. Automated JavaScript And XHTML
C. Advanced JavaScript And XML
D. Asynchronous Java And XML
Q.79 What is the issue with this code?
button.addEventListener(‘click’, doSomething); function doSomething() {
alert(‘Clicked’);
}
A. Missing event listener
B. doSomething is not defined
C. Incorrect event type
D. No error
Q.80 Identify the error in this code:
document.getElementById(‘myBtn’).onClick = function() {
console.log(‘Button clicked’);
};
A. Incorrect event property
B. Syntax error
C. Logic error
D. No error
Q.81 What will be the result of this code if div1 is inside div2 in the HTML structure?
document.getElementById(‘div1’).addEventListener(‘click’, function(event) {
console.log(‘div1 clicked’);
event.stopPropagation();
});
document.getElementById(‘div2’).addEventListener(‘click’, function() {
console.log(‘div2 clicked’);
});
A. Only ‘div1 clicked’ will be logged
B. Only ‘div2 clicked’ will be logged
C. Both ‘div1 clicked’ and ‘div2 clicked’ will be logged
D. No message will be logged
Q.82 Consider the following code snippet:
element.addEventListener(‘click’, function() {
console.log(‘Element clicked’);
});
What does this code do?
A. Logs a message when the element is double-clicked
B. Changes the style of the element when clicked
C. Logs a message when the element is clicked
D. Submits a form when the element is clicked
Q.83 What does the following JavaScript code do?
document.getElementById(‘btn’).onclick = function() {
alert(‘Button clicked’);
};
A. Displays an alert when a button is clicked
B. Changes the text of a button
C. Reloads the page
D. Does nothing
Q.84 How can you stop event propagation in JavaScript?
A. event.stop()
B. event.preventDefault()
C. event.stopPropagation()
D. event.pause()
Q.85 Which of the following is not a mouse event in JavaScript?
A. onclick
B. onmouseover
C. onmousemove
D. onchange
Q.86 What is event bubbling in JavaScript?
A. When an event on a child element is also triggered on parent elements
B. When an event triggers a server request
C. When an event occurs repeatedly in a short period
D. When an event fails to trigger
Q.87 Which method is commonly used to attach an event handler to an element in JavaScript?
A. addEventListener()
B. attachEvent()
C. onEvent()
D. bindEvent()
Q.88 What is an event in the context of JavaScript?
A. A user action like a mouse click
B. A change in the state of the program
C. A server response
D. All of the above
Q.89 Spot the mistake in this code:
let btn = document.getElementById(‘submit’);
btn.onClick = function() {
console.log(‘Clicked’);
};
A. Incorrect event handler
B. Missing element with id ‘submit’
C. Syntax error in the function
D. No error
Q.90 Identify the error in this code:
document.getElementByld(‘demo’).innerText = ‘Welcome’;
A. Typo in method name
B. Missing element with id ‘demo’
C. Incorrect property innerText
D. No error
Q.91 Identify the issue in this async function:
async function loadData() {
let data = await fetch(‘https://api.example.com’).json();
console.log(data);
}
A. Incorrect use of await
B. Syntax error in fetch
C. No error handling for fetch failure
D. Missing async keyword
Q.92 Consider this code:
async function checkData() {
try {
let response = await fetch(‘https://api.example.com/data’);
if (!response.ok)
throw new Error(‘Error fetching data’);
let data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
What happens when fetch fails?
A. It logs ‘Error fetching data’
B. It returns ‘Error fetching data’
C. It throws an error but doesn’t catch it
D. It returns undefined
Q.93 What will the following async function output?
async function fetchData() {
let response = await fetch(‘https://api.example.com/data’); let data = await response.json(); console.log(data);
} fetchData();
A. The contents of ‘https://api.example.com/data’
B. A JavaScript object
C. An error message
D. Nothing
Q.94 How does await work inside an async function?
A. It stops the entire program until the awaited promise resolves
B. It waits for a promise to resolve before continuing the execution of the async function
C. It sends a request to the server
D. It creates a new thread for asynchronous execution
Q.95 What is the purpose of the async keyword in JavaScript?
A. To pause the execution of a function
B. To declare a function as asynchronous
C. To speed up a function
D. To handle multiple promises simultaneously
Q.96 Spot the error in this promise code:
let p = new Promise((resolve, reject) => {
resolve(‘Success’);
reject(‘Failed’);
}).then(result => console.log(result)).catch(error => console.log(error));
A. The promise should not call both resolve and reject
B. The .then() method is misplaced
C. The .catch() block is unnecessary
D. The promise does not handle asynchronous operations
Q.97 What is the output of this promise chain?
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => {
throw new Error(‘My Error’);
})
.catch(() => console.log(‘Caught’))
.then(() => console.log(‘Done’));
A. ‘Caught’ then ‘Done’
B. ‘My Error’ then ‘Done’
C. Just ‘Caught’
D. Just ‘Done’
Q.98 Consider this code:
new Promise((resolve, reject) => {
throw new Error(‘Error’);
})
.catch(error => console.log(error.message))
.then(() => console.log(‘Completed’));
What will be the output?
A. ‘Error’ then ‘Completed’
B. Just ‘Error’
C. Just ‘Completed’
D. A runtime error
Q.99 What does the following code do?
new Promise((resolve, reject) => {
setTimeout(() => resolve(‘Result’), 2000);
})
.then(result => console.log(result));
A. Executes a function after 2 seconds
B. Logs ‘Result’ immediately
C. Creates a promise that resolves with ‘Result’ after 2 seconds, then logs it
D. Repeatedly logs ‘Result’ every 2 seconds
Q.100 What happens if a promise is rejected and there is no .catch() block?
A. The error is silently ignored
B. The promise is fulfilled with an undefined value
C. A TypeError is thrown
D. An unhandled promise rejection occurs
Q.101 How does promise chaining work in JavaScript?
A. By returning a new promise from the callback of another promise
B. By executing multiple callbacks in parallel
C. By repeatedly calling the same promise
D. By automatically rejecting a promise after a set timeout
Q.102 What is a Promise in JavaScript?
A. A function that executes asynchronously
B. A callback function that executes immediately
C. An object representing the eventual completion or failure of an asynchronous operation
D. A data structure for storing multiple callbacks
Q.103 Spot the error in this callback usage:
function fetchData(callback) {
if (error) {
callback(error);
} return callback(null, data);
}
A. The callback is called twice
B. The data is returned before the callback is called
C. The error is not properly handled
D. There is no error
Q.104 What is the output of this code? function doAsyncTask(cb) { setTimeout(() => { console.log(‘Async Task Calling Callback’); cb(); }, 1000); } doAsyncTask(() => console.log(‘Callback Called’));
A. ‘Async Task Calling Callback’ then ‘Callback Called’ after 1 second
B. ‘Callback Called’ then ‘Async Task Calling Callback’ after 1 second
C. ‘Async Task Calling Callback’ and ‘Callback Called’ simultaneously
D. Nothing, it’s an infinite loop
Q.105 Consider this code:
function firstFunction(params, callback) {
// Do something, then callback()
}
function secondFunction(params) {
firstFunction(params, function(err, data) {
if (err) {
console.log(‘Error:’, err);
} else {
console.log(‘Data:’, data);
}
}); }
What pattern does this represent?
A. Callback pattern
B. Module pattern
C. Observer pattern
D. Singleton pattern
Q.106 What does the following code do?
function processData(callback) {
if (data) {
callback(null, data);
} else {
callback(new Error(‘No data’), null);
}
}
A. Throws an error if there’s no data
B. Processes data asynchronously and executes the callback function
C. Logs data to the console
D. Creates a new data object
Q.107 How can “Callback Hell” be avoided in JavaScript?
A. Using promises and async/await
B. Increasing the response time of servers
C. Writing all code in a single callback function
D. Avoiding the use of callback functions altogether
Q.108 What is “Callback Hell” in JavaScript?
A. A large number of nested callback functions that make the code hard to read and maintain
B. An error thrown by a failed callback function
C. A callback function that never gets executed
D. A standard method for handling asynchronous operations
Q.109 What is a callback function in JavaScript?
A. A function that is scheduled to run after a set interval
B. A function that calls itself
C. A function passed into another function as an argument to be executed later
D. A function that runs immediately after declaration
Q.110 Find the mistake in this ES6 code:
let obj = { a: 1, b: 2, a: 3 }; console.log(obj.a);
A. Repeated property name in object literal
B. Syntax error in object declaration
C. Error in console.log statement
D. No error
Q.111 What will this ES6 code output?
function multiply(a, b = 2) {
return a * b;
}
console.log(multiply(3));
A. 3
B. 6
C. undefined
D. NaN
Q.112 Consider the following ES6 code:
const square = x => x * x; console.log(square(4));
What is the output?
A. 4
B. 8
C. 16
D. Syntax error
Q.113 What does the following ES6 code output?
let [a, b] = [1, 2];
console.log(a);
A. 1
B. 2
C. [1, 2]
D. undefined
Q.114 How does the spread operator (…) work in ES6?
A. It divides an array into individual elements
B. It merges arrays or object properties
C. It spreads an object into multiple arrays
D. It is used for error handling
Q.115 What is the purpose of the let and const keywords in ES6?
A. To create global variables
B. To declare variables with block scope
C. To declare constants
D. Both B and C
Q.116 What ES6 feature allows us to combine multiple strings and variables?
A. String interpolation
B. Template literals
C. Concatenation
D. Variable injection
Q.117 What is an arrow function in ES6?
A. A function that points to another function
B. A shorter syntax for writing function expressions
C. A function used for one-way data binding
D. A special function for asynchronous programming
Q.118 Spot the error in this code:
try {
let obj = JSON.parse(‘{“name”:”Alice”‘);
} catch(e) {
console.log(‘Parsing error:’, e);
}
A. Missing closing brace in JSON string
B. Incorrect use of JSON.parse
C. Error in the catch block
D. No error
Q.119 What is the problem with this code?
try { // code } catch(e) { console.log(e); }
A. There’s no error to catch
B. The try block is empty
C. The catch block should have more logic
D. No error
Q.120 Find the mistake in this code:
try {
let x = 10;
if(x > 5) {
throw ‘Too high’;
}
} catch(e) {
console.log(‘Error: ‘, e);
}
A. Incorrect use of throw
B. x > 5 should be x < 5
C. Error in the catch block
D. No error
Q.121 Identify the issue in this code snippet:
localStorage.setItem(‘settings’, { theme: ‘dark’, layout: ‘grid’ });
let settings = localStorage.getItem(‘settings’);
console.log(settings.theme);
A. The object is not correctly stored as a string
B. The localStorage API is misused
C. The settings object does not have a theme property
D. No error
Q122 What will be the result of this code if localStorage already has 10 items?
for (let i = 0; i < 5; i++) {
localStorage.setItem(key${i}, value${i});
}
console.log(localStorage.length);
A. 5
B. 10
C. 15
D. Error
Q.123 Consider this web storage code:
sessionStorage.setItem(‘sessionData’, JSON.stringify({ id: 123, token: ‘abc’ }));
let data = JSON.parse(sessionStorage.getItem(‘sessionData’));
console.log(data.id);
What is the output?
A. { id: 123, token: ‘abc’ }
B. 123
C. ‘abc’
D. undefined
Q.124 What does this code do?
localStorage.setItem(‘user’, ‘Alice’);
console.log(localStorage.getItem(‘user’));
A. Retrieves a user’s details from the server
B. Saves the user ‘Alice’ in the session storage and logs it
C. Saves the user ‘Alice’ in the local storage and logs it
D. Creates a cookie named ‘user’ with the value ‘Alice’
Q.125 How can web storage be made more secure against XSS attacks?
A. By encrypting the data stored in web storage
B. By using cookies instead of web storage
C. By storing only non-sensitive data in web storage
D. By limiting the size of the data stored
Q.126 What is the main difference between localStorage and sessionStorage?
A. localStorage is larger in size than sessionStorage
B. localStorage persists data across browser sessions, while sessionStorage clears it when the session ends
C. sessionStorage is more secure than localStorage
D. localStorage can store complex data types, while sessionStorage cannot
Q.127 What are localStorage and sessionStorage in web development?
A. Server-side storage mechanisms
B. Cookie-based storage mechanisms
C. Client-side storage mechanisms that store data locally in the user’s browser
D. Database storage solutions provided by the browser
Q.128 Spot the problem in this JavaScript security code:
fetch(‘https://api.example.com/data’, {
credentials: ‘include’
})
.then(response => response.json())
.then(data => console.log(data));
A. It allows Cross-Origin Resource Sharing (CORS) without proper checks
B. It sends credentials without checking the response type
C. There’s no error handling for the fetch request
D. The data from the response is logged, which can be a security risk
Q.129 Identify the security flaw in this code snippet:
let username = document.querySelector(‘#username’).value;
if (username.length < 3) {
alert(‘Username too short’);
}
A. Potential Cross-Site Scripting vulnerability
B. Improper validation of the username length
C. Lack of encryption for the username
D. No security flaw
Q.130 What security issue does this code present, and how can it be mitigated?
let userDetails = JSON.parse(localStorage.getItem(‘userDetails’));
A. The code may execute malicious JavaScript from localStorage, which can be mitigated by validating and sanitizing the data before using it
B. The data might be outdated, leading to performance issues
C. The code can be blocked by browser security settings
D. The code exposes user details in the global scope
Q.131 How can the following JavaScript code be a security risk?
document.write(userInput);
A. It can lead to XSS if userInput is not properly sanitized
B. It may slow down the website
C. It can overwrite important data
D. It can make the site non-responsive
Q.132 What is Content Security Policy (CSP) and how does it help in web security?
A. A policy that restricts the types of content that can be loaded on a webpage to prevent XSS attacks
B. A server configuration that encrypts all data leaving a website
C. A JavaScript function that validates user input on a webpage
D. A protocol for secure communication between a website and its database
Q.133 What is Cross-Site Scripting (XSS) in the context of web security?
A. Stealing cookies and session tokens
B. Injecting malicious scripts into webpages viewed by other users
C. Breaking into databases through the web interface
D. Disabling websites with Denial of Service attacks
Q.134 Spot the error in this class inheritance:
class Animal { constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name, lives) {
super();
this.lives = lives;
}
}
A. Missing name argument in the super call
B. Cat should not have additional properties
C. Syntax error in extending the class
D. No error
Q.135 Identify the mistake in this class definition:
class Person {
constructor(name) {
name = name;
}
}
A. The constructor doesn’t properly set the property
B. The class should also have methods
C. Syntax error in class definition
D. No error
Q.136 What will the following inheritance code output?
class Animal {
speak() {
return ‘I am an animal’;
}
}
class Dog extends Animal {
speak() {
return super.speak() + ‘, but more specifically a dog’;
}
}
let dog = new Dog();
console.log(dog.speak());
A. ‘I am an animal’
B. ‘I am an animal, but more specifically a dog’
C. ‘I am a dog’
D. Syntax error
Q.137 Consider this code:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
} let rect = new Rectangle(5, 10);
console.log(rect.area);
What is the output?
A. 15
B. 50
C. ‘5×10’
D. Syntax error
Q.138 What does this ES6 class syntax do?
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(${this.name} makes a noise.);
}
}
A. Defines an Animal class with methods for each animal
B. Creates an instance of the Animal class
C. Defines an Animal class with a constructor and a speak method
D. Declares a global function named Animal
Q.139 What is polymorphism in the context of object-oriented programming?
A. The ability to create multiple instances of a class
B. The ability of different classes to be treated as instances of the same class
C. The process of a function taking multiple forms
D. The ability of a class to inherit from multiple classes
Q.140 What are the benefits of using ES6 classes over constructor functions?
A. ES6 classes are more performant
B. ES6 classes offer private methods and properties
C. ES6 classes provide a clearer, more concise syntax
D. Constructor functions do not allow inheritance
Q.141 How does inheritance work in JavaScript?
A. Through classes and the extend keyword
B. Through the prototype chain
C. Through the use of constructor functions
D. Through global variables
Q.142 In JavaScript, what is a prototype?
A. A blueprint for creating objects
B. A function that creates an object
C. An instance of a class
D. The object from which a function or object inherits properties
Q.143 What is encapsulation in object-oriented programming?
A. The bundling of data and methods that operate on that data
B. Creating private variables within a class
C. The ability of an object to take on many forms
D. A design pattern that ensures only one instance of a class is created
Q.144 Spot the error in this currying implementation:
function sum(a, b, c) {
return a + b + c;
}
let curriedSum = (a) => (b) => (c) => sum(a, b);
console.log(curriedSum(1)(2)(3));
A. Missing argument in the final function call
B. Incorrect return value in curriedSum
C. sum function is not needed
D. Syntax error
Q.145 Identify the issue in this partially applied function:
function log(date, importance, message) { console.log([${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}); } let logNow = log.bind(null, new Date()); logNow(‘INFO’, ‘Server started’);
A. Incorrect use of bind
B. Date is not updated correctly
C. Incorrect number of arguments provided
D. No error
Q.146 Consider this code:
function add(a) {
return function(b) {
return function(c) {
return a + b + c; };
};
} let addFive = add(2)(3);
console.log(addFive(5));
What is the output?
A. 10
B. Syntax error
C. Undefined
D. 15
Q.147 What will the following curried function output?
function multiply(a) {
return function(b) {
return a * b;
};
}
let multiplyByTwo = multiply(2);
console.log(multiplyByTwo(3));
A. 5
B. 6
C. 8
D. Syntax error
Q.148 How is partial application different from currying?
A. Partial application is about fixing some arguments to a function, while currying is about breaking down a function into a series of functions that each take a single argument
B. Partial application is a technique for performance optimization, while currying is for error handling
C. Partial application deals with asynchronous functions, while currying deals with synchronous ones
D. There is no difference
Q.149 What is currying in JavaScript?
A. The process of breaking down a function into a series of functions that each take a single argument
B. Transforming a function to manage its state
C. A way of writing asynchronous code
D. Optimizing functions for performance
Q.150 What is the problem with this async function?
async function getUser() {
let user = await fetch(‘/user’);
if (user.id === 123) {
return ‘Admin’;
}
}
A. The function may return undefined
B. user.id is always undefined
C. The fetch request is incorrect
D. There is no error handling for the fetch