How does == vs === and != vs !== differ in JavaScript?

Jadala Ajay
2 min readDec 20, 2022

--

While working on Playwright I came across below situation where we compare the values between two variables from an API response. So I did some reading on this topic and thought of sharing all my findings with audience.

const [response] = await Promise.all([
// Waits for the next request matching some conditions
page.waitForResponse(
respo=>
respo.url() === 'www.google.com/image' && respo.status() ===200 ) //using some random url here just for reference
]);

So below are the actual differences

  • == converts the variable values to the same type before performing comparison. This is called type coercion.
  • === does not do any type conversion (coercion) and returns true only if both values and types are identical for the two variables
  • != Converts values if variables are different types before checking for inequality
  • !== Checks both type and value for the two variables

Is there any performance improvement using === than == ?

No, Its almost negligible. Most suggestable is to use=== until and unless you want to do type coercion.

Lets see some examples to understand it better.

var a = 'ajay16';
var b = 'ajay16';
console.log(a==b) // true
console.log(a===b); // also true as type of both variables is same (String here)

another example to understand it better.

var anum = 99;
var bnum = 99;
var cstr = "99"; //string
console.log(anum == bnum); // true
console.log(anum === bnum); // true
console.log(anum == cstr); // true as type coercion happens here.
console.log(anum === cstr); // false

Same is the case with != and !== also.

Can we compare Arrays or Objects also in the same way?

No, The comparision should work only with primitive types. See

var array1 = ['a',1,false];
var array2 = ['a',1,false];
console.log(array1==array2); // false
console.log(array1==array2); // false

BTW the basic thing, = is used as an assignment operator.

Please let me know your thoughts on this in the comments and hit follow if it’s helpful as I will be sharing such cool things.

--

--

Jadala Ajay
Jadala Ajay

Written by Jadala Ajay

8 Years Exp Senior Automation Engineer with expertise on Selenium,RestAsured API,Postman,Cypress,WebdriverIO with prog languages Java,Javascript and Python

No responses yet