Curiosity Encountered in Javascript Tutorial - javascript

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));

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

Related

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

Is using parseInt extraenous if unnecessary?

I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.
var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;
I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?
Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.

Should literal numbers not have quotes?

I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
That being said, is there anything wrong with quoting a literal number?
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
It isn't a number. Quoting a number makes it a string, which can make for some differences in the way they're handled. For example:
var a = 1;
var b = '33';
console.log(a + b === 34); // false
console.log(a + b === '34'); // true
Strings also have different types and methods for manipulating them. However, for most of the numeric operators (-, /, *, and other bitwise operators), they convert the string form to its numeric equivalent before performing the operation.
There are also a few differences where numbers are not stored with their exact value in some cases, due to the nature of the floating point format JavaScript numbers are stored in. Strings avoid this problem, though it is much harder to manipulate them. Converting these back to numbers reintroduces these issues. For example, see this:
var recordID = 9007199254740992;
var previousID = recordID;
recordID += 1;
console.log(recordID === previousID); // true
Adding quotes makes the number a string literal and so serves a different purpose than the Number literal defined without quotes.
JavaScript has the concept of type coercion which might have confused you.
Quoting makes a string of a number. It means that for example + operation will concatenate instead of add:
var a = 'asdf';
var b = '20';
var c = a + b; // asdf20
Here is a great explanation of what is going on.
I know that literal numbers do not require quotes around the value. For instance, var x=123; is acceptable and does not need to be var x='123'; or var x="123";.
It's not a matter of required Vs not required (optional)
Using quotes (single or double) you state that it is a string (a sequence of characters - no matter if they're all digits)
If you don't place quotes you state it is a number.
That being said, is there anything wrong with quoting a literal number?
No if the entity it represents is not actually a number but a string. So...
If the "number" was a zipcode or database record ID, and not a number in the normal sense which might be used in arithmetic, would the answer be different?
If the number is a zipcode it may make sense to put quotes, because it is a "code", not a number and is not subject to arithmetics operations.
You're not going to divide a zipcode by 2 or sum two zipcodes because that would not make sense.
But instead of deciding to use quotes or not based on what the value represents I suggest you to consider the problem from the language perspective
You should understand and keep always in mind how do the language's operators behave when you use a string instead of a number in an expression (assignment or comparison).

New to Javascript calculations

I'm BRAND new to javascript so this is probably an easy fix I can't figure out.
I'm writing a easy script to calculate age Leapyear, Dog years and plus Five.
var age = prompt ("what's your age?");
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);
JS isn't calculating age + 7. It's writing the age + 7. So if I write 15 in the age prompt it will print in the browser 157.(15) and (7) Which i understand and know why. but how do I get it to compute the math.
It's actually returning 1573.75155
thanks
Like what everyone's been saying, prompt returns a string so it needs to be converted. There are a number of ways to do this, some of which have already been mentioned:
parseInt('123')
parseFloat('123')
Number('123')
These are probably the most common and depending on context also quite possibly the most clear and intuitive ways of doing it. There are also a couple of very terse and interesting ways of converting strings to numbers, depending on which kind of number you'd like. For instance, to convert a number in a string to a float, you can prefix it with the + operator:
+'1.23'
This can seem really counter intuitive, particularly since 4 + '1.23' will actually return 41.23. So what's going on? Well, the + operator, when used as a unary operator (that is, it only has one operand on the right hand side) will always convert the operand value to a number. Compare these two (try them in a javascript console):
4 + '1.23' // returns 41.23
4 + +'1.23' // returns 5.23; the second + is a unary operator
In contrived examples such as this, it really reads rather badly so you might not want to use this trick everywhere. But in your code, it reads quite well:
var age = +prompt("What's your age?")
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
If you understand the workings of the unary plus operator (it really isn't rocket surgery) then you can get some nice terse but quite comprehensible results.
The unary + operator will always convert the value to a Number, i.e. floating point. Now, you might want an integer instead, in which case you can use the bitwise not operator twice, like so:
4 + ~~'1.23' // returns 5; note the double operator
This operator first converts the value to an integer, and then returns the bitwise complement of the value, meaning all the bits are inverted. Using it twice will mean that we get the complement's complement, i.e. the original value but this time as an integer instead of a float.
Hope this was informative!
Right now Javascript handles the input as a string, so age is a string. You're gonna want to convert that to an int using the function parseInt(age).
Official documentation
Also, I'd suggest you read this about types in JS
Use either parseInt(age) or parseFloat(age) depending on whether you want to accept non-integer ages.
Your prompt is returning your number as a string, so when you calculate 15 + 7 it's actually just concatenating "7" on to "15".
You need to convert your string to an number:
var age = prompt ("what's your age?");
age = parseInt(age,10); // Converts to an integer
// parseFloat(age) will allow fractional ages
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);
the age is going to be treated as string so string plus int result in string you have to convert age to int :
var age= parseInt(prompt("what's your age"));
updated...

Possible to treat singular Javascript var as an array?

Whilst I am sure there's a duplicate question of this out there, because I am unfamiliar with javascript, I don't know the proper term, and thus wouldn't know where to start searching for it (if I knew what it was called, I'd just read up about it).
I have a singular var (that is not an array) that contains a set of numbers:
var Latitude = Math.floor(Math.random()*90) + Math.random();
I want to encode all numbers contained in Latitude, including the numbers after the floating point (and including the floating point, and any minus signs - although note this code example doesn't add a minus sign) into an array of letters, so 0 = A, 1 = B, so on.
Is there any simple way of converting the singular var into an array of individual numbers for encoding?
First, slight typo in your question, Math.random is a function. You want to convert the number you get to a string, the easiest way to do this is to add an empty string - ''. Then just use the split function to break the string into an array:
var Latitude = ((Math.floor(Math.random()*90) + Math.random()) + '').split('');
var latitude = new Array();
latitude.value = Math.floor(Math.random*90) + Math.random();
latitude.push(2);//demonstrating that it's an array;
console.log(latitude.value);//for testing purposes only
console.log(latitude);//for testing purposes only
Now you can use latitude's value but also use it as an array.
edit Sorry, I seem to have misread your question. Graham's answer is correct. But this might help someone with a similar problem. I thought you wanted to use the same variable to store a value and an array.
Convert the value first to string (toString()) and then split it (split()):
var arr = Latitude.toString().split('')

Categories

Resources