var a = [10];
console.log("a = %d", a); ---> Printed a = 10
var a = [10, 20];
console.log("a = %d", a); ---> Printed a = NaN
Why for a single element array, we can directly use the array name to access the element?
var a = [10];
console.log("a = %d", a); ---> Printed a = 10
var a = [10, 20];
console.log("a = %d", a); ---> Printed a = NaN
Why for a single element array, we can directly use the array name to access the element?
Placing an array into string context will implicitly call toString on it (which, for an array, is along the lines of this.join(",").
If the array contains one number, then the resulting string will be a value you can parse as a number.
If the array contains multiple numbers, then it won't.
console.log("a = %s", [10]);
console.log("a = %s", [10, 20]);
console.log(Number("10"));
console.log(Number("10,20"));
With that formatter %d, you're asking to output an integer.
[10] == 10), in JavaScript, return true. So, an integer and array that only has the same integer are equivalent. Also, Number([10]) returns the number 10. Number([]) returns 0. ['a'] == 'a' also returns true. But String(['a']) returns the string ['a'].
[10, 20], though, doesn't have an equivalent integer. It can't be converted to an integer: Number([10]) returns NaN. That's why you get NaN (i.e.: not a number).
You find in the Ecma Standard how types are converted to numbers. Notice that array's type is Object.
In conclusion: that happens, because you're asking for an integer and way arrays are converted to numbers in JavaScript.
Array is a continious memory location. When we define an array as arr=[a,b,c]; then the memory refernce of the first element is stored in arr. If there is only one element in an array (arr=[5]) so arr will be storing the reference of the memory location where '5' is present. And if there are more than one element then we need to provide the element number.