DEV Community

Cover image for Time for JS brain teasers
Akash K
Akash K

Posted on

Time for JS brain teasers

Hello Everyone!...

No doubt that JavaScript is one of the weirdest programming language. I'm sure that many of you will agree with me!... So let's explore some of its weirdness together.

Rub your hands!!... It's time for some quick JavaScript brain teasers.

So Can you predict the output for the following consoles?

questions

Well I couldn't predict on the first try. If you've predicted it correctly congratulations!..For those who didn't crack it, you are not alone!..

Okay let's try to figure out

console.log(1 + "2" + "2");
Here 1 is an integer whereas the "2" is a string. So what will happen will you try to add integer with a string? That's right! It will get concatenated instead of getting added.
So the output is "122"

console.log(1 + +"2" + "2");
This is more similar to the first one but here one more + is there before "2", + before a string will convert that to an integer. So here "2" will become 2. Hence 1+2 will be 3 and the 3 will get concatenated to the final string which is "2".
So the output is "32"

console.log(1 + -"1" + "2");
This is very similar to the above console, the difference here is instead of + here it is -. - will convert the string to negative integer. so "1" will become -1. 1+(-1) is 0 and it will get concatenated to the final string which is "2".
so the output is "02"

console.log(+"1" + "1" + "2");
No need of explanation I guess, you already know the answer. Yes the output is "112"

console.log( "A" - "B" + "2");
Okay here we are trying to subtract a string("A") with another string ("B") which is not possible Right? so what do you think it will print? Exactly it will print NaN. But there is another string("2") after that so that will get concatenated.
So the output is "NaN2"

console.log( "A" - "B" + 2);
This more similar to the last one. we know that "A" - "B" will print NaN and we know why. But here there is an integer(2) which is getting added which means NaN + 2. So what do you guess is the answer?
The output is just "NaN"

Thank you so much for making it so far. Please do share your thoughts on this.

If you liked reading this blog, please don't forget to like ❤️, and share 🤩. See you in the next post.

Cheers! 🤙

Top comments (0)