2

The following calls returns value of 0:

var n1 = Number()         // n1 === 0 is true
var n2 = Number("")       // n2 === 0 is true
var n3 = Number(null)     // n3 === 0 is true 

I tried above in Google Chrome Version 64.0.3282.119

But, is this behavior well-defined? I'm not sure if it behaves the same way in other browsers.

2
  • 1
    It's defined in the ToNumber() internal operation description in the language spec. Commented Apr 3, 2018 at 16:13
  • 2
    Look at the spec ecma-international.org/ecma-262/8.0/… Commented Apr 3, 2018 at 16:14

3 Answers 3

2

From the ECMAScript specification

enter image description here

For string-to-number conversion, there is added information in the next section: https://www.ecma-international.org/ecma-262/8.0/index.html#sec-tonumber-applied-to-the-string-type

Sign up to request clarification or add additional context in comments.

Comments

1

Yes this is an expected behavior on all the browsers.

Any non executable value passed to constructor of Number will return 0.

var num1 = Number();
var num2 = Number("");
var num3 = Number(false);
var num4 = Number(null);
// here num1, num2, num3 and num4 will be 0 as undefined, empty string, false and null are non-executable values.

If you pass executable non-number value to constructor of Number, it will return NaN

var num5 = Number("abc");
var num6 = Number({});
var num7 = Number([]);
// num5, num6 and num7 will be NaN as non-empty string, any object and any array are executable but Not a number values.

Comments

-2

When no argument is provided Number() will always return 0 and if the argument is illegale so Number() will return NaN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.