DataTypes in JavaScript
- Boolean
var a = true; // true or false
- Number
var a = 100; // including decimal numbers
- String
var a = 'Hello, World!'; // enclosed under single or double quotes
- BigInt
var a = x + 1n; // 9007199254740993n
- Null
var a = null; // null variable
- Undefined
var a; // value not declared
- Symbol
var a = Symbol("abc"); // unique identifier
Expressions
You might have come across certain memes where javascript behaves strangely with respect to other programming languages when it comes to certain expressions. For example:
var a = "" + 1 + 2 // evaluates to "12"
But we are adding up a String type with a Number type here. How is that even logical? Alright! JavaScript initially checks the first expression and notices that it is of String type so therefore it concludes that the entire expression is of type String and concatenates the rest of the expression. This makes javascript a lot of fun to work with. Let's see another example and guess the output:
var a = true + false;
The above expression evaluates to 1 of Number type because true gets interpreted as 1 and false as 0. Awesome! Let's check out another one:
var a = "2" * "10";
You might think this could result in an error, but javascript is clever enough to understand that multiplying string makes no sense, hence it multiplies them as numbers and returns 20.
The sole purpose of this was not to show javascript is a "weirdo", but to depict how flexible, adaptable and diverse this language is and the amount of fun it is to work with.
Still not convinced? I have a fun activity for you. There is a huge debate on the topic, "Was it the hen or the egg that appeared first on this planet?". JavaScript answers this easily. Just go to your browser console and enter the following piece of code:
['π₯','π'].sort();
This clearly says that the egg appeared first on this planet and settles the debate(Scientists say the same too).
I hope you understood some of the basics and fun involved in learning javascript.
Thank You!
Top comments (2)
I think the example for null data type is incorrect, the value will be undefined for "a" there. Correct example could be "var a = null"
Noted! Thank you! I will make changes right away.