Computer >> Computer tutorials >  >> Programming >> Javascript

Why it is better not to create numbers as objects in JavaScript?


In javascript try not to convert numbers into objects because numbers can't be compared to objects and even objects cannot be compared to objects.

Example

In the following example, the provided number 20 is assigned to both variable 'x' and variable 'y'. When compared both the variables with each other, Boolean value "true" is displayed as shown in the output.

<html>
<body>
   <script>
      var x = 500;
      var y = (500);
      document.write((x===y));
      document.write("</br>");
      document.write(typeof(x));
      document.write("</br>");
      document.write(typeof(y));
   </script>
</body>
</html>

Output

true
number
number

Example

In the following example, variable "y "is turned from number to an object and then when compared with variable "x" Boolean value false is displayed as shown in the output.

<html>
<body>
   <script>
      var x = 500;
      var y = new Number(500);
      document.write((x===y));
      document.write("</br>");
      document.write(typeof(x));
      document.write("</br>");
      document.write(typeof(y));
   </script>
</body>
</html>

Output

false
number
object