What does the "Number" function do in JavaScript? - javascript

var num = Number(prompt("Pick a number", "0"));
if (num < 10)
alert("Small");
else if (num < 100)
alert("Medium");
else
alert("Large");
I'm just confused about what the Number is doing in this code.
What will happen if I make it like this:
var num = prompt("Pick a number", "0");

Number converts the passed value to a number value. Examples:
> Number(10)
10
> Number("10")
10
> Number(true)
1
> Number("0x11")
17
> Number("foo")
NaN
It performs explicit type conversion to a number.
There is also String and Boolean which do basically the same, but convert to a string and boolean instead.
What will happen if I make it like this ...
prompt will always return a string value. However, in your specific example, it wouldn't actually make a difference because the relational comparison operator (<) will perform the same type conversion implicitly. I.e.
a < 10
// is the same as
Number(a) < 10
Still, I'd say it's good practice to perform explicit type conversion, since it makes it clearer in the rest of the code what type you expect.
Note: It is also possible to call Number with new, i.e. new Number(...), however, that will return a number object instead of primitive number value. This is rarely used.

Related

Javascript: Why won't my values equal up? [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 5 years ago.
var check = true;
var number = Math.floor(Math.random() * 20);
while (check === true){
var guess = prompt("I picked a number 0 to 20, try to guess it!");
if (number === guess) {
print("You guessed correctly! Good job!");
check = false;
}
else if (number < guess) {
print("\n\You guessed too high!");
}
else if (number > guess) {
print("\n\You guessed too low!");
}
else {
print("\n\Error. You did not type a valid number");
exit();
}
print("\n\Guess: " + guess + ".");
}
When I try running this program, I get all the way up to the correct answer, but it doesn't work! Even if the randomly generated number is 13, and I guessed 13, it would go through and it would say it is invalid.
Your guess is a string. It is the text entered by the user you need to convert it into a number in order to be able compare it with your guess so replace
var guess = prompt("I picked a number 0 to 20, try to guess it!");
with
var guess = Number(prompt("I picked a number 0 to 20, try to guess it!");
This will turn your guess from your user into a number or a special value NaN if it isn't formatted correctly.
You could also use the == operator which will automatically convert between types. I would recommend against using the operator if you are new to javascript as it can have some confusing and unexpected behaviors.
You are comparing the return value of prompt (a string) with the return value of Math.floor (a number).
Since you are using === and they are different data types, you'll never get a match.
Use == or explicitly cast the number to a string or vice versa.
number === +guess
=== is strictly typed so it will not compare the int to a string.
Convert guess to an integer. You should first validate it though in case the user inputs something other than an int.
var guessInt = +guess; // the plus converts to an integer
if(isNaN(guessInt))
continue;
if (number === guessInt) {
print("You guessed correctly! Good job!");
check = false;
}
You are using the triple = operator which checks for type equalness too. when you compare the prompt value (your guess variable) to your number variable. you are comparing a String and a Number. To make this work you could use
number == guess
or
Number(guess)
You’re using strict equality comparison, which also compares types.
prompt returns string values. Use parseInt to cast to a number.
var guess = prompt("I picked a number 0 to 20, try to guess it!");
guess = parseInt(guess, 10);
The second parameter tells the number base (10 is for decimal, 16 for hexadecimal, etc.). In non strict mode (aka sloppy mode) you may experience accidental conversion to octal (base 8) when parsing strings with a leading zero. Always specify the base to avoid this.
You might want to learn more about JavaScript strict mode.

javascript the difference between the number 01 and 1

I am writing a function that needs to be able to tell the difference between the numbers 01 and 1. I am doing a cubical search within a company directory and on the same floor there are cubicles numbered 01 and 1. When the cubical search returns 01 it automatically assumes the value is a 1 and not '01'.
Is there a method or something I could use to differentiate between '01' and '1'.
Thanks.
There is no difference between the numbers 01 and 1. They are absolutely identical.
console.log(01 === 1);
There is a difference between the strings "01" and "1". If you need to distinguish between the values, then use strings, not numbers.
console.log("01" === "1");
Is there a method or something I could use to differentiate between '01' and '1'.
Yes, string comparison.
When you treat these two values as strings then these two values will be different
var isEqual = '1' === '01'; // false
Only by converting them to numbers will they evaluate the same and be indistinguishable.
These aren't really NUMBERS, they are CHARACTER STRINGS, whose characters all happen to be digits.
I presume that you are doing a "cubicle search" - a search for a cubicle (those little pens that companies keep people in), rather than some sort of mathematical search that involve cubes
You will treat both inout as strings. Consider this:
var x = "01";
var y = "1";
var z;
if (x === y) {
return true;
} else {
return false;
}
Note there is a difference between == (value only) and === (value and type)

Why does Number < String returns true in JavaScript?

EDIT: I will rephrase my question, I type Number < String and it returns true, also works when I do typeof(2) < typeof("2").
Number < String => true
typeof(2) < typeof("2") => true
I'm guessing it is the value of ASCII characters of each letter in Number and String but I am not sure if that is the reason this is returning true, and I want to know why does this happens, what processes or how does the interpreter gets to this result?
First answer:
The charCodeAt() method returns the numeric Unicode value of the character at the given index. Read here
Now if you do not specify any index position then character at 0th index is considered. Now, S ASCII value is 83 and N ASCII value is 78. so, you are getting those number. Check here.
And 78 < 83 => true is obvious.
Try "String".charCodeAt(1) and you will get 116 which is ASCII value of t
Second answer based on OP's edited question:
Frankly speaking your comparison Number < String is "technically" incorrect because Less-than Operator < or any similar operator is for expressions, and Number and String are functions and not expressions. However #Pointy explained on how Number < String worked and gave you results.
More insight on comparison operators
Comparison operators like < works on expressions, read here. Typically, you should have a valid expression or resolved value for RHS and LHS.
Now this is the definition of expression, read more here - "An expression is any valid unit of code that resolves to a value. Conceptually, there are two types of expressions: those that assign a value to a variable and those that simply have a value."
So, (x = 7) < (x = 2) or new Number() < new String() is a "technically" valid/good comparison, even this Object.toString < Number.toString() but really not Object < Function.
Below are rules/features for comparisons, read more here
Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two distinct objects are never equal for either strict or abstract comparisons.
An expression comparing Objects is only true if the operands reference the same Object.
Null and Undefined Types are strictly equal to themselves and abstractly equal to each other.
The result of
Number < String
is not the result of comparing the strings "Number" and "String", or not exactly that. It's the result of comparing the strings returned from Number.toString() and String.toString(). Those strings will (in all the runtimes I know of) have more stuff in them than just the strings "Number" and "String", but those two substrings will be the first place that they're different.
You can see what those actual strings are by typing
Number.toString()
in your browser console.
JavaScript does the following thing:
"String".charCodeAt(); => 83
"S".charCodeAt(); => 83
"String".charCodeAt(0); => 83
The method charCodeAt(a) gets the char code from position a. The default value is 0
If you compare N > S you will get 78 > 83 => true
For the complete String Javascript calculates the sum of all ASCII char codes.
So I can answer your question with yes.

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

Why do strings sometimes get changed to numbers in javascript?

I have this code:
function getSessionGUID() {
return (S4()+S4());
}
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
It clearly returns a string, but if you run it a bunch of times, you can notice that it sometimes returns infinity.
for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log("INFINITY"); }
871 x INFINITY
I then noticed that if you remove the |0, it solves the problem:
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
Results:
for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log("INFINITY"); }
undefined
Why does this happen? In both cases the value is changed into a string.
You are generating hexidecimal strings.
When you use the == operator, the interpreter tries to coerce the two values to the same data type. When comparing strings to Infinity, that intermediate data type is Number. When those strings contain the letter "e" (a valid hexidecimal digit) and they're coerced to a Number, javascript interprets this as 10^x which ends up as some huge number.
Numbers in javascript are 8 bytes, so anything larger than 1.7976931348623157e308 is considered equal to Infinity.
The easiest way to fix this is to change your == to === so the string doesn't get coerced to a number.
if(getSessionGUID() === Infinity)
http://jsfiddle.net/Uhkxm/
This test reveals the answer:
for (var i = 0; i < 100000; i++){
var x=getSessionGUID();
if(x == Infinity) console.log(x); }
}
It logs values like 61e93284 or 1413e390
These values are valid numbers and they are way too big for the Number type, so they get cast as Infinity when interpreted as a number.
If you replace == with === in the test, no conversion occurs and nothing is logged. The conversion is caused by the == operator.
I think I figured it out. There's actually nothing wrong in all of this, except on my test code.
If you take this string "11e51354", you can get it to assert to true since Javascript checks for all the types that could make it equal to true.
"11e51354" == Infinity # True
The right test would be:
"11e51354" === Infinity # False
It's still a string, but somehow while I was sending it through a GET request, it was being transformed into a number type which gave Infinity.
JavaScript is dynamically typed. There isn't an integer, floating point. String data type. All of that conversions is done internally depending on the context.
The + could be string concatenation or addition depending on context.
Edit: Apologies. Too late. But it was the == performing the conversion to number when comparing against infinity. In some cases, you generated valid numbers.
If you really need a number type, you always could use following.
console.log(Number("1"));

Categories