Data types in JavaScript: Difference between ‘==’ and ‘===’ in Javascript:
Data types in JavaScript:
Data types are nothing but different types of data that can be stored. JavaScript provides two types of data types: Primitive and Non-primitive.
It is important to note that JavaScript is a dynamically typed language. It means that we do not have to specify the data type for a variable, it is done dynamically by the JavaScript engine.
1. Primitive Data Types:
Number: It represents numeric values, both with and without decimal.
Eg: let x = 5;
String: It represents a sequence of characters inside quotes. It can consist of letters, words, and sentences. It is important to note that even numbers enclosed inside quotes are treated as strings.
Eg: let x = "Test123";
Boolean: It represents either true or false.
Eg: let a = true;
Undefined: A variable that has not been assigned a value is of type undefined.
Eg: let a;
null: It represents null, which means no value at all.
Eg: let a = null;
2. Non-primitive data types:
Object: It represents information in the form of key-value pairs.
Example:
In the above example, city, state, and country are properties of the details object. They can be accessed either using the square bracket syntax as shown above i.e. details['city'] or they can be accessed using the dot syntax i.e. details.City
Array: It is used to store multiple values at once.
Example:
You will learn more about arrays and objects later on in the module.
- Difference between ‘==’ and ‘===’ in Javascript: You would have normally observed ‘==’ sign in if conditions. However, JS offers two types of equality checks, ‘===’ being the other option. What is the difference between both?
- ‘==’ is called an equality operator and ‘===’ is a strict equality operator. As the name suggests, ‘===’ operator strictly checks the type as well while comparing two things while ‘==’ does not.
- ‘==’ actually converts the two operands into the same type and then compares the values. On the other hand, ‘===’ checks both type and values without any kind of conversion.
Example:
It can be observed in the above example that when values of ‘a’ and ‘b; are checked without strict checking, the condition is true even when ‘a’ is a boolean and ‘b’ number. However, they are converted into a single type and checked.
This is because in JavaScript, 1 number is considered to be similar to a true boolean, and 0 number is considered to be similar to a false boolean.
On the other hand, ‘===’ sign offers strict checking where both types and values equality is checked. Hence, the condition fails since both ‘a’ and ‘b’ are of different types.
To avoid confusion, it is always recommended to use the strict equality operator, i.e. ===
Comments
Post a Comment