1

I am not understanding what the Number function does. This is the tutorial I'm using, which in fact does explain what the function does... BUT... when I delete Number it still returns the same value, so I'm not understanding its purpose. Even if I change Number to String it still returns the same value. Here is the example code:

var theNumber = Number(prompt("Pick a number", ""));  
print("Your number is the square root of " +  
    (theNumber * theNumber));

1 Answer 1

3

Whats happening is its automatically converting theNumber to a number to do the *.

I am assuming you are saying you did:

var theNumber = prompt("Pick a number", "");  
print("Your number is the square root of " +  
(theNumber * theNumber));

Here is a good reference that explains "Automatic Conversions"


It looks like you have a second question, and is "Why would I ever use it?"

Once you have convert it you a "Number" object you now have access to some additional properties/methods which allow you to do some conversions like adding/trimming decimals, as well as converting to Exponential Notation.

Example (user Enters 1.22222222222222222222222222):

var theNumber = new Number("1.22222222222222222222222222");
theNumber.toFixed(2);
//value is now 1.22
Sign up to request clarification or add additional context in comments.

9 Comments

But if that's the case why am I still able to get the correct return without using the Number function. Sorry, I'm still not understanding.
Its a loosely typed language. For example assume you enter "3". It takes the "3" * "3" and converts it to the number to do the multiplication. Did you look at the article? look for the -, *, / and % operator section.
I'm understanding what you're saying, but when I don't even USE the Number function it still is able to do the multiplication correctly. Edit: I didn't see your link at first, I will look at that now
Agreed. And I explained why above, its converting your string to a number automatically. The value of using "Number" is that it can convert a bad value to NaN if the input is invalid. (not sure if the automatic casting will do this)
It would have helped if the tutorial mentioned that this was done automatically. But since this is the case I'm still not understanding why you would use Number if it's done automatically. Sorry, this is probably something most programmers get, but I've never programmed before. Edit: it still does convert it to NaN without the function...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.