== vs === vs typeof in javascript

== vs === vs typeof in javascript

In yesterday's lesson, we covered the concepts of Implicit, Explicit, Nominal, Structuring, and Duck Typing in JavaScript. We delved deep into each of these terms and provided some useful references for further study. If you missed that article, you can find it here. Now, let's move on to today's post.

In yesterday's lesson, we covered implicit behavior in javascript. Implicit behavior refers to actions that occur automatically without being explicitly stated in the code.

Javascript has an implicit behavior where it automatically converts data types to a common type when performing operations. This is called type coercion.

For example: if you add a number to a string using the "+" operator, JavaScript will implicitly convert the number to a string and concatenate the two values.

//Type coercion
let result = "2" + 3;
console.log(result); // Output: "23"

Coming back to the topic of the day; when you see `==` , === and typeof what comes immediately to your mind is a comparison in Javascript but the latter is different as it is used to check the type of a datatype.

When used in combination with the equality operators == and ===, it can help ensure that the values being compared are of the same type.
For example, consider the following code:

let x = 5;
let y = "5";

if (typeof x === typeof y && x == y) {
  console.log("x and y are equal");
}
//Will log undefined since x and y are of different types.

In this code above, the typeof operator is used to check if x and y are of the same type before performing the loose equality comparison with the == operator. Since x is a number and y is a string, JavaScript will convert y to a number before performing the comparison, and the code will output "x and y are equal".

If we were to use the strict equality comparison operator === instead, the code would output "x and y are not equal", because the two values are of different types.

Note: it is recommended to use the typeof operator to check the data type of a value before using the == or === operators to perform equality comparisons, to ensure that the values being compared are of the same type.

I hope you have understood what all these operators do in javascript and how they can be used together can help you write more efficient and reliable JavaScript code.

Tomorrow we won't be handling any topic but we will summarize all 5 days in one post to improve our understanding of the concepts learned.

As always leave a comment and share this post if you found this post helpful: