JavaScript Comparison Operators: <, >, String Ordering, in and instanceof
How <, >, <= and >= compare numbers, strings, dates and mixed types, why "10" < "9" is true and null >= 0 is true while null == 0 is false, locale-aware sorting with localeCompare and Intl.Collator, the in operator vs Object.hasOwn, #private in obj, and how instanceof really works.
kvi5hnuCode Sprout team member8 min readOn this page
Comparison operators return true or false, and they drive every if, while, filter and sort you write. The equality operators === and == got their own articles (21 and 23). This one covers the rest of the relational operators:
<,>,<=,>=test order: numeric or alphabetical.intests whether an object has a property.instanceoftests whether an object was created by a class or constructor.
How <, >, <= and >= work
The four ordering operators can only compare numbers or strings in the end, so they convert everything else first:

- Objects are converted to primitives with the "number" hint (article 24): a
Datebecomes its timestamp, an array becomes a string. - If both values are now strings, they're compared as strings.
- Otherwise both are converted to numbers and compared numerically. If either becomes
NaN, the result isfalse.
console.log(3 < 10, "3" < "10", "3" < 10);
console.log("10" < "9", "10" < 9);
console.log("abc" < 5, "abc" >= 5);
console.log([2] > 1, 1n < 2, 2n > 1.5);
true false true
true false
false false
true true true
"3" < "10"isfalsebecause both are strings, and the character"3"comes after"1". One number in the pair ("3" < 10) switches to numeric comparison."abc"converts toNaN, so both"abc" < 5and"abc" >= 5arefalse. WithNaN, a value can be neither smaller, nor equal, nor larger.- BigInt and number compare exactly by mathematical value.
This is a classic source of bugs when numbers arrive as strings, from form fields, URL parameters, CSV files or JSON that quotes numbers. Two strings "10" and "9" compare alphabetically. Convert first: Number(a) < Number(b).
null, undefined and the <= surprise
null converts to 0 for comparisons, undefined converts to NaN. But == has its own special rule for them (article 23), so the operators disagree:
console.log(null >= 0, null <= 0, null == 0, null > 0);
console.log(undefined < 1, undefined >= 0, undefined == 0);
true true false false
false false false
null >= 0 is true and null <= 0 is true, yet null == 0 is false. That's because >= is defined as "not less than", which converts null to 0, while == never converts null to a number. Avoid comparing values that may be null or undefined; check for them first.
Comparing strings
Two strings are compared one UTF-16 code unit at a time, left to right (article 14). At the first difference, the one with the smaller code unit is smaller. If one string runs out first, the shorter one is smaller ("app" < "apple").
Comparing code units is not dictionary order:
console.log("apple" < "banana", "Zebra" < "apple", "a" < "B");
console.log("é" > "f");
console.log(["banana", "apple", "Cherry"].sort());
true true false
true
[ 'Cherry', 'apple', 'banana' ]
All uppercase ASCII letters (codes 65–90) come before all lowercase ones (97–122), and accented letters like é (233) come after z. The default sort() uses this same order (article 22 showed it also sorts numbers as strings).
Human-friendly order: localeCompare and Intl.Collator
For text people will read, compare with the language's rules:
console.log("é".localeCompare("f", "en")); // negative: é sorts before f
const words = ["banana", "apple", "Cherry"];
console.log(words.toSorted((a, b) => a.localeCompare(b, "en")));
const files = ["item10", "item9", "item1"];
const natural = new Intl.Collator("en", { numeric: true });
console.log(files.toSorted(natural.compare)); // numbers inside text sort by value
const loose = new Intl.Collator("en", { sensitivity: "base" });
console.log(loose.compare("resume", "Résumé")); // 0: equal, ignoring case and accents
-1
[ 'apple', 'banana', 'Cherry' ]
[ 'item1', 'item9', 'item10' ]
0
a.localeCompare(b, locale)returns a negative number, 0, or a positive number, which is exactly whatsortexpects.Intl.Collatordoes the same and is faster when you compare many strings, since the rules are prepared once. Itsnumericoption gives "natural" sorting, andsensitivity: "base"makes comparisons ignore case and accents.- Order differs between languages (Swedish puts
äafterz; German puts it witha), so pass the user's locale when you know it. Part 11 coversIntlin depth.
Comparing dates
Date objects convert to their timestamp (milliseconds) with the number hint, so < and > work. Equality doesn't, because == and === compare object identity:
const start = new Date(2026, 0, 1);
const end = new Date(2026, 5, 1);
console.log(start < end);
const a = new Date(0), b = new Date(0);
console.log(a == b, a === b); // two different objects
console.log(a.getTime() === b.getTime(), +a === +b);
true
false false
true true
Compare getTime() values for equality. Temporal, the modern date API (ES2027), has explicit compare and equals methods instead (part 11).
The in operator
key in object is true if the object has a property with that name, either its own or inherited through the prototype chain:
const settings = { theme: "dark", fontSize: undefined };
console.log("theme" in settings, "fontSize" in settings, "color" in settings);
console.log("toString" in settings); // inherited from Object.prototype
console.log(Object.hasOwn(settings, "toString")); // own properties only
const letters = ["a", "b"];
console.log(0 in letters, "1" in letters, 2 in letters, "length" in letters);
true true false
true
false
true true false true
Notice the difference between in and simply reading the property. "fontSize" in settings is true even though its value is undefined. Use in (or Object.hasOwn) when "missing" and "present but undefined" mean different things, and also when a property's value is falsy: if (inventory.stock) is false for a stock of 0.
Object.hasOwn(obj, key) (ES2022) checks own properties only. It's the modern replacement for obj.hasOwnProperty(key), which breaks for objects without a prototype or with their own hasOwnProperty property.
The right operand must be an object. Using in with a primitive throws:
try {
"a" in "abc";
} catch (err) {
console.log(err.name);
}
console.log("abc".includes("a"));
TypeError
true
For strings, use string methods such as includes instead.
Checking for private fields: #field in obj
Classes can use in with a private field name (ES2022) to check whether an object is a genuine instance, created by that class, without risking an error:
class Account {
#balance = 0;
static isAccount(obj) { return #balance in obj; }
}
console.log(Account.isAccount(new Account()), Account.isAccount({ balance: 0 }));
true false
Part 9 covers private fields.
The instanceof operator
obj instanceof Ctor is true if Ctor.prototype appears anywhere in obj's prototype chain. In practice, that means "was created by Ctor or by a subclass of it":
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object);
console.log([] instanceof Array, [] instanceof Object);
console.log(5 instanceof Number, new Number(5) instanceof Number); // primitives are never instances
console.log(Object.create(null) instanceof Object); // no prototype chain at all
true true true
true true
false true
false
- Every ordinary object is an instance of
Object, sinceObject.prototypeis at the end of nearly every chain. - Primitives are never instances of anything: use
typeoffor them (article 9). - If the right side isn't callable,
instanceofthrows aTypeError.
When instanceof gives the wrong answer
instanceof compares against one specific prototype object, so it fails for objects created in a different realm: another iframe, a worker, or a Node vm context each have their own Array:
const vm = require("node:vm");
const foreignArray = vm.runInNewContext("[1, 2]"); // created in another global environment
console.log(foreignArray instanceof Array, Array.isArray(foreignArray));
false true
That's why Array.isArray exists, and why ES2026 added Error.isError for errors. Prefer them over instanceof Array and instanceof Error in library code.
A class can also customize instanceof with the well-known symbol Symbol.hasInstance (article 19), which is useful for duck-typing but surprising to readers, so it's rarely a good idea:
class Even {
static [Symbol.hasInstance](n) { return n % 2 === 0; }
}
console.log(4 instanceof Even, 3 instanceof Even);
true false
Common questions
Why does [10, 9, 1].sort() give [1, 10, 9]?
Without a comparator, sort converts elements to strings and compares code units, so "10" < "9". Pass a numeric comparator: .sort((a, b) => a - b). The non-mutating toSorted (ES2023) takes the same comparator.
How do I compare two arrays or objects for order or equality?
< on arrays compares their string forms ([1, 10] < [1, 9] is true), which is almost never what you want, and === compares identity. Compare element by element in a loop, or for equality use a deep-equality helper (Node's util.isDeepStrictEqual, or a library).
Should I use in, Object.hasOwn or obj.key !== undefined?
obj.key !== undefined is shortest, but can't tell a missing property from one set to undefined. Object.hasOwn checks own properties, which is usually what you want for data objects. in also sees inherited properties, which suits checking for methods and features ("share" in navigator).
Is instanceof the right way to check types?
For your own classes, yes. For built-ins, prefer realm-safe checks: Array.isArray, Error.isError, typeof for primitives and functions. For plain data, check shape instead ("id" in obj), or validate with a schema library.
Summary
<,>,<=,>=compare strings by UTF-16 code units if both operands are strings, and numbers otherwise;NaNmakes every comparisonfalse.- Strings that look like numbers compare alphabetically (
"10" < "9"); convert them first. null >= 0istruebutnull == 0isfalse; check fornull/undefinedbefore comparing.- Use
localeCompareorIntl.Collator(withnumeric: truefor natural order) for text people read. - Dates compare correctly with
</>but needgetTime()for equality. key in objchecks own and inherited properties;Object.hasOwnchecks own only;#field in objis a private brand check.instanceofwalks the prototype chain; it's false for primitives and across realms, whereArray.isArrayandError.isErrorstill work.
Practice Questions
What do "B" < "a", "b" < "a" and "20" > "100" return?
Answer
true, false and true. Uppercase letters have smaller codes than lowercase ones, and "2" comes after "1" in string comparison, so the length doesn't matter.
Sort ["Émile", "eve", "Zoe", "adam"] the way a French reader expects.
Answer
names.toSorted((a, b) => a.localeCompare(b, "fr"))
Or with a collator: names.toSorted(new Intl.Collator("fr").compare). The result is ["adam", "Émile", "eve", "Zoe"].
A config object has { retries: 0 }. Why does this code misbehave, and what should you check instead?
if (config.retries) {
...
} else {
useDefault()
}
Answer
0 is falsy, so a deliberate 0 is treated as "not set". Check presence with "retries" in config or Object.hasOwn(config, "retries"), or use config.retries ?? 3 when only null/undefined should fall back.
What does "length" in "hello" do?
Answer
It throws a TypeError: the right operand of in must be an object, and a string primitive isn't one. "hello".length or typeof checks are the way to inspect primitives.
Why is this comparison true, while === is false for the same two dates?
new Date(2026, 0, 1) <= new Date(2026, 0, 1)
Answer
<= converts both dates to their timestamps (numbers) and compares those, which are equal. === compares the two objects' identities, and they're two different objects.
Previous: JavaScript Bitwise Operators: AND, OR, XOR, NOT, Shifts and Bit Flags
Next: JavaScript Logical Operators: &&, ||, !, ?? and Short-Circuit Evaluation

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.