Chapter 4 Beginner 57 Questions

Practice Questions — Operators and Expressions

← Back to Notes
8 Easy
13 Medium
11 Hard

Topic-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.
15
5
50
3.3333333333333335
Question 2
Easy
What is the output?
console.log(10 % 3);
console.log(15 % 5);
console.log(7 % 2);
% returns the remainder after division.
1
0
1
Question 3
Easy
What is the output?
console.log(5 == "5");
console.log(5 === "5");
== converts types, === does not.
true
false
Question 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.
true
false
true
false
Question 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.
Priya
0
Guest
Rohan
Question 6
Medium
What is the output?
let age = 15;
let result = age >= 18 ? "adult" : "minor";
console.log(result);
condition ? valueIfTrue : valueIfFalse
minor
Question 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.
10
0
Question 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.
Neha
undefined
No phone
Question 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.
5
6
7
7
Question 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.
true
false
true
false
false
Question 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]'.
3
truehello
[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 intentionally
What 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.
14
20
512
false
Question 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 odd
Question 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.
1
2
false
true
Question 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.
27
Question 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: Fail
Question 18
Hard
What is the output?
console.log(false || 0 || "" || null || undefined || "found it" || true);
|| keeps going until it finds a truthy value.
found it
Question 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.
B
Question 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.
a
c
0

Mixed & 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).
8
9
1
Question 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: true
Question 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.
true
false
false
Question 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.
false
true
false
false
false
true
Question 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.
default
default
0
(empty string)
false
Question 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.
true
false
Question 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
$53
Question 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.
11
16
Question 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?
boolean
boolean
boolean

Multiple Choice Questions

MCQ 1
What is the output of: 5 === '5'?
  • A. true
  • B. false
  • C. NaN
  • D. Error
Answer: B
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?
  • A. The quotient
  • B. The percentage
  • C. The remainder after division
  • D. The decimal part
Answer: C
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?
  • A. =
  • B. ==
  • C. ===
  • D. ===
Answer: C
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)?
  • A. true
  • B. false
  • C. 0
  • D. NaN
Answer: B
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'?
  • A. ''
  • B. Guest
  • C. true
  • D. false
Answer: B
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'?
  • A. 0
  • B. default
  • C. null
  • D. false
Answer: A
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?
  • A. Loops three times
  • B. Takes three operands and returns one based on a condition
  • C. Divides a number by 3
  • D. Creates three variables
Answer: B
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'?
  • A. true
  • B. Aarav
  • C. Priya
  • D. false
Answer: C
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?
  • A. 0
  • B. null
  • C. "0"
  • D. NaN
Answer: C
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?
  • A. true
  • B. false
  • C. Error
  • D. 1
Answer: B
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 ???
  • A. No difference, they are the same
  • B. || checks for falsy values, ?? checks only for null/undefined
  • C. ?? checks for falsy values, || checks only for null/undefined
  • D. || is for numbers, ?? is for strings
Answer: B
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'?
  • A. false
  • B. 0
  • C. null
  • D. found
Answer: D
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)?
  • A. number
  • B. boolean
  • C. string
  • D. true
Answer: B
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?
  • A. 5
  • B. 10
  • C. 15
  • D. 50
Answer: C
C is correct. x += 5 is shorthand for x = x + 5. 10 + 5 = 15.
MCQ 15
What is the output of: null == undefined?
  • A. true
  • B. false
  • C. null
  • D. Error
Answer: A
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

Easy
Write 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

Easy
Create 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

Medium
Build 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

Medium
Write 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

Hard
Build 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

Hard
Write 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 Notes

Want to learn web development with a live mentor?

Explore our Frontend Masterclass