Front end developer Front end developer - 14 days ago 7
Javascript Question

Global variable is null

I have a global variable. The variable is equal to null. " var a=null;" Then I write a=a+"example" in console. But output is nullexample. Why is it so ?

Answer

There are three possibilities in javascript:

Option 1

var a; 
a=a+"example";

output: "undefinedexample"

Option 2

var a=null; 
a=a+"example";

output: "nullexample"

Option 3

var a=""; 
a=a+"example";

output: "example"

As per your Question you need to define third option. bcz in javascript null and "" both are different types.

For more ref JavaScript String concatenation behavior with null or undefined values