DEV Community

Cover image for Unexpected Moments of JavaScript That Will Challenge Your Understanding of the Language

Unexpected Moments of JavaScript That Will Challenge Your Understanding of the Language

Code of Relevancy on March 18, 2023

As one of the most popular programming languages in the world, JavaScript is widely used for building dynamic and interactive websites, web applica...
Collapse
 
tohodo profile image
Tommy • Edited

Good stuff. Another common gotcha:

for (var i = 0; i < 3; ++i) {
  setTimeout(() => console.log(i), 1000); // returns 3 three times
}

for (let i = 0; i < 3; ++i) {
  setTimeout(() => console.log(i), 1000); // returns 0 1 2
}
Enter fullscreen mode Exit fullscreen mode

This is because var creates a single binding at the function scope, so after a one-second timeout the loop has already run its course, hence you get 3 three times. By using let you bind the variable at the block scope (loop), so it returns the values you expected since i refers to the value at that loop iteration.

Collapse
 
wintercounter profile image
Victor Vincent

If someone wants to overcome this while using var, not many people know that setTimeout can accept params to be passed to the callback, great alternative to bind.

for (var i = 0; i < 3; ++i) {
  setTimeout(a => console.log(a), 1000, i);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tohodo profile image
Tommy

Good tip. I used this pattern a lot before ES6.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Good fix

Collapse
 
codeofrelevancy profile image
Code of Relevancy

I gave your suggestion a space, here it's..

Image description

Thank you again.. Happy reading!!!

Collapse
 
scofieldidehen profile image
Scofield Idehen

this is insightful.

Thread Thread
 
codeofrelevancy profile image
Code of Relevancy

Yes

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes perfect example. I will add it to the article..
Personally, I don’t use ‘var’. I always use ‘let’ and ‘const’ to avoid these kinds of bugs..
Thank you for your valuable feedback

Collapse
 
joydeep-bhowmik profile image
Joydeep Bhowmik

This was really informative and solved one of most annoying glitch of my small project. Thanks

Collapse
 
codeofrelevancy profile image
Code of Relevancy

You're welcome my friend. Glad you found it helpful and thank you for your feedback..

Collapse
 
aarone4 profile image
Aaron Reese

The moral of this article is
1) don't try to be clever. Just write clean, clear expressive code.
2) Using Typescript will avoid the majority of the accidental type coercion errors.
3) please don't rely on these coercion oddities for logic gates. Be explicit.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

I appreciate your input on this article

Collapse
 
tracker1 profile image
Michael J. Ryan

Interesting... But most of this begins to make more sense if you understand how loose typing works through coercion and the seven falsy values.

I learned this I've 25 years ago.

It also helps when using JS to process potentially unreliable input. JS is also pretty nice for ETL work.

Collapse
 
tracker1 profile image
Michael J. Ryan

One thing I've found cool is that ~~ double bitwise not will coerce any value into a number in the 32-bit signed integer range. Not number or easily interpreted string values will be 0.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes it's more important to understand the loosely type languages..

Thank you sir for your valuable feedback..

Collapse
 
zetaraku profile image
Raku Zeta • Edited

5️⃣ is terribly wrong and your explanation just contradicts to itself:

JS converts the string "1" to the boolean value true and string "0" to false because any non empty string is considered truthy and on other side falsy.

Is "0" even non-empty?
Does true == "2"?
Does if ("0") { console.log("hi"); } execute?

Read the doc: developer.mozilla.org/en-US/docs/W...

Collapse
 
codeofrelevancy profile image
Code of Relevancy • Edited

Image description

I will update the explanation. Thanks

Collapse
 
mergerg profile image
Raphael

I've always loved these little tricks (although they do lead to some nasty mistakes sometimes lol) and this is a wonderful compilation! I also really appreciate that you made the NaN example say baNaNa

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Glad you loved it and thank you for appreciating it. Happy reading..

Collapse
 
zirkelc profile image
Chris Cook

It’s kind of frightening to see that the language that runs all of the web and a lot of backend applications has so many quirks.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes it should be refactored. Thanks you for the feedback..

Collapse
 
ant_f_dev profile image
Anthony Fung

Nice write up!

People generally love JavaScript for its duck-typing, but this article illustrates that there are quite a few traps that we can fall in to if we aren't careful.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you my friend. Yes I agree with you.. we should be careful with JavaScript. I appreciate your feedback..

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you my dear friend. I appreciate it

Collapse
 
jonrandy profile image
Jon Randy 🎖️

These results are only 'unexpected' if you don't fully understand the language and how to use it. They can also be used to your advantage.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes you’re right. But sometimes it happens, even for experienced developers..
Thank you for your feedback

Collapse
 
codeofaccuracy profile image
Code Of Accuracy

This is really helpful cleared core concept which is mainly we are using day to day coding.

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you for appreciating it

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you, Parth. Tamaro feedback mne gamyo..

Collapse
 
Sloan, the sloth mascot
Comment deleted
 
codeofrelevancy profile image
Code of Relevancy

😂😂

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Well done @codeofrelevancy This is awesome

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you sir for appreciating it..

Collapse
 
louiecodes profile image
L O U I S

Accurate compilation of JS 'craziness' that could drive a human insane lol

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes it could..
Thanks for comment

Collapse
 
ndohjapan profile image
Joel Ndoh

This is crazy

Thanks for sharing this

Collapse
 
codeofrelevancy profile image
Code of Relevancy

You’re welcome my friend. Thank you for your kind message

Collapse
 
mustakimbee profile image
Md.Mustakim Ahmed

Good One 👌

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you boss

Collapse
 
pcockerell profile image
Peter Cockerell

This article is a great advert for the use of TypeScript. Hardly any of the examples would even compile in TypeScript, as they shouldn't in any language that takes type safety seriously

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Yes agree, TypeScript is better in this case. Thank you sir for your valuable feedback..

Collapse
 
clericcoder profile image
Abdulsalaam Noibi

Wow,what an informative and educative Article. Thanks for sharing

Collapse
 
codeofrelevancy profile image
Code of Relevancy

You're welcome dear. Thanks for the feedback.. Happy reading!!!

Collapse
 
stakedesigner profile image
StakeDesigner • Edited

it is a useful article for developers

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Thank you for feedback