Table of contents
Javascript is one of the most trending and popular languages. You can build anything with JavaScript, websites, Web Apps, Native Mobile Apps, etc. JavaScript's versatility extends to server-side development, enabling the creation of robust and dynamic backends, making it a comprehensive language for full-stack development. Its extensive ecosystem and active community contribute to its continued popularity and innovation.
But Javascript has many weird functionalities above all this, making developers think "JavaScript is Weird". Let's see a few of the most weird things in Javascript.
StringNumber
const stringValue = "7";
const numberValue = 7;
console.log(stringValue + numberValue);
console.log(typeOf(stringValue + numberValue));
what do you think will be the output?
A number? Hell No!
An error? Ummm still NO!
The output will be:
"77"
string
but why does it give a string as an output? Because JavaScript assumes that you want to concat something inside the string, so it converts the number to a string and the output is of string data type.
String - Number
You might wonder if a similar thing will happen when you subtract a string from a number. Let's check it out!
const stringValue = "7";
const numberValue = 5;
console.log(stringValue - numberValue);
console.log(typeOf(stringValue - numberValue));
will the output be a string? NO the output is a number🤯🤯🤯!
2
number
So what happens when there are two types of operations
String Concatenation
Numeric Operation
As soon as JavaScript detects the type "string," it checks for possible string concatenation, as is the case with the '+' operator. However, if the operation is not string concatenation, it then proceeds with numeric operations and attempts to convert the string into a number. So I feel JavaScript is not weird but a part of JavaScript's design philosophy.
Let's see one more version of type coercion in JavaScript:
What's the type of null?
I had the curiosity about the type of a variable whose value is not initialized.
typeOf(null)
and the output was: 'object'. But how?!?!?!
Comment down below or let's connect on:
Loved the blog? Awesome❤️❤️❤️! Follow for more🤙🙌
References: MDN