Practice Questions — Operators and Expressions
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
console.log(10 + 5);
console.log(10 - 5);
console.log(10 * 5);
console.log(10 / 3);Basic arithmetic. Division returns a decimal.
155503.3333333333333335Question 2
Easy
What is the output?
console.log(10 % 3);
console.log(15 % 5);
console.log(7 % 2);% returns the remainder after division.
101Question 3
Easy
What is the output?
console.log(5 == "5");
console.log(5 === "5");== converts types, === does not.
truefalseQuestion 4
Medium
What is the output?
console.log(0 == false);
console.log(0 === false);
console.log("" == false);
console.log("" === false);== converts types. false becomes 0, '' becomes 0.
truefalsetruefalseQuestion 5
Medium
What is the output?
console.log("Aarav" && "Priya");
console.log(0 && "Priya");
console.log("" || "Guest");
console.log("Rohan" || "Guest");&& returns first falsy or last value. || returns first truthy or last value.
Priya0GuestRohanQuestion 6
Medium
What is the output?
let age = 15;
let result = age >= 18 ? "adult" : "minor";
console.log(result);condition ? valueIfTrue : valueIfFalse
minorQuestion 7
Medium
What is the output?
let count = 0;
console.log(count || 10);
console.log(count ?? 10);|| checks for falsy. ?? checks only for null/undefined.
100Question 8
Medium
What is the output?
let user = { name: "Neha" };
console.log(user.name);
console.log(user.address?.city);
console.log(user.phone?.number ?? "No phone");?. returns undefined if the property does not exist. ?? provides a fallback.
NehaundefinedNo phoneQuestion 9
Hard
What is the output?
let x = 5;
console.log(x++);
console.log(x);
console.log(++x);
console.log(x);x++ returns old value then increments. ++x increments then returns new value.
5677Question 10
Hard
What is the output?
console.log("0" == false);
console.log("0" == "");
console.log(false == "");
console.log(null == 0);
console.log(undefined == 0);== is inconsistent. null only equals undefined with ==, not 0.
truefalsetruefalsefalseQuestion 11
Hard
What is the output?
console.log(true + true + true);
console.log(true + "hello");
console.log([] + {});
console.log({} + []);true is 1 in numeric context. [] becomes '' as a string. {} is '[object Object]'.
3truehello[object Object][object Object]Question 12
Medium
Vikram wrote a function to greet users but it greets everyone as 'Guest' even when they provide a name. Find the bug:
function greet(name) {
let displayName = name || "Guest";
console.log(`Hello, ${displayName}!`);
}
greet(""); // User cleared their name intentionallyWhat happens when name is an empty string with ||?
Use
?? instead of ||: let displayName = name ?? "Guest";Question 13
Hard
What is the output?
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(2 ** 3 ** 2);
console.log(!true || false && true);PEMDAS for math. Precedence: ! > && > || for logical.
1420512falseQuestion 14
Easy
Write code that checks if a number is even or odd using the % operator. Test with the number 17.
A number is even if n % 2 === 0.
let n = 17;
let result = n % 2 === 0 ? "even" : "odd";
console.log(`${n} is ${result}`);
Output: 17 is oddQuestion 15
Hard
What is the output?
let a = 1;
let b = 2;
console.log(a || b);
console.log(a && b);
console.log(!a);
console.log(!!a);|| returns first truthy value. && returns first falsy or last value. ! converts to boolean.
12falsetrueQuestion 16
Easy
What is the output?
let x = 10;
x += 5;
x *= 2;
x -= 3;
console.log(x);Trace each step: 10, then +5, then *2, then -3.
27Question 17
Medium
Write a one-liner using the ternary operator that assigns 'Pass' to a variable if marks >= 40, otherwise 'Fail'. Test with marks = 35.
Use condition ? 'Pass' : 'Fail'.
let marks = 35;
let result = marks >= 40 ? "Pass" : "Fail";
console.log(`Marks: ${marks}, Result: ${result}`);
Output: Marks: 35, Result: FailQuestion 18
Hard
What is the output?
console.log(false || 0 || "" || null || undefined || "found it" || true);|| keeps going until it finds a truthy value.
found itQuestion 19
Medium
What is the output?
let score = 85;
let grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F";
console.log(grade);Nested ternaries evaluate from left to right.
BQuestion 20
Hard
What is the output?
console.log(null ?? "a" ?? "b");
console.log(undefined ?? null ?? "c");
console.log(0 ?? null ?? "d");?? returns the right side only for null/undefined.
ac0Mixed & Application Questions
Question 1
Easy
What is the output?
console.log(2 ** 3);
console.log(3 ** 2);
console.log(10 ** 0);** is the exponentiation operator (power).
891Question 2
Easy
Write code that checks if a variable
age (set to 16) is between 13 and 19 inclusive using comparison operators. Log: 'Is teenager: true'.Use >= and <= with &&.
let age = 16;
let isTeen = age >= 13 && age <= 19;
console.log(`Is teenager: ${isTeen}`);
Output: Is teenager: trueQuestion 3
Medium
What is the output?
let x = 5;
console.log(x > 3 && x < 10);
console.log(x > 10 || x < 3);
console.log(!(x === 5));Evaluate each comparison first, then apply logical operators.
truefalsefalseQuestion 4
Medium
What is the output?
console.log(!!"");
console.log(!!"hello");
console.log(!!0);
console.log(!!null);
console.log(!!undefined);
console.log(!!"0");!! converts any value to its boolean equivalent.
falsetruefalsefalsefalsetrueQuestion 5
Medium
Write an HTML page with a number input. When a button is clicked, display whether the number is positive, negative, or zero, AND whether it is even or odd — all using ternary operators.
Use two ternary operators: one for sign, one for even/odd.
<input type="number" id="num">
<button onclick="check()">Check</button>
<p id="result"></p>
<script>
function check() {
let n = Number(document.getElementById("num").value);
let sign = n > 0 ? "positive" : n < 0 ? "negative" : "zero";
let parity = n % 2 === 0 ? "even" : "odd";
document.getElementById("result").textContent = `${n} is ${sign} and ${parity}`;
}
</script>Question 6
Hard
What is the output?
let a = null;
let b = undefined;
let c = 0;
let d = "";
let e = false;
console.log(a ?? "default");
console.log(b ?? "default");
console.log(c ?? "default");
console.log(d ?? "default");
console.log(e ?? "default");?? only triggers on null and undefined. 0, '', and false are kept.
defaultdefault0 (empty string)falseQuestion 7
Medium
Ananya's calculator adds numbers from two inputs but keeps concatenating instead of adding:
<input id="a" value="5"> <input id="b" value="3">
<button onclick="add()">Add</button>
<script>
function add() {
let result = document.getElementById('a').value + document.getElementById('b').value;
alert(result); // Shows '53' instead of 8
}
</script>Input .value always returns a string.
Convert inputs to numbers:
let result = Number(document.getElementById('a').value) + Number(document.getElementById('b').value);Question 8
Hard
What is the output?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);JavaScript does NOT chain comparisons like Python. It evaluates left to right.
truefalseQuestion 9
Hard
Write code that safely accesses deeply nested data. Given an API response object, access the first user's email and provide 'No email' as a default.
Use optional chaining (?.) and nullish coalescing (??).
let response = {
data: {
users: [
{ name: "Priya", contact: { email: "priya@example.com" } }
]
}
};
// Safe access with ?. and ??
let email = response?.data?.users?.[0]?.contact?.email ?? "No email";
console.log(email); // "priya@example.com"
// Test with missing data
let emptyResponse = {};
let email2 = emptyResponse?.data?.users?.[0]?.contact?.email ?? "No email";
console.log(email2); // "No email"Question 10
Easy
What is the output?
console.log(5 + 3 + "px");
console.log("$" + 5 + 3);JavaScript evaluates left to right. The + behavior changes when it encounters a string.
8px$53Question 11
Hard
What is the output?
let x = 10;
let y = (x++, x + 5);
console.log(x);
console.log(y);The comma operator evaluates both expressions and returns the last one.
1116Question 12
Medium
What is the output?
console.log(typeof (10 > 5));
console.log(typeof (5 === 5));
console.log(typeof !true);What type do comparison and logical operators return?
booleanbooleanbooleanMultiple Choice Questions
MCQ 1
What is the output of: 5 === '5'?
Answer: B
B is correct.
B is correct.
=== (strict equality) checks both value AND type. 5 is a number and '5' is a string. Since the types differ, the result is false.MCQ 2
What does the % operator return?
Answer: C
C is correct.
C is correct.
% is the remainder (modulo) operator. 10 % 3 returns 1 because 10 divided by 3 is 3 with a remainder of 1.MCQ 3
Which operator should you use for comparisons in JavaScript?
Answer: C
C is correct.
C is correct.
=== (strict equality) is the recommended comparison operator. = is assignment. == performs type coercion which leads to bugs.MCQ 4
What is the output of: Boolean(0)?
Answer: B
B is correct.
B is correct.
0 is one of the six falsy values in JavaScript. Boolean(0) returns false.MCQ 5
What is the output of: '' || 'Guest'?
Answer: B
B is correct.
B is correct.
|| returns the first truthy value. Empty string '' is falsy, so || moves to the next value and returns 'Guest'.MCQ 6
What is the output of: 0 ?? 'default'?
Answer: A
A is correct.
A is correct.
?? only returns the right side for null or undefined. 0 is neither, so it is returned as-is.MCQ 7
What does the ternary operator do?
Answer: B
B is correct. The ternary operator
B is correct. The ternary operator
condition ? a : b evaluates the condition. If true, it returns a. If false, it returns b. It takes three operands: the condition, the true value, and the false value.MCQ 8
What is the output of: 'Aarav' && 'Priya'?
Answer: C
C is correct.
C is correct.
&& returns the first falsy value, or the last value if all are truthy. Both strings are truthy, so it returns the last one: 'Priya'.MCQ 9
Which of these is a truthy value?
Answer: C
C is correct. The string
C is correct. The string
"0" is a non-empty string, which is truthy. 0, null, and NaN are all falsy.MCQ 10
What is the output of: 3 > 2 > 1?
Answer: B
B is correct. JavaScript evaluates left to right:
B is correct. JavaScript evaluates left to right:
3 > 2 is true. Then true > 1 converts true to 1, and 1 > 1 is false. JavaScript does not chain comparisons like Python.MCQ 11
What is the difference between || and ???
Answer: B
B is correct.
B is correct.
|| returns the right side for ANY falsy value (0, '', null, undefined, NaN, false). ?? returns the right side ONLY for null or undefined. Use ?? when 0 or '' are valid values.MCQ 12
What is the output of: false || 0 || '' || null || 'found'?
Answer: D
D is correct.
D is correct.
|| checks each value left to right: false (falsy), 0 (falsy), '' (falsy), null (falsy), 'found' (truthy — returns it). The first truthy value encountered is 'found'.MCQ 13
What is the output of: typeof (5 > 3)?
Answer: B
B is correct.
B is correct.
5 > 3 evaluates to true. typeof true returns "boolean". Comparison operators always return boolean values.MCQ 14
What is x after: let x = 10; x += 5?
Answer: C
C is correct.
C is correct.
x += 5 is shorthand for x = x + 5. 10 + 5 = 15.MCQ 15
What is the output of: null == undefined?
Answer: A
A is correct. With
A is correct. With
==, null and undefined are considered equal to each other (and only to each other). This is a special rule in the == algorithm. Note: null === undefined would be false.Coding Challenges
Challenge 1: Comparison Table Builder
EasyWrite code that compares the number 5 with the string '5' using both == and ===. Display the results on a web page in a clear format.
Sample Input
(No input required)
Sample Output
5 == '5': true
5 === '5': false
Show both results on the page.
<!DOCTYPE html>
<html>
<body>
<pre id="output"></pre>
<script>
let result = `5 == '5': ${5 == '5'}\n5 === '5': ${5 === '5'}\n\n0 == false: ${0 == false}\n0 === false: ${0 === false}\n\n'' == false: ${'' == false}\n'' === false: ${'' === false}`;
document.getElementById('output').textContent = result;
</script>
</body>
</html>Challenge 2: Smart Default Values
EasyCreate a function that takes a name and an age. If name is not provided, default to 'Guest'. If age is not provided, default to 0. Use ?? for defaults so that empty string names and age 0 are preserved.
Sample Input
greet('', 0)
Sample Output
Hello, ! You are 0 years old.
Use ?? instead of ||.
function greet(name, age) {
let displayName = name ?? 'Guest';
let displayAge = age ?? 0;
console.log(`Hello, ${displayName}! You are ${displayAge} years old.`);
}
greet('Aarav', 15); // Hello, Aarav! You are 15 years old.
greet('', 0); // Hello, ! You are 0 years old.
greet(null, null); // Hello, Guest! You are 0 years old.
greet(undefined); // Hello, Guest! You are 0 years old.Challenge 3: Grade Calculator with Ternary
MediumBuild an HTML page where the user enters marks (0-100) and clicks a button. Use nested ternary operators to determine the grade (A: 90+, B: 80+, C: 70+, D: 60+, F: below 60). Display the grade with a different color for each.
Sample Input
User enters 85
Sample Output
Grade: B (displayed in blue)
Use ternary operators, not if-else. Use different colors for each grade.
<!DOCTYPE html>
<html>
<body>
<input type="number" id="marks" placeholder="Enter marks (0-100)">
<button onclick="calc()">Get Grade</button>
<p id="result"></p>
<script>
function calc() {
let marks = Number(document.getElementById('marks').value);
let grade = marks >= 90 ? 'A' : marks >= 80 ? 'B' : marks >= 70 ? 'C' : marks >= 60 ? 'D' : 'F';
let color = grade === 'A' ? 'green' : grade === 'B' ? 'blue' : grade === 'C' ? 'orange' : 'red';
let el = document.getElementById('result');
el.textContent = `Marks: ${marks}, Grade: ${grade}`;
el.style.color = color;
}
</script>
</body>
</html>Challenge 4: Short-Circuit Pattern Demo
MediumWrite code demonstrating three practical uses of short-circuit evaluation: (1) default values with ||, (2) conditional execution with &&, (3) safe property access before optional chaining existed. Log the results.
Sample Input
(No input required)
Sample Output
Name: Guest
Dashboard shown
City: Unknown
Show each pattern clearly with comments.
// Pattern 1: Default values with ||
let userInput = '';
let name = userInput || 'Guest';
console.log('Name:', name);
// Pattern 2: Conditional execution with &&
let isLoggedIn = true;
isLoggedIn && console.log('Dashboard shown');
// Pattern 3: Safe access (old way, before ?.)
let user = { profile: null };
let city = user && user.profile && user.profile.city || 'Unknown';
console.log('City:', city);
// Modern way with ?. and ??
let city2 = user?.profile?.city ?? 'Unknown';
console.log('City (modern):', city2);Challenge 5: Truthy/Falsy Visual Tester
HardBuild an HTML page with an input field. As the user types (oninput event), show in real-time: the raw value, typeof, Boolean conversion (truthy/falsy), Number conversion, and highlight the box green for truthy or red for falsy.
Sample Input
User types '0'
Sample Output
Value: '0' | typeof: string | Boolean: true (truthy) | Number: 0 [green border]
Update in real time using oninput event.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="val" oninput="test()" placeholder="Type any value..." style="padding:10px;font-size:16px;border:3px solid #ccc;">
<pre id="output" style="font-size:16px;"></pre>
<script>
function test() {
let val = document.getElementById('val').value;
let boolVal = Boolean(val);
let numVal = Number(val);
let input = document.getElementById('val');
input.style.borderColor = boolVal ? 'green' : 'red';
document.getElementById('output').textContent =
`Value: '${val}'\ntypeof: ${typeof val}\nBoolean: ${boolVal} (${boolVal ? 'truthy' : 'falsy'})\nNumber: ${numVal}\n\nNote: Only empty string is falsy for strings.\n'0', ' ', and 'false' are all truthy strings!`;
}
test();
</script>
</body>
</html>Challenge 6: Operator Precedence Challenge
HardWrite 5 complex expressions that test operator precedence knowledge. For each, show the expression, the step-by-step evaluation (as comments), and the final result. Include at least one with **, one with mixed && and ||, and one with ternary.
Sample Input
(No input required)
Sample Output
Step-by-step evaluation of 5 expressions with final results.
Show detailed step-by-step comments for each expression.
// Expression 1: Math precedence
// 2 + 3 * 4 ** 2 - 1
// Step: 4**2=16, 3*16=48, 2+48-1=49
console.log(2 + 3 * 4 ** 2 - 1); // 49
// Expression 2: Logical precedence
// true || false && false
// Step: && first: false && false = false, then true || false = true
console.log(true || false && false); // true
// Expression 3: Mixed comparison and logical
// 5 > 3 && 10 < 20 || false
// Step: 5>3=true, 10<20=true, true&&true=true, true||false=true
console.log(5 > 3 && 10 < 20 || false); // true
// Expression 4: Ternary with comparison
// 10 > 5 ? 'yes' : 'no' + ' way'
// Step: 10>5=true, returns 'yes' (+ is inside the false branch)
console.log(10 > 5 ? 'yes' : 'no' + ' way'); // 'yes'
// Expression 5: Nullish with logical
// null ?? 'a' || 'b'
// Step: null??'a' = 'a', 'a'||'b' = 'a'
console.log(null ?? 'a' || 'b'); // 'a'Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn web development with a live mentor?
Explore our Frontend Masterclass