What is wrong with my switch statement here? - javascript

Trying to output how a user inputted number compares to the number 117, very simple, yet I somehow am doing something wrong?
let output = "";
//
//input Number here
let userNumber = 117;
function calcUserNumberFunc(indvNumber) {
switch (indvNumber) {
case userNumber === 117:
return `the number ${userNumber} is equal to 117.`;
case userNumber > 117:
return `the number ${userNumber} is greater than 117.`;
case userNumber < 117:
return `the number ${userNumber} is less than 117.`;
default:
return `Invalid, or not whole number.`;
}
}
output += calcUserNumberFunc();
document.getElementById("app").innerHTML = output;

While your code is syntactically correct (ie. doesn't throw any errors), you are not using [switch][1] the way it's intended.
switch (expression) { ... } evaluates expression and matches its values with the value you provide in the cases. In your code, you are not doing anything with that parameter.
What's actually happening, is that you are comparing indvNumber against the results of your comparisons (eg. userNumber === 117) and since all of them are bools (true or false) you are basically comparing indvNumber against true or false.
That said. For your use case, you actually what to use [IFs][2] statements to compare all your cases.
Also, when you are calling the function calcUserNumberFunc() you are not passing any parameter so indvNumber is undefined which evaluates to false (as is a [falsy value][3]) that's why in your code you will always be getting the number ${userNumber} is greater than 117.;. userNumber > 117 is false and is compared against indvNumber which is undefined.
[3]https://developer.mozilla.org/en-US/docs/Glossary/Falsy

You can refactor your code to this and it will help to make the function more reusable.
//input Number here
let inputNumber = 117
// Assuming userNumber is the input Number and indvNumber is the number to be compare
function calcUserNumberFunc(userNumber, indvNumber = 117) {
if (userNumber === indvNumber) {
return `the number ${userNumber} is equal to ${indvNumber}.`;
}
if (userNumber > indvNumber) {
return `the number ${userNumber} is greater than ${indvNumber}.`;
}
if (userNumber < indvNumber) {
return `the number ${userNumber} is less than ${indvNumber}.`;
}
return `Invalid, or not whole number.`;
}
document.getElementById("app").innerHTML = calcUserNumberFun(inputNumber);
You can now pass input Number directly as userNumber parameter
Eg: calcUserNumberFunc(116) and it will return the number 116 is less than 117..
You can also overwrite 117 to different number if you ever need to change it for example comparing user input to 120 instead.
Eg: calcUserNumberFunc(120, 120). This should return the number 120 is equal to 120.

Related

getting wrong answer for finding largest of 2 numbers using readline-sync in js [duplicate]

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

While loop for odd or even

Ask user for a number. Determine if the number is even or odd. I have my constants set and using modulo to figure this out. However I am stuck in an infinite loop and can't figure out why. I have my if statement in the loop as well as a break statement to get out, but still in an infinite loop.
HAVE TO USE A WHILE LOOP
// declare constants
const MODULO = 2;
const EVEN = 0;
const ODD = 1;
// declare variables
var enteredNumber;
var result;
// prompt user to enter an even number
enteredNumber = prompt("Enter an even number: ");
// convert user input into a number
enteredNumber = Number(enteredNumber);
// determine result of modulo equation
result = enteredNumber % MODULO;
// while loop to check if enteredNumber is even or odd
while (result === EVEN) {
document.write(enteredNumber + " is an even number <br/>");
enteredNumber = prompt("Enter an even number: ");
enteredNumber = Number(enteredNumber);
result = enteredNumber % MODULO;
if (result === ODD) {
document.write(enteredNumber + " isn't an even number");
break;
}
}
You can essentially one-liner this thing. You're already checking stuff with the while.
document.addEventListener('DOMContentLoaded', () => {
while (!(parseInt(window.prompt('Enter an even number', '2') || '1', 10) % 2)) { };
});
Why this works
Javascript has 'falsy' and 'truthy' values.
window.prompt('Enter an even number', '2')
This code prompts the user for a number. The result is a string (or null, if the user blanks out the prompt).
<a string or null> || '1'
If the user blanked out the prompt, it will return null. In Javascript we can use the or operator to choose between two things. null || '1' reads from left to right. The first thing is falsy so it chooses '1'.
If the user entered a number (like 10), we would get the number they entered as a string.
Then we parse the string to a number with parseInt.
Take that result and use the modulo operator % to divide by the operand and return the remainder. When you divide by 2 the remainder will either be 0 or 1. These are falsy/truthy values.
while(0) evaluates to false and breaks the loop. while(1) evaluates to true and continues the loop.

Why does a string with 300 in it compared against a string with 1000 in it return false in Javascript?

In my React project I am currently filtering data by price, using the min and max. In my max price conditional I check if the max price is empty or if not I check to see if the price for the current data can pass the filter
( !this.state.max_price.trim() || listing.price <= this.state.max_price )
I noticed that it will work when entering a max price for every number that doesn't exceed 1000, but as soon as a number 1000 or higher was entered it failed, and return false so I tested out the conditional in jsfiddle to see if I was missing something. Below I got an unexpected result
// I put this in jsfiddle, and it returned false
if ("300" <= "1000") {
alert('true')
} else {
alert('false')
}
I also put this code below in jsfiddle and was met with a result I expected (as you can see it is working for numbers below 1000 but not 1000 and above)
// I put this in jsfiddle, and it returned false
if ("300" <= "500") {
alert('true')
} else {
alert('false')
}
you are comparing strings, and "300" is lexographically greater than "1000"
console.log("300" < "1000");
console.log(300 < 1000);
In string comparison in JavaScript (mostly any language), strings are compared by their ASCII values, and since the ASCII value for "3" (51) is greater than that of "1" (49) 51>49 hence "300">"1000".
You can convert the string variables to numbers using the unary + oprator +"1" => 1:
var a = "300";
var b = "1000";
if (a <= b) {
console.log('true')
} else {
console.log('false')
}
a = +a; // convert to number using the unary '+' operator
b = +b;
if (a <= b) {
console.log('true')
} else {
console.log('false')
}

Matching float and string value in javascript not matched

I am using this code
if(total == balance)
{
alert("test ok");
}
else
{
alert("test failed");
}
here total=10; and balance=10.00; but the result is "test failed".
Hmm... I may not be exactly correct, but I think total is taken as an integer and balance is taken as a decimal. Try the === function instead of the == function.
The === function converts the values and then checks them.
So checking if a value is true or false depending on whether it is 0 or 1 requires the === operator to convert both into the same type of values.
And the == function just checks whether two values are equal, just by looking at the present value of it. No conversion. So if I want to check the values of two int values, I will use ==.
There are two ways to solve this problem.
One is by changing either the total into a decimal, by giving it a value of 10.00 with a decimal or changing the balance into an int by giving it a value of 10, without the decimal places.
The other is the better one, and you just have to replace your == with a ===. So your code would look like this:
if (total === balance) {
window.alert("test ok");
} else {
window.alert("test failed");
}

Integer validation not working as expected

Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.

Categories