I an working on a project for an Introductory Programming class so I'm using basic javascript. This is our first project with functions and for some reason I can't seem to make it work. I called all my variables and created the function before the program starts but for some reason it skips over running the function in my program. Any help would be appreciated.
This is just the beginning of my program, I don't wanna write the rest of the code until I figure out why this part is broken, thats why the program doesn't do anything but close the window if it doesnt pass the tests.
// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";
function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3) {
if (numTrees == 5, 10) {
answer = "yes";
} else if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
}
}
if (answer == "no") {
alert("You have entered an incorrect number too many times.\nThe Program will now end.");
window.open('', '_self', '');
window.close();
} else if (answer == "yes") {
return;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees); {
document.write("<br/> <br/>" + "End of Program.");
}
You have;
if(numTrees == 5, 10)
The erroneous comma is causing the if to evaluate the truthy expression 10 so its always passing the test, to test for 5, 6, 7, 8, 9 or 10;
if(numTrees >= 5 && numTrees <= 10)
The way you are using the comma in this line has a special meaning:
if(numTrees == 5, 10)
Essentially what this does is returns the value of 10 (the second operand) when cast to a boolean, which is not 0, so it is true.
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comma_Operator
You probably meant to use OR (||):
if(numTrees == 5 || numTrees == 10)
Or check numTrees against a range:
if(numTrees >= 5 || numTrees <= 10)
On a side note, in javascript it is recommended that you always use identity comparison (===) instead of regular comparison (==):
if(numTrees === 5 || numTrees === 10)
if(numTrees == 5, 10) doesn not mean If numtrees is equal to 5,6,7,8,9, or 10
change it to
if(numTrees >= 5 || numTrees <=10)
if (numTrees == 5, 10) {
answer = "yes";
}
This is an odd-looking construct that I've never seen before. I'm assuming you believe it means "is numTrees within the range 5 to 10?", but that's not the case. Without checking, I think it essentially means you're checking two things at once:
is numTrees equal to 5?
is 10? (this essentially means "is 10 not 0", which of course is always true).
Since the 2nd condition you're checking is always true, you're always setting answer to "yes". As a result, your loop always runs exactly once - it starts up, checks answer is "no", sets answer to "yes", and that immediately stops the loop.
You need to change your condition to if(numTrees >= 5 && numTrees <= 10)
What you want is something more like this:
if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
} else {
answer = "yes";
}
Related
I'm currently working on an assignment where a person must choose cave 1, 2 or 3. Everything works except the validation part. This function is used to see if the user put in a number lower than 1, higher than 3 or not even a number. I'm trying to use a while loop to fix my problem. I have tried putting a continue after between the third last and second brackets.
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
prompt("Which cave will you go in? 1, 2 or 3?");
if(number <= 1 || number >= 3){
break;
}
}
}
You need to store the second prompt return value in a variable.
Also, return value of prompt is always a string, so you need to parse it into an int too for proper comparison, although JS implicitly converts it for you.
//Gets input from the user
guess = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
valid(guess);
//Checks if the input is valid
function valid(number) {
while(isNaN(number) || number < 1 || number > 3){
alert("Please Try Again");
let number = parseInt(prompt("Which cave will you go in? 1, 2 or 3?"));
if(number <= 1 || number >= 3){
break;
}
}
}
You are not storing the prompt input in the function. Here is the solution with some modifications:
//Gets input from the user
guess = prompt("Which cave will you go in? 1, 2 or 3?");
valid(guess);
//Checks if the input is valid
function valid(number) {
let guess = number;
while(isNaN(guess) || guess < 1 || guess > 3){
alert("Please Try Again");
guess = prompt("Which cave will you go in? 1, 2 or 3?");
if(!isNaN(guess) && guess <= 1 && guess >= 3){
break;
}
}
}
change this line valid(guess); to valid(parseInt(guess));
Hello I'm new to javascript and trying to run the following
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else (age > 19) {
document.write("you can already drink");
}
I can't seem to get anything to show up but if I change my code to remove the else statement and change the === to just == my code runs. This is how it looks like when it runs after I get rid of the else statement and === operator.
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age == 19) {
document.write("you can finally drink");
}
I'm trying to get the first block of code to run but can't. The page is empty and no prompt shows up. Someone please help.
There are a few mistakes in your code:
1) prompt method return string no number, so :
Use == instead of === :
else if (age == 19) {
PS: (19 == '19'); is true but (19 === '19'); is false
OR convert age to number :
else if (Number(age) === 19) {
2) You should not use condition for else , so you must change else like this:
else { document.write("you can already drink"); }
var age = prompt("What is your age");
if (age < 19) { document.write("You can't drink"); }
else if (Number(age) === 19) { document.write("you can finally drink"); }
else { document.write("you can already drink"); }
Your problem is the last else statement. You are putting a condition after the else, which does not work. You only add the condition after another if. You can fix this by removing the condition like so:
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
You seem to be having some logical error in your last else statement. If none of the first 2 conditions are true, then logically speaking, the last condition must be true. else does not hold any conditions. It's simply just else in terms of the previous condition(s). Else you would have to use else if() again, but as mentioned earlier, in case neither of the conditions are true, then the last condition must be the case regardless in this example. Therefore, just else makes the most sense.
Example:
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
Another thing in terms of your operators. == means equal to, and can be used to compare different types. I.e. you can compare a number type to a string type, and if they both hold the same value, the statement will be true. However, === is a strict equals, and means that the things being compared must be the same value AND the same type.
Example:
var x = 5; //number
var y = '5'; //string
if(x == y) {
//true, because they are equal, both has the value 5
}
if(x === y) {
//false, because even though they are equal in value, they are not the same type
}
var a = 8; //number
var b = 8; //number
if(a === b) {
//true, because they are both equal, and the same type
}
So, to clearify,
== checks if the values are equal, no matter the type.
=== checks if the values are equal AND are of the same type.
More simple documentation on operators here.
Firstly you need to understant differnce between "==" and "===" . From this you can conclude
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]
And secondly "else" with a condition is always written as "else if" ...else is block which is runs when none of its above conditions is true i.e none is true ..read from here for more information
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.
What I have is:
var i = 0;
do {
i++;
console.log(i)
}
while (i <= 9);
if(i % 2 = 1) {
console.log("odd")
}
else {
console.log("even")
}
Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment
What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?
Thanks!
Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.
Difference between == and ===:
=== is more strict than == since === checks the value AND type whereas the == only checks the values.
Example:
if(1 == '1') // true
if(1 === '1') //false : their types are different.
Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.
Here is the final result:
var i = 0;
do {
i++;
console.log(i);
if(i % 2 === 1) {
console.log("odd");
} else {
console.log("even");
}
} while (i <= 9);
When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -
if(i % 2 = 1)
However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.
This should be your code -
if(i % 2 == 1)
Instead of = it should be == in the if condition.
you need to change if condition from if(i % 2 = 1)
to
if(i % 2 ==1)
if(i % 2 == 1) {
console.log("odd")
}else {
console.log("even")
}
Because == is for equality comparison while = is for assigning of value.
So the problem in you code is , you are using an assignment operator "=" in your if condition, instead use "==" (comparision operator).
You can find more information on comparision operators in Javascript here :
https://www.w3schools.com/js/js_comparisons.asp
Whenever I write a name with over 6 letters it still prints
that isn't a very long name
instead of
that's such a long name
I know this must be a basic question and that it might be pretty straightforward, but I just can't get it to work. I would appreciate any ideas on why it doesn't perform as it's supposed to.
let myName = prompt('What is your name?');
if (myName.length <= 3) {
document.write('That is such a short name!');
}
else if (3 < myName.length < 6) {
document.write('That isn\'t a very long name');
}
else if (myName.length >= 6) {
document.write('That\'s such a long name!');
}
else {
document.write('Nop');
}
One of your expressions isn't doing what you think it does.
else if (3 < myName.length < 6) {
Both 3 < myName.length and myName.length < 6 evaluate to true, so they'll almost always be hit.
To check for multiple conditions you need an "and" operator, which is && in Javascript
else if (myName.length > 3 && myName.length < 6) {
Notice how we've also flipped the expression so that myName.length is always first. This makes it easier to read aloud
if myName.length is greater than 3 and myName.length is less than 6...
I'd like to add that -- because you're using 'else' statements -- about half of your conditions are redundant.
Your first condition, for example, checks if the size of the string is less than or equal to 3; this is ok.
Your second condition, however, will only be tested if the length is greater than 3, so you don't have to check it again.
Here is a simplified version of your logic:
let myName = prompt('What is your name?');
if (myName.length <= 3) {
document.write('That is such a short name!');
}
else if (myName.length < 6) {
document.write('That isn\'t a very long name');
}
else {
document.write('That\'s such a long name!');
}
I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}