0

Im currently reading eloquent JavaScript and this was an example for using the prompt command:

var theNumber = Number(prompt("Pick a number", " "));

Why does the bolded need to be there? Is that the way of letting the computer know what kind of entry was entered? If it was a set of words would it be String(prompt("Pick a number", " "));

1

1 Answer 1

1

If you just used:

var theNumber = prompt("Pick a number");

The variable theNumber would be set to a string. For example if the user entered 5, then theNumber would equal "5". Number() is a function in javascript that will convert a string to a number, meaning if you use:

var theNumber = Number(prompt("Pick a number"));

Then theNumber would equal 5 or whatever the user entered.

If you wanted to convert a number back into a string, you would use:

var stringOfTheNumber = theNumber.ToString();

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

2 Comments

Also worth mentioning that Number() is considered harmful. Number("0x100") returns 256. Instead use Number.parseInt(..., 10) where in that case you'll get 0.
Also it is important to use try, catch statements in the event that the user doesn't enter a number.

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.