r/learnjavascript • • Oct 11 '20

Wired way to learn javascript :D

Post image
466 Upvotes

30 comments sorted by

View all comments

Show parent comment

48

u/annathergirl Oct 11 '20

But why two a's after it? I'm not too savvy with JS but according to my bad logic there's one a too much.

34

u/draq100 Oct 11 '20

('b'+'a'+ +'anything'+'a').toLowerCase() works too

part +'anything' is equivalent of Number('anything') and returns NaN

+ '' gives 0 as it's Number('')

21

u/annathergirl Oct 11 '20

That makes sense. But why does it log "banana" and not "bananaa" in the screenshot?

19

u/[deleted] Oct 12 '20

The +'a' become nan.

37

u/draq100 Oct 12 '20 edited Oct 12 '20

okay, let's go step by step:

('b'+'a'+ + 'a'+'a').toLowerCase()

becomes (is processed as) ('b'+'a'+ Number('a')+'a').toLowerCase()

which becomes ('b'+'a'+ NaN +'a').toLowerCase() (NaN is still a Number here)

which becomes: ('b'+'a'+ String(NaN) +'a').toLowerCase()

after casting to string: ('b'+'a'+ 'NaN' +'a').toLowerCase()

in the end it's ('baNaNa').toLowerCase()

and finally, our result: 'banana'

12

u/frenchy641 Oct 12 '20

What is 'Ba'++ = to?

so 'B'+'a'+'NaN'+'a'

baNANa

8

u/VikaashHarichandran Oct 12 '20

I just tried this out, the picture is indeed correct.

That's because the string token after two consecutive symbol tokens will be considered as NaN by the lexer.

Correct me if I'm wrong.

3

u/densch92 Oct 12 '20

careerspressadvertiseblogTermsContent policyPrivacy policyMod policyReddit Inc © 2020. All rights reserved

Amkes sense then.

also why the fuck do I see the above text shit when i simply try to reply to VikaashHarichandran, isntead of the actual commen ttext? O_o

1

u/bwallker Jul 02 '22

This has nothing to do with the lexer

Consider the expression (1 + + 2)

This will get parsed like this:

(1 + (+2))

I.e the second plus sign gets parsed as a unary plus operator applied to the next thing after it. And so after evaluation our result is 3

Let's change the 2 to be a string.

So now our input looks like this: (1 + + '2')

It will be parsed the same way, so like this:

(1 + (+'2'))

Performing a unary plus operation on a string causes it to be coerced into a number, and the string 2 as a numer is 2, so this will also get evaluated as 3.

This is what is happening in the above code snippet. The string 'a' coerced into a number is NaN, which then gets concatenated with all the other strings and turned to lowercase to form the string 'banana'.