While loop keep looping even though expression is false - javascript

My loop is not quitting when i enter 10. Please help me.
let getGuessess = function(){
let guessedNum = null;
while(guessedNum !== 10){
guessedNum = prompt(`enter number $`);
if(guessedNum === "quit"){
break;
}
}
}
getGuessess();

Change from !== to !=. You're doing a strict equality check on 10 vs '10'.
or !== '10'

Maybe these links can help:
https://www.w3schools.com/js/js_comparisons.asp
I see there that:
!== means not equal value or not equal type
https://www.w3schools.com/jsref/met_win_prompt.asp
And here that, for the prompt function:
Return Value: A String.
I think that it doesn't work because you are comparing a string and an int, they are different types, so your comparison returns False even if you enter 10.

Related

unexpected results in evaluation of chains logical expressions javascript

I am writing a program to identify special numbers according to the criteria laid out in this code wars kata:
http://www.codewars.com/kata/catching-car-mileage-numbers
Here is a link to my full code and tests:
http://www.codeshare.io/UeXhW
I have unit tested my functions which test for each of the special number conditions and they appear to be working as expected. However, I have a function:
function allTests(number, awesomePhrases){
var num = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros(num) || sameDigits(num) || incrementing(num) || decrementing(num) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
which determines if any of the criteria of being a special number is met and that's not working as expected. For example, when I tested the allZeros() function on 7000 it returned true, but alltests(7000) is returning false. Is there something about how chains of logical expressions are evaluated that I don't understand or is the problem something else?
I have looked at W3schools and MDN to try and diagnose the problem.
Change all your !== to != will do.
False results as long as allTests() executes with a second argument even it it's the empty string, as follows:
allTests(7000,"");
If the function is called with just one argument, i.e. the number, expect this error:
Uncaught TypeError: Cannot read property 'length' of undefined
The error message refers to one of the functions in the logic chain, namely matchPhrase() which expects two parameters: number and awesomePhrases. If instead of providing an empty string, you use null, you'll also get the same error message.
JavaScript doesn't support the concept of default parameters -- at least not in a way that one might expect; the parameters default to undefined. But there is a way to work around this hurdle and improve the code so that one may avoid this needless error. Just change matchPhrase() as follows:
function matchPhrase(number, awesomePhrases){
awesomePhrases = typeof awesomePhrases !== 'undefined' ? awesomePhrases : "";
for(var i = 0, max=awesomePhrases.length; i < max; i++){
if(number == awesomePhrases[i]){
return true;
}
}
return false;
}
The first statement accepts the second argument's value as long as it is not the undefined value; if so, then the variable gets set to the empty string. (Source for technique: here).
To make the code more readily comprehensible, I suggest rewriting allTests() as follows, so that the code follows a more explicit self-documenting style:
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros( arrDigits ) || sameDigits( arrDigits ) || incrementing( arrDigits ) || decrementing( arrDigits) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
This function takes a number and uses its toString() method to convert the number to a string. The resulting string which is not visible will split itself on the empty string so that the result of arrDigits is an array of numerical strings, each one consisting of just one digit. This is the point of origin for the ensuing problem with allZeros() which compares a stringified digit with a number.
Incidentally, in the function allTests() there is an awfully lengthy ternary expression. The syntax is fine, but you might wish to rewrite the code as follows:
function getCriteriaStatus(arrDigits,number,awesomePhrases) {
var criteria = new Array();
criteria[0] = allZeros( arrDigits );
criteria[1] = sameDigits( arrDigits );
criteria[2] = incrementing( arrDigits );
criteria[3] = decrementing( arrDigits);
criteria[4] = palindrome(number);
criteria[5] = matchPhrase(number, awesomePhrases);
var retval = false;
for (var i=0, max=6; i < max; i++) {
if ( criteria[i] == true ) {
retval = true;
break;
}
}
return retval;
}
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
var criteria_met = getCriteriaStatus(arrDigits,number,awesomePhrases);
return (number > 99 && criteria_met);
}
To obtain the desired true result from allTests() when it invokes allZeros(), rather than complicate the code by using parseInt(), I suggest rewriting allZeros() and any other functions containing code that compares a numerical string value with a number by changing from the identity operator to the equality operator. The change involves merely replacing === with == as well as replacing !== with !=. The code that compares values of the same data type, using the identity operators, those operators may, and probably should, remain unchanged. (See here).

isFinite of space giving true value

I am trying to validate a price field. I was trying this:
var productId = document.getElementById("productId");
var productName = document.getElementById("productName");
var productPrice = document.getElementById("price");
alert(isFinite(productPrice.value));
if(isNaN(productPrice.value)||!isFinite(productPrice.value)){
error = document.getElementById("priceError");
error.innerHTML = "Please enter correct value";
productPrice.style.border="thin solid red";
}else{
error = document.getElementById("priceError");
error.innerHTML = "";
}
The line alert is giving me true when the input is space/ multiple spaces only.
This is my HTML page.
<td>Price</td>
<td><input type = "text" id = "price" size = "14"/></td>
Thanks
Why this happens i cant say, but this code should solve the problem
isFinite(parseFloat(" ")) // false
// because -->
parseFloat(" "); // => result NaN
// tested in Chrome 27+ on Win7
in the MDN refernce of isNaN here
it says
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
Update:
in the Reference of isFinite found Here it states that isFinite only returns false if the argument is:
NaN
positive infinity, (Number.POSITIVE_INFINITY)
negative infinity (Number.NEGATIVE_INFINITY)
In any other Case it returns true. (like Paul S mentioned)
Now i Think i got all loose ends, and in that course learned something. :)
with window.isFinite, you must be aware of the issues that window.isNaN suffers from when coercing types.
window.IsNaN Summary
Determines whether a value is NaN or not. Be careful, this function is
broken. You may be interested in ECMAScript 6 Number.isNaN.
Examples
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN
// This is a false positive and the reason why isNaN is not entirely reliable
isNaN("blabla") // true: "blabla" is converted to a number. Parsing this as a number fails and returns NaN
In ECMAScript 6 there are new methods Number.isNaN and Number.isFinite that address these issues. (of course these are not available in many browsers)
Number.isFinite is equivalent to
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
So as a solution, you would need to consider something like this (cross-browser).
Note: this solution will still allow you to enter hexadecimal or scientific notations, "0xA", "1e10"
Javascript
function isFinite(number) {
return typeof number === "number" && window.isFinite(number);
}
function trim(string) {
return string.replace(/^\s+|\s+$/g, "");
}
var price = document.getElementById("price");
price.onchange = function (e) {
var evt = e || window.event,
target = evt.target || evt.srcElement,
value = trim(target.value) || "NaN",
number = +value;
console.log("number:", number);
console.log("isFinite:", isFinite(number));
}
On jsfiddle
You could do it using reqular expression.
Try this.
function validatePrice() {
var el = document.getElementById('price');
if (
el.value.length < 14 &&
/^ *\+?\d+ *$/.test( el.value )
)
{
return true;
}
return false;
}
This function checks if the input is positive integer. I didnt know if you want floated values also.
If you do, switch the regex to this /^ *+?\d+((.|,)\d+)? *$/

What causes isNaN to malfunction? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 9 years ago.
I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:
function isNumerical(value) {
var isNum = !isNaN(value);
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
on these values:
isNumerical(123)); // => numerical
isNumerical("123")); // => numerical
isNumerical(null)); // => numerical
isNumerical(false)); // => numerical
isNumerical(true)); // => numerical
isNumerical()); // => not numerical
shown in this fiddle: http://jsfiddle.net/4nm7r/1
Why doesn't isNaN always work for me?
isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!
It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.
You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.
Anyway you can fix your code by simply doing this:
function isNumerical(value) {
var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"
return isNum ? "not numerical" : "<mark>numerical</mark>";
should be:
return isNum ? "<mark>numerical</mark>" : "not numerical";
See updated fiddle:
http://jsfiddle.net/4nm7r/1/
Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:
var isNum = !isNaN(parseFloat(value));
Just keep in mind the following kinds of outputs from parseFloat:
parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN
(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)
I suggest you use additional checks:
function isNumerical(value) {
var isNum = !isNaN(value) && value !== null && value !== undefined;
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
If you would like treat strings like 123 like not numerical than you should add one more check:
var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number');

Comparing NaN values for equality in Javascript

I need to compare two numeric values for equality in Javascript. The values may be NaN as well.
I've come up with this code:
if (val1 == val2 || isNaN(val1) && isNaN(val2)) ...
which is working fine, but it looks bloated to me. I would like to make it more concise. Any ideas?
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
Nothing to improve. Just add the parentheses to make it clear to everyone.
Avoid isNaN. Its behaviour is misleading:
isNaN(undefined) // true
_.isNaN (from Underscore.js) is an elegant function which behaves as expected:
// Is the given value `NaN`?
//
// `NaN` is the only value for which `===` is not reflexive.
_.isNaN = function(obj) {
return obj !== obj;
};
_.isNaN(undefined) // false
_.isNaN(0/0) // true
Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:
both undefined
both null
both true or both false
both strings of the same length with the same characters in the same order
both the same object
both numbers and
both +0
both -0
both NaN
or both non-zero and both not NaN and both have the same value
e.g. Object.is(NaN, NaN) => true
Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if ( val1 === val2 )
If either one or both are NaN it will evaluate to false.
Also, NaN !== NaN
As long as you know these two variables are numeric, you can try:
if (val1 + '' == val2 + '')
It turns the two values into strings. A funny answer, but it should work. :)
NaN is never equal to itself no matter the comparison method, so the only more concise solution for your problem that I can think of would be to create a function call with a descriptive name for doing this rather special comparison and use that comparison function in your code instead.
That would also have the advantage of localizing changes to the algorithm the day you decide that undefined should be equal to undefined too.
And what's about the function Number.isNaN() ? I believe this must be used whenever is possible.
> NaN === NaN
false
> Number.isNaN
ƒ isNaN() { [native code] }
> Number.isNaN() === Number.isNaN()
true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
For Numeric cases the solution is fine but to extend it to work for other data-types as well my suggestion would be as follows:
if(val1 === val2 || (val1 !== val1 && val2 !== val2))
Reason being global isNaN is erroneous. It will give you wrong results in scenarios like
isNaN(undefined); // true
isNaN({}); // true
isNaN("lorem ipsum"); // true
I have posted a comprehensive answer here which covers the NaN comparison for equality as well.
How to test if a JavaScript variable is NaN
Why not an if statement like this?
if (isNaN(x) == true){
alert("This is not a number.");
}
Equality comparison with NaN always results in False.
We can go for the javascript function isNaN() for checking equality with NaN.
Example:
1. isNaN(123) //false
2. var array = [3, NaN];
for(var i = 0 ; i< array.length; i++){
if(isNaN(array[i])){
console.log("True ---- Values of " + i);
} else {
console.log("false ---- Values of " + i);
}
}
Results:
false ---- Values of 0
True ---- Values of 1
Found another way using Array.prototype.includes MDN link. Apparently, [NaN].includes(NaN) returns true for NaN.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
Or we can go with davidchambers' solution which is much simpler.
function IsActuallyNaN2(obj) {
return obj !== obj;
}

type checking in javascript

How can I check if a variable is currently an integer type? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)
A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.
You can test if the variable contains a number, and if that number is an integer.
(typeof foo === "number") && Math.floor(foo) === foo
If the variable might be a string containing an integer and you want to see if that is the case:
foo == parseInt(foo, 10)
These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:
js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
A number is an integer if its modulo %1 is 0-
function isInt(n){
return (typeof n== 'number' && n%1== 0);
}
This is only as good as javascript gets- say +- ten to the 15th.
isInt(Math.pow(2,50)+.1) returns true, as does
Math.pow(2,50)+.1 == Math.pow(2,50)
A clean approach
You can consider using a very small, dependency-free library like Issable. Solves all problems:
// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error
// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')
define({
primitives: 'number',
nameOfTyping: 'integer',
toPass: function(candidate) {
// pre-ECMA6
return candidate.toFixed(0) === candidate.toString()
// ECMA6
return Number.isInteger(candidate)
}
})
is(4.4).custom('integer') // throws error
is(8).customer('integer') // returns true
If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.
function test (string, boolean) {
// any of these below will throw errors to protect you
is(string).string()
is(boolean).boolean()
// continue with your code.
}
I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.
function isFloat( x )
{
return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}
Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.
Ex.
alert(isFloat(5.2)); //returns true
alert(isFloat(5)); //returns false
alert(isFloat(5.0)); //return could be either true or false
Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:
function isInt(x) {
return typeOf(x, 'Number') && x % 1 == 0;
}
The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2
You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
Try this code:
alert(typeof(1) == "number");

Categories

Resources