LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 4 of 25

Operators Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Operators · Study material

Operators are where JavaScript's type conversion shows up most, which is why they fill so many output questions: "6" + 2 is "62" but "6" - 2 is 4, null >= 0 is true while null == 0 is false, && and || return one of their operands rather than true or false, and 3 > 2 > 1 is false. This topic covers every operator family with the rules behind those results, including the modern ??, ?. and logical assignment operators. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

Arithmetic operators

+ - * / % (remainder) and ** (exponent, ES2016). Division always gives a decimal result when needed – there is no integer division. The sign of % follows the left operand. + is special: if either operand is a string, it concatenates; the other arithmetic operators convert strings to numbers.

console.log(7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 % 2, 2 ** 10);
console.log(-7 % 3, 7 % -3);           // the sign of % follows the left operand
// Only + joins strings; - * / % convert strings to numbers
console.log("6" * "2", "6" - 2, "6" + 2);

Output

9 5 14 3.5 1 1024
-1 1
12 4 62

Increment, decrement and assignment

x++ (postfix) returns the old value and then increments; ++x (prefix) increments first and returns the new value. Compound assignment operators – +=, -=, *=, /=, %=, **= and the bitwise ones – combine an operation with assignment.

let a = 5;
const b = a++;    // postfix: use the old value (5), then increment → a is 6
const c = ++a;    // prefix: increment first (a is 7), then use it
console.log(a, b, c);

let x = 1;
x += 2;   // 3
x *= 3;   // 9
x **= 2;  // 81
x %= 7;   // 4
console.log(x);

Output

7 5 7
4

== vs ===

=== (strict equality) is true only when both type and value match. == (loose equality) converts the operands first: null and undefined equal each other and nothing else; a boolean is converted to a number; a string compared with a number is converted to a number; an object is converted to a primitive. NaN is never equal to anything. Because the rules are surprising, use === – except for x == null, a common shorthand for "null or undefined".

Relational operators (<, >= …) follow different rules: they convert null to 0, which is why null >= 0 is true while null == 0 is false.

console.log(5 == "5", 5 === "5");                 // == converts types, === does not
console.log(0 == "", 0 == "0", "" == "0");        // == is not even transitive
console.log(null == undefined, null == 0, null >= 0);
console.log(NaN == NaN, [1] == 1, true == "1");

Output

true false
true true false
true false true
false true true

Logical operators return operands

a && b returns a if it is falsy, otherwise b. a || b returns a if it is truthy, otherwise b. Both short-circuit: the right side is not evaluated when the left side decides the result. ! always returns a boolean.

// && returns the first falsy operand (or the last one); || returns the first truthy operand (or the last one)
console.log("Asha" && 42, 0 && "never", "" || "guest", null || 0 || "last");
// ! always returns a boolean; !! converts any value to a boolean
console.log(!"text", !!"text", !0);

Output

42 0 guest last
false true true

Nullish coalescing (??) and optional chaining (?.)

a ?? b returns b only when a is null or undefined – unlike ||, it keeps valid falsy values such as 0 and "". obj?.prop, obj?.[key] and fn?.() return undefined instead of throwing when the value before ?. is null or undefined. ?? cannot be mixed with || or && without parentheses.

const settings = { volume: 0, theme: "", user: { name: "Asha" } };

// || treats 0 and "" as missing; ?? only treats null and undefined as missing
console.log(settings.volume || 50, settings.volume ?? 50);
console.log(settings.theme || "light", JSON.stringify(settings.theme ?? "light"));

// ?. stops and returns undefined instead of throwing when the left side is null/undefined
console.log(settings.user?.name, settings.profile?.name, settings.getData?.());

Output

50 0
light ""
Asha undefined undefined

Logical assignment

ES2021 added a ||= b (assign if a is falsy), a &&= b (assign if a is truthy) and a ??= b (assign if a is null or undefined). They are ideal for defaults.

const config = { retries: 0, timeout: null, debug: true };
config.retries ||= 3;        // assigns when the value is falsy (0 is falsy)
config.timeout ??= 5000;     // assigns when the value is null/undefined
config.debug &&= "verbose";  // assigns when the value is truthy
console.log(config);

Output

{ retries: 3, timeout: 5000, debug: 'verbose' }

Precedence and comparison

** binds tighter than * and /, which bind tighter than + and -; comparisons come next, then equality, then &&, || / ??, the ternary ? : and assignment. ** is right-associative. Strings are compared character by character by code unit, so "10" < "9" and uppercase letters sort before lowercase. Chained comparisons such as 1 < x < 10 do not test a range.

console.log(2 + 3 * 4, (2 + 3) * 4, 2 ** 3 ** 2);   // ** is right-associative: 2 ** 9
// Strings compare character by character (by UTF-16 code), numbers numerically
console.log("apple" < "banana", "Zebra" < "apple", "10" < "9", 10 < "9");
// Comparisons are evaluated left to right and produce booleans
console.log(1 < 2 < 3, 3 > 2 > 1);

Output

14 20 512
true true true false
true false

typeof, in, instanceof and delete

typeof returns a type name; "key" in obj checks own and inherited properties (use Object.hasOwn for own only); obj instanceof C checks whether C.prototype is in the object's prototype chain; delete obj.key removes a property (on arrays it leaves a hole).

const car = { brand: "Tata", year: 2024 };
console.log("brand" in car, "toString" in car, Object.hasOwn(car, "toString"));   // in also sees inherited keys
delete car.year;                                                                   // removes the property
console.log(car, [] instanceof Array, [] instanceof Object);

Output

true true false
{ brand: 'Tata' } true true

Common mistakes

  • Adding form values with + – strings concatenate; convert with Number() first.
  • Using || for defaults – it replaces valid 0, "" and false; use ??.
  • Writing 10 < x < 30 – use x > 10 && x < 30.
  • x === NaN – always false; use Number.isNaN(x).
  • Forgetting precedence – a + b + c / 3 divides only c.
  • -2 ** 2 – a SyntaxError; write (-2) ** 2 or -(2 ** 2).
  • Using == with mixed types – prefer ===.

Key points to remember

  • + concatenates if either operand is a string; - * / % convert to numbers.
  • x++ returns the old value, ++x the new one.
  • === compares without conversion; null == undefined is true and equals nothing else.
  • && and || return an operand and short-circuit.
  • ?? replaces only null and undefined; ?. returns undefined instead of throwing.
  • ** is right-associative and needs parentheses around a negative base.
  • in includes inherited properties; delete on arrays leaves holes.

Frequently asked questions

Should I ever use ==?

Most style guides allow one case: value == null, which is true for both null and undefined. Everywhere else, === avoids conversion surprises.

What is the difference between ?? and ||?

|| falls back for any falsy value (0, "", false, NaN, null, undefined); ?? falls back only for null and undefined. Use ?? when 0 or an empty string is a valid value.

Are bitwise operators used in real code?

Occasionally: flags and permissions, fast integer tricks, hashing and graphics. They convert operands to 32-bit integers, so they are unsafe for large numbers.

Where can I learn more?

Read JavaScript Operators and Type Coercion in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links