mina mina - 2 months ago 33
Javascript Question

how does alert print array , although it takes strings?

I am a beginner in javascript , I have a question , I have an array like

var nameOfName=["john","mark"];
alert(nameOfName); // or
document.getElementById("anyelementid").innerHTML=nameOfName; //should also trigger error because we are trying to put array in place of string.

why alert or innerhtml shows the results correctly although it's an array, not a string ?
I think in other programming techniques an error should be triggered and a message told us that this is an array to string not allowed conversion .


When calling alert with an object value (arrays are objects, just a special case), it automatically calls toString on that value.

var arr = [1, 2, 3];
// Notice that they show the same result

The thing about Javascript is that it's dynamically typed with type coercion. In laymans terms, that means it will automatically try to convert your data to the correct type given the context. For example:

// Converts the number to a string
console.log(1 + '2');

// Converts the booleans values to numbers
console.log(true + true);