Javascript Variable Declarations & typeof operator

Can you explain why typeof operator yields different results in the below case:
s4=s1+s2+s3 //typeof = string
s1+s2+s3 //typeof = number

NaN is type ‘number’. NaN is what we get when we cast a value which is not a number to a number using the unary operator, +. That is how your log expression is being evaluated, pre-logging.

+ is used to cast a number in string form (or something in any form, such as a boolean), to a number in literal terms.

   Expression      =>  Evaluation

typeof + 'string'  =>   'number'

+"42" + +"42"      =>    84

+"xyz25true"       =>    NaN
2 Likes

Okay! I wasn’t aware of this functionality in JS. So it’s because we’re appending “+” symbol when logging it to the console that it shows Number type. Not so sure that why I put the + symbol in the first place as it wasn’t needed. May be I was subconsciously thinking the expression equivalent to string interpolation. But I’m glad this taught me this new concept.

Tried few examples:

Thank you very much @mtf . Appreciate your prompt response.

1 Like