var one = 1;
var one_again = 1;
var one_string = "1"; // note: this is string
console.log(one == one_again); // true
console.log(one === one_again); // true
console.log(one == one_string); // true
console.log(one === one_string); // false
As you can see in the above code I've declared three variables with different names but the same values.
var one = 1
where I've used the '='
an operator which is used to assign the value to the variable.
Now, I'm going to compare the variables with the 'one'
variable.
console.log(one == one_string)
returns true because both variables, one
and one_string
contain the same value even though they have different types: one
is of type Number
whereas one_string
is String
. But since the ==
operator does type coercion, the result is true.
console.log(one === one_string)
returns false because the types of variables are different.
In the end, perhaps it will help beginners to clear their doubts. If this article helped you please do like and comment. Thank you so much.