DEV Community

Discussion on: Why do we write JavaScript like this?

Collapse
 
spazmodius profile image
rajiv • Edited

Why do we right code like this?

if (s[i] != s[s.length - 1 - i]) {
Enter fullscreen mode Exit fullscreen mode

This allocates 2 1-character strings, and performs a string comparison (not a character comparison, there is no character datatype in Javascript).

If efficiency is our criteria, then we would write

if (s.charCodeAt(i) !== s.charCodeAt(s.length - 1 - i)) {
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anders profile image
Anders

That is great, how does that perform compared to what I wrote?

Collapse
 
spazmodius profile image
rajiv • Edited

That is, of course, the right question.

In Node 12, it seems to make no difference at all. Maybe they optimize to the same thing.

Results may vary in other runtimes.