This one thing I never said ever - “once you type, you cannot un-type”. Yep, I make up words and compete on how to level up in my eating my own words.
Even if I allegedly uttered those words (which are totally unoriginal anyway), I happily don’t abide by them. I continue to use Javascript without types with all fervour (and have had a stint with typeless / loosely-typed scripting languages).
So.. what are these types that have given many a Javascript developer sleepless nights? (huh?)
Programming languages did not befriend Javascript, and classical programmers frowned at it since there were no types.
While others do a int
, String
, {% raw %}List
|
|
.. and later -
|
|
‘i’ can be a best of friends with strings, integers, numbers, objects and so on.
There were too many people jumping away from one language to the other, and saw a ‘yuuuge’ benefit of introducing types in Javascript as well.
Any who, blah blah.. and yadda yadda later, we had super set languages like Typescript that introduce types and willing to die by types.
Gotcha
Did I ever say ‘type-less’? Well, this can’t be true. What will ever happen if -
|
|
Will JS add numbers, add ASCII value, get mad and refuse to execute any programs for next 24 hours?
Well, it turns out that Javascript has types internally. Dynamic typing is a feature - I hope you heard that loud and clear?
In the above examples Javascript will intelligently figure out which types should be converted to which other types before doing the specified operation.
|
|
Type in the Types
Types can be many and you can define your own types as well. However there are what are called ‘primitive types’ that are part of the core language.
Javascript simple primitive types are string, number, boolean, null, undefined, and symbol. The complex primitive type is object. I bet you had figured that one out yourself.
What happens internally?
JS will use implicit type conversions for any operation starting from the left side of the expression to the right. As a developer you MUST understand that or suffer innumerable times in typeless hell.
For example:
|
|
Or..
|
|
In the above logic, none of the last three ‘if’ conditions are executed.
I’m afraid. How can I avoid the typeless hell?
Simple -
- Keep reading this blog. I personally bless everyone who reads this post
- Know which operations do what
- Or, do what I do - always assume the worst and over-engineer
Rewriting the above examples -
|
|
Clear about the last statement but confused on the last but one? Fear not - head over to Javascript type casting.