Simple javascript function not working as expected. Why? - javascript

For some reason, no matter what I bind to the variable theNumber, I still get the console outputting the first console.log() inside of the numberCheck(). I expected this to output the second console.log(), but it refuses. I have tried many different syntactical changes. Maybe I just don't understand the expression !Number.isNaN(). I thought that this meant if the number is a number than its true, but I might be wrong.
Keep in mind, I'm new. I understand terminology so feel free to communicate with whatever words. But my javascript logic is subpar.
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why won't this log');
}
}
numberCheck(theNumber)
numberCheck(12)
The output:
You picked a number
You picked a number
FIXED and Working as Expected:
let theNumber = 'god'
function numberCheck(x) {
if (isNaN(x)) {
console.log('You picked a number')
}
else {
console.log('why wont this log');
}
}
numberCheck(theNumber)
numberCheck(12)
The output:
why wont this log
You picked a number

In JS NaN is a value that differs from a type to another, basically NaN for strings, NaN for ints etc, what that method is doing is checking if the passed value is a NaN of type Number.

You have to cast the argument x to a number
let theNumber = 'god'
function numberCheck(x) {
if (!Number.isNaN(Number(x))) {
console.log('You picked a number');
} else {
console.log('why won\'t this log');
}
}
numberCheck(theNumber);
numberCheck(12);

Using "isNaN" function can be tricky sometimes (see this part of the documentation "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN").
Since it seems you want just verify if a variable is a number or not, you can make it that way:
var theNumber = 100;
function numberCheck(x){
if(typeof x === 'number'){
console.log('Nice you picked a number');
}else{
console.log('It is not a number');
}
}
numberCheck(theNumber);
"typeof" function will return the type of the variable "x".

Related

How come the if-statement is skipped when I am checking if a string is equal to a number?

I am trying to see if the user input is equal to a number, and if it isn't, then show a label saying, "Must be a number" and do not proceed until it is. I never learned about how to check if a string is equal to a number, so I searched it up and added it to my code, but it still doesn't work. Can someone look at it and tell me how I can fix my if-condition? Thank you in advance!
//variable that is used
var user_answer = getNumber("answer_input");
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN("user_answer") === false){ //here is where I tried to use it, but it just skips the condition
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
});
This is what I tried based on a comment and it still did not work:
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN(user_answer) === true){ //I forgot to specify that user_answer is a variable, but I even set the condition to equal to true and it did the same thing as before.
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
Okay, with the answer I got, the "mustBeNum_label" shows, BUT when the user inputs an actual number, it still shows "mustBeNum_label".
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (Number(user_answer)){
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
} else {
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
});
Try checking like this:
if (Number(user_answer) || user_answer == 0) {
// input is a number
} else {
// input is not a number
}
You can find out more here: Number - MDN
I would consider this a poor case for Number() since it will output NaN or a number.
Consider when you encounter 0: the conditional will run your else block since 0 is falsey.
Number.isInteger(Number(user_input)) may be a better solution since it will always output a boolean, and if it gets passed NaN will output false.
Shorter syntax would be Number.isInteger(+user_input)

Ordering arguements alphebetically and printing a number depending on the order

So I'm new to Javascript, just finished a small free online crash course that covers the bare bones basics but I'm still pretty clueless.
Found TwilioQuest that takes problems and gets the player to solve them in a game format.
One issue has me at the mercy of the same 11 lines of code.
The task is write a script that will take two command line arguments - a pair of strings that should be compared to see which one comes first alphabetically (letter casing is not important). The script should determine if the first string is before, after, or in the same position (equal) to the second string, alphabetically. For each case, you should print out a number with console.log.
When the first argument is earlier in the alphabet than the second, your script should print -1.
When the first argument is the same as the second, your script should print 0.
When the first argument is later in the alphabet than the second, your function should print 1.
This is what I have right now and I'm being told that its false or that it doesn't work
const firstValue = process.argv[2];
const secondValue = process.argv[3];
if ((firstValue.toLowerCase() < secondValue.toLowerCase())) {
console.log(-1)
};
if ((firstValue > secondValue)) {
console.log(1);
};
if ((firstValue.ignoreCase == secondValue.ignoreCase)) {
console.log(0);
};
I have tried nesting the conditional operator and I'm still told its wrong
You're only doing the case-insensitive comparison in the first condition. toLowerCase() doesn't modify the string, so you need to do it in all the comparisons.
But it's easier if you do it once when assigning the variables.
const firstValue = process.argv[2].toLowerCase();
const secondValue = process.argv[3].toLowerCase();
if (firstValue < secondValue) {
console.log(-1);
} else if (firstValue == secondValue) {
console.log(0);
} else {
console.log(1);
}
When you have a series of mutually exclusive tests, you should use else if and else so it doesn't perform unnecessary tests.
you can use charCodeAt() it provides the ascii value of a string character
const firstValue = process.argv[2];
const secondValue = process.argv[3];
firstValue.toLowerCase()
secondValue.toLowerCase()
if ((firstValue.charCodeAt(0) < secondValue.charCodeAt(0))) {
console.log(-1)
};
if ((firstValue.charCodeAt(0) > secondValue.charCodeAt(0))) {
console.log(1);
};
if ((firstValue.charCodeAt(0) == secondValue.charCodeAt(0))) {
console.log(0);
};
hope this solves your problem

How do I check if a variable is null, so that I can change it later on?

A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Javascript if else condition run time failure

I have started javascript today. Trying with the very basic and got stuck with If Else loop.
var input = prompt("type your name"); //variable stores the value user inputs
var outout = tostring(input); // the input value is changed to string datatype and stored in var output
alert(output);//supposed to display the value which it doesn't
if(output == "Tiger")
{alert("It is dangerous");
}
Else
{alert("all is well");
}//I only get a blank page
If I omit the line var output = tostring(input) and try to display the alert box with input value I get the alert box. But after that I only get a blank page. The If Else loop doesn't work at all. I am using notepad++. Also checked in Dreamweaver. There is no compile error. What am I doing wrong?
Sorry for such a basic question and thanks for replying.
Regards,
TD
Your line
tostring(input);
Should be
toString(input);
The toString() method has a capital S
Also, your output variable is called "outout". Don't know if that's a typo...
Not only that, your Else should also have a small e. All JavaScript keywords are case sensitive.
You do not have to convert the result of a prompt to a string, it is a string already. And it actually would be
input.toString()
And Else is lowercase, the correct would be else.
So you can use like this
var input = prompt("Type your name");
if (input == "Tiger")
{
alert("Wow, you are a Tiger!");
}
else
{
alert("Hi " + input);
}
Notice that if you type tiger (lowercase) you will end up on the else. If you want to compare a string case insensitive you can do this:
if (input.toLowerCase() == "tiger")
Then even tIgEr will work.
Your code has the following problems:
var input = prompt("type your name");
var outout = tostring(input);
// Typo: outout should be output
// tostring() is not a function as JavaScript is case-sensitive
// I think you want toString(), however in this context
// it is the same as calling window.toString() which is going to
// return an object of some sort. I think you mean to call
// input.toString() which, if input were not already a string
// (and it is) would return a string representation of input.
alert(output);
// displays window.toString() as expected.
if(output == "Tiger")
{alert("It is dangerous");
}
Else // JavaScript is case-sensitive: you need to use "else" not "Else"
{alert("all is well");
}//I only get a blank page
I suspect what you want is this:
var input = prompt("type your name");
alert(input);
if (input === "Tiger") {
alert("It is dangerous");
} else {
alert("all is well");
}

Categories