===
The strict equality operator compares values without type conversion: true only for the same type and the same value.
- Returns
trueorfalse.
Example
#console.log(1 === 1)
console.log(1 === '1')
console.log(1 == '1')
console.log(0 == '')
console.log(null == undefined)
console.log(null === undefined)Definition and usage
#The === operator returns true when both sides have the same type and the same value. It never converts anything: the number 1 and the string "1" are different to it. Its negation is !==.
The loose operator == converts types before comparing, following convoluted rules, which is why 0 == "" and "1" == 1 are both true. That’s why modern code standardizes on ===. The one common exception is value == null, which checks for null and undefined at once.
Objects, arrays, and functions are compared by reference, not by content: two separately created objects are never equal to each other. A special case is NaN, which isn’t even equal to itself. Number.isNaN() and Object.is() are used to detect it.
Syntax
#a === b
a !== bMore examples
#const a = { level: 1 }
const b = { level: 1 }
const c = a
console.log(a === b)
console.log(a === c)
console.log([1, 2] === [1, 2])const result = Number('abc')
console.log(result === NaN)
console.log(Number.isNaN(result))
console.log(Object.is(result, NaN))const input = '5'
const correctAnswer = 5
console.log(input === correctAnswer)
console.log(Number(input) === correctAnswer)Values from form fields and URL parameters are always strings. Convert them to a number explicitly before comparing, instead of relying on ==.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always write
===and!==. If you’re comparing values of different types, convert explicitly, e.g. withNumber(value)orString(value). - To compare the contents of two arrays or objects, compare specific fields, or use a function for deep comparison.
===only checks whether it’s the same object.
Related entries
#- &&, ||, !The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.
- typeofReturns a string with the name of a value’s type, e.g. "number", "string", or "object".
- switchCompares a value against a list of case labels and runs the code from the first match.
- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- Number.isNaN()Checks whether a value is exactly NaN.
- Object.is()Checks whether two values are the same. It differs from === only for NaN, and for 0 and -0.
Spotted a mistake or missing an example? Write to us.