Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What will happen when [50,100] is converted to Number in JavaScript?
Use the Number() method in JavaScript to convert to Number. When an array like [50, 100] is converted to Number in JavaScript, the result might be surprising.
What Happens with Array to Number Conversion?
When Number() is called on an array, JavaScript first converts the array to a string, then attempts to convert that string to a number. For arrays with multiple elements, this results in NaN (Not a Number).
Example
<!DOCTYPE html>
<html>
<body>
<p>Convert [50,100] to Number</p>
<script>
var myVal = [50,100];
document.write("Number: " + Number(myVal));
</script>
</body>
</html>
Number: NaN
Why Does This Happen?
The conversion process follows these steps:
let arr = [50, 100];
// Step 1: Array converts to string
console.log("Array to string:", String(arr)); // "50,100"
// Step 2: String converts to number
console.log("String to number:", Number("50,100")); // NaN
// Final result
console.log("Final result:", Number(arr)); // NaN
Array to string: 50,100 String to number: NaN Final result: NaN
Different Array Cases
console.log("Empty array:", Number([])); // 0
console.log("Single element:", Number([50])); // 50
console.log("Multiple elements:", Number([50,100])); // NaN
console.log("String element:", Number(["hello"])); // NaN
Empty array: 0 Single element: 50 Multiple elements: NaN String element: NaN
Comparison Table
| Array | String Representation | Number() Result |
|---|---|---|
[] |
"" |
0 |
[50] |
"50" |
50 |
[50, 100] |
"50,100" |
NaN |
Conclusion
Converting [50, 100] to Number results in NaN because the array becomes the string "50,100", which cannot be parsed as a valid number. Only single-element numeric arrays convert successfully to numbers.
Advertisements
