Returning undefined while calling same function - javascript

Here is my code
function secondval_prompt(firstval) {
var secondval = prompt("should be greater than 1st value");
if((secondval > firstval) && (secondval != "") && (!isNaN(secondval))) {
return secondval;
} else {
secondval_prompt(firstval);
}
}
var firstvalue = prompt("Enter 1st value");
var secondvalue = secondval_prompt(firstvalue);
alert(secondvalue);
If I gave the second value greater that first value on first time its returning the second value correctly.Once I gave the second value as wrong (less than first value) on first time and gave the correct value(greater than first value) on second time it return undefined...
Why its returning undefined on second attempt..
Demo link : http://jsbin.com/balufete/1/edit?js,output
Please try like this
First
Give first value as 100 &
Give Second value as 101
It will return 101
Second
Give first value as 100 &
Give Second value as 10 &
Again give Second value as 101
It will return undefined

You need to return the value from the recursive function as well.
return secondval_prompt(firstval);
Note that you are currently doing a comparison on the text values entered in the prompt. "5" will be considered higher than "10" due to their respective alphabetical order. You may want to parseInt the two inputs:
if(parseInt(secondval, 10) > parseInt(firstval, 10))
You should also apply firstval the same validity tests that you're currently applying to secondval. At the moment, your code will accept non-number values for firstval.

Related

comparing array position to prompt (javascript)

I'm trying to compare the input from a prompt window to the position of the correct answer in an array within an array.
This function logs the question and possible answers to the console. It then logs the correct answer, but does not recognize the input as correct ie. it will always show the else statement.
Code:
questionArray[randomQ].questionPrompt();
var currentQ = randomQ;
Question.prototype.answerPrompt = function(){
var tryQ = prompt("Enter number of the correct answer.");
if (currentQ === tryQ){
console.log('The correct answer is ' + this.answer)
} else {
console.log('Try again. ' + this.answer)
}
};
Console log. The final line comes after input of 0:
Question?
0) answer 0 - correct answer
1) answer 1
2) answer 2
Try again. 0
If I use
if (questionArray.answerArray[currentQ] === tryQ)
then the correct array item is found, and listed as undefined in a TypeError. How do I use that array item to compare to the prompt answer?
prompt will always return a string, so it won't be === to a number. Cast the prompt result to a number first.
You also probably want to exclude the empty string from defaulting to 0.
const guess = prompt("Enter number of the correct answer.");
const tryQ = guess && Number(guess);

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

Comparing values with leading zeros in Javascript

I have a javascript code that compares two values:
} else if (!(parseInt($('#form_value').val()) >= 1)){
alert("Error: You didn't pick a number!");
form_value in this case is 001, and I would like to compare it to the one, but it doesn't seem to work. I have tried using parseInt but it didn't work either. Any solutions?
Try:
if (!(Number(parseInt($('#form_value').val(),10)) >= 1)){
EDIT: try this shortened version:
if ( parseInt($('#form_value').val(),10) < 1){
Well, Number("001"); returns 1 and Number("000"); returns 0
based on your comment above
"I'm trying to display an error if the value is less than 1, the
lowest value a user can submit is 000 (which is loaded by default), if
you pick something, it becomes 001."
If the lowest possible value is 0 then just test for 0...
var thing = Number($('#form_Value').val());
if (isNaN(thing) || thing === 0) {
alert('an error message')'
}
May be you should change the condition to if ( +( $('#form_value').val() ) < 1 ) or just if (!+$('#form_value').val()).

Why using this method to return a function or value?

I'm just wondering why should I use this method to return a function :
clusters.prototype.get_local_storage_data = function(data_key) {
return +(this.localStorage.getItem(data_key) || 1);
};
What does the +() do there and why using that ? Is there a better way of returning the function or 1 if what the function gets is null ?
Using the + before a value forces that value to become a number. In the case above, the data key will be converted to a number (if it's found), or the number 1 will be returned. Either way, the result will be converted to a number.
+null; // 0
+"3.14"; // 3.14
+1; // 1
It's just ensuring that no matter what the output is, you will be returning a number.
The + is there to cast the result to a number -
typeof +"123" // "number"
The way it's implemented looks just fine, and doesn't need to be changed.
The + is just making sure the return value is a number or else 1 would be true and not the number one. It's a shortcut for:
Number( expression )

Categories

Resources