0

I expected the following script to display hello, but it display nullhello:

alert(null+'hello');

Why is this so? I can change from null to "", but still would like to understand what is happening.

2 Answers 2

10

The value null is stringified to "null", not to the empty string. That's just how it is, there is no "reason" :-)

Sign up to request clarification or add additional context in comments.

2 Comments

similar to how an empty object, {}, when coerces to a string, ends up as "[object Object]" (at least in Chrome browser)
Thanks Bergi, That had me for a loop for a while. I will not forget!
1

Javascript concatenates the two strings using the + operator. Consider the following example:

var a = null;
alert(a+'hello');

Even in the above case, the two vars are considered as strings to be concatenated.

In javascript, a default var is initialized as undefined and not null. Consider this

var b; 
alert(b+'hello');

.. This will result in undefinedhello

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.