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

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.

Related

Javascript templete literals not working with random number generator

I'm trying to generate a random number and then if the user enters the same num he can move forward otherwise it will generate another random number. But the template literal to generate random num (a) is not working.
var a = Math.floor(Math.random()*10); // Random num generator
var userInput = alert('Enter the numbers: ${a}'); // User input
while ( userInput !== a){ // Loop
alert("Try Again!");
userInput = alert('Enter the numbers: ${a}');
};
There are a few things that can be improved in your code.
Naming your number variable a instead of n is confusing.
Math.floor can be shorted to ~~ in your case (not every case).
You get user input from prompt, not alert, which merely shows a message.
You're using the strict equality !== operator to compare your random number with the user's input, which will always be a number in String form. So even if they enter the correct number, it will be interpreted as incorrect, since '3' is not strictly equal to 3. You have to use != instead.
There's no need for a userInput variable since you're only doing one thing with it. Just inline the prompt inside the condition of the while loop.
Since n never changes, declare it with const so that if you accidentally try to change it later, you will get an error to bring this to your attention.
As someone noted in the comments, string literals use `, not '.
const n = ~~(Math.random() * 10);
while (prompt(`Enter the number: ${n}`) != n) {
alert('Try again!');
};

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)

What does the "Number" function do in 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.

Which is the safest way to discriminate 0 from empty string in JavaScript?

From user input, I receive a string which must contain numbers. 0 and empty string must be treated differently.
I've made this brief case study
0 == "" // true
parseInt(0) == "" // true
parseInt("") // NaN
parseInt("") == "NaN" // false
parseInt("") == NaN // false
typeof parseInt("") // "number"
With a bit of extra research I've made up this solution (considering uInput the user input)
function userInput(uInput){
var n = parseInt(uInput);
if (isNan(n))
// empty string
else
// 0 or number
}
It looks like it is able to distinguish 0 from empty string correctly in Google Chrome.
What I'd like to know is:
Is this the best/most efficient solution?
Is this solution compatible in any browser?
Is this even a solution at all? Is there any way n can become
something other than a number (considering uInput could be any kind of string)?
I wouldn't be asking this, but since empty string and 0 are treated the same (?!) I don't know to which other holes is my code potentialy exposed.
I'd do something like this:
var nmbr = parseInt(uInput, 10);
if (!isNaN(nmbr)) {
// Yay, valid input!
} else {
// Ups, weird input...
}
This seems the simplest and most correct answer, because parseInt only returns an integer or NaN.
I would go with the ===, try it like: 0 === "" // false
The difference about them and about type conversions read:
Q: Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?
Is this even a solution at all? Is there any way n can become something other than a number?
Yes. parseInt only does consider the first, integer part of the string when parsing it. It ignores the rest, so "12.34 oops" will still validate as 12.
I receive a string which must contain numbers
You can use a simple regex to test that:
/^\d+$/.test(uInput)
It will yield true for strings that consists of only (and at least one) digits, and false for anything else (non-numeric and empty strings).
Create your own test, you do like a million try for each and retrieve the time it takes.
For browser compatibility, I guess simple operation should be alike.
Try this:
function validate(uInput){
var regEx = /^[1-9]{1}[\d]*$/;
if (regEx.test(uInput))
alert(uInput + " is a valid number.");
else
alert(uInput + " is not valid number.");
var validNumber = parseInt(uInput);
}
0 == "" // true
because of == which does a type coercion first:
0 == false, "" == false so false == false.
you should be using ===, where
0 === "" // false
without type coercion.

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