Keep adding numbers into an array until a = 0 - javascript

Hi I'm new to javascript and I'm sorry if my question is silly for you.
This question was solved with the following code:
let arr = [12, 6, 53]
let a
do {
a = prompt("Enter a number")
a = Number.parseInt(a)
arr.push(a)
}
while (a != 0)
console.log(arr)
But, if I want that run the code if a == 0 rather than a != 0
i simply changed
while (a != 0)
into
while (a == 0)
But, it simply adds the number into the array
Can anyone please explain why this is happening?
I was expecting that the output should keep asking me to enter a number until a is equal to 0.
I'm a bit silly (Please explain me if I'm right or wrong) I think that running the code until a != 0 and a == 0 should give the same answer in this code

First off, stop using do..while. Its usages are very limited and 0.01% of use cases where it actually makes sense are simply not worth the trouble of having yet another syntax construct in your codebase.
In your case, the use of do is not justified, because you want to check the condition (a!=0) before you perform the action (arr.push), not after it. The right pattern here is "loop forever + break":
while (true) {
let a = prompt("Enter a number")
a = Number.parseInt(a)
if (a !== 0) {
break
}
arr.push(a)
}
Also note that 1) block-scoped variables belong inside the block, not outside it and 2) declaration without initialization (as in let a;) is a code smell and should be avoided.
Hope this helps.

Can anyone please explain why this is happening?
I was expecting that the output should keep asking me to enter a
number until a is equal to 0. I'm a bit silly (Please explain me if
I'm right or wrong) I think that running the code until a != 0 and a
== 0 should give the same answer in this code.
a != 0
Add items to the array if they do not equal 0 (else stop)
a == 0
Add items to the array if they equal 0 (else stop)
If you do not want the numbers that do not match adding to the array, then you need to also check this condition before inserting the value (before push).
let arr = [12, 6, 53];
let a;
do {
a = prompt("Enter a number");
a = Number.parseInt(a);
if (a == 0) {
arr.push(a)
};
}
while (a == 0);
console.log(arr);

Related

Appropriate way to check if 4 strings are duplicated in JS [duplicate]

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

javascript if else for beginners

I am very new to Javascript, so I am having a hard time figuring out this easy exercise and what I'm doing this wrong. Any help would be greatly appreciated!
You are given two numeric variables: var n = 25; var result = 0;
Their values may change when you submit.
DO NOT EDIT CODE ABOVE THIS LINE.
=================================
Your Challenge:
Using if and else, make decisions based on the values
of n and result with the following rules:
1. When n is even,
set the value of result to result's current value
plus 10.
2. When n is odd,
set the value of result to result's current value
minus the value of n.
3. Do not declare new variables.
4. Be sure your solution works for all values of n and result.
if (n%2 == 0) {result+10;} else {result-n;}
Your problem isn't if/else, the problem is you never set result to the new value. result+10 just results in the value without storing that value anywhere. (In many programming langauges, that would be a syntax error, but JavaScript allows what it calls ExpressionStatement where any expression can be a statement.)
Either use the compound assignment operators (+= and -=), or write a verbose assignment (result = ...).
Side note: It's easier to debug and edit code when statements are on their own lines, suggest:
if (condition) {
trueStuffHere
} else {
falseStuffHere
}
...or any of the several variations on that theme where trueStuffHere and falseStuffHere are on lines of their own.
You may set the result?
if (n%2 == 0) {
result = result + 10;
} else {
result = result - n;
}
Or if you're a bit better:
if (n % 2 == 0) {
result += 10;
} else {
result -=n;
}

Can you compare multiple variables to see if they all equal the same value in JS?

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

Simple arithmetic challenge function with limited attempts

Recently began studying Javascript, trying to read out of Javascript: The Definitive Guide and Eloquent Javascript, while going off on my own to experiment with things in order to really etch them in my memory. I thought a good way to get my head around arithmetic operations and conditional statements, I'd build a series of little games based around each Math operator, and began with addition.
function beginAdditionChallenge() {
var x = Math.ceiling(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
else {
alert("Fail.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
You can see the whole thing thus far on JSFiddle, here. The idea is that clicking the button generates a random number between 1 and 100, displays it to the user, then prompts them to provide two addends, giving them 3 attempts. If the sum of these addends is equal to the RNG number, it congratulates the user and ends the program. If they do not provide suitable addends, the loop prompts them to try again, until they've hit 3 attempts, at which point the program snarks at them and ends.
I know the event listener is not the failure point here, as when I change beginAdditionChallenge to simply display a test alert, it works, but I don't know what exactly is wrong with the loop I've created.
You did it correctly. However, Math.ceiling isn't a function and should be Math.ceil. In addition, your code (in jsfiddle) should be set to wrap in head. Why? Because right now you call initChallenge when the page loads. However, in your jsfiddle example, the code runs onLoad so the load event never gets called. Essentially, you're adding a load event after the page has loaded.
http://jsfiddle.net/rNn32/
Edit: In addition, you have a for loop that goes up to three. Therefore
else if (a + b !== x && i < 3) {
alert("Please try again.");
}
should be
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
because when i === 2, the user's last chance has ended.
Everything is fine. Just change:-
var x = Math.ceiling(Math.random()*100);
to:-
var x = Math.ceil(Math.random()*100);

Nested If-else statements being skipped

What I'm building is a game where the computer generates a random number (1-100) and the user must guess the correct number. The goal is for the computer to compare the current guess to the previous guess and spit out a statement: "hot", "cold", "hotter", "colder", etc.
My Code (focus on the JS): CodePen fiddle
//global variables--computer generated guess, and guess log
var answer = Math.floor((Math.random() * 100)+1);
var guessArray = [];
var index = 0;
//user clicks submit button and guess is registered by computer
$("#submit").click( function(){
var guess = $("#guess").val();
guessArray.push(guess);
//prints out the answer and user guesses
$("#answer").text("Answer:" + " "+ answer);
$("#guessArrayPrint").text("You guessed: " + " " + guessArray + " ");
if (answer === guess) {
$("#statement").text("woo hoo right answer");
} else {
var currentDifference = Math.abs(answer-guess);
var currentDiffArray = [];
currentDiffArray.push(currentDifference);
if (index = 0) {
//if-else statement comparing current guess range to answer
if ( currentDifference >=1 && currentDifference <= 10){
$("#statement").text("Ouch! You're hot!");
} else {
$("#statement").text("Brr! You're cold!");
}
} else {
//if-else statement comparing current guess to previous guess
var previousDiff = answer- prevguess;
var prevguess = guessArray [i-1];
if( previousDiff < currentDifference){
$("#statement").text("Ahh! Getting Warmer!");
} else {
$("#statement").text("Brrr...getting colder");
}
}
index++
}
});
My nested if-else statements are not working. When a user inputs a guess, no matter how close to the answer, it always returns the statement "brr.. getting colder", which is in the "else" section.
Ideally when the user inputs their first guess if (index = 0) should run then when the second guess is input, it should move to the "else" statement with the previous guess variables. I tried moving around the variables, changed orders of if/else, and thought maybe it's the placement of index++. Nothing is working. Not sure if something is wrong with my variables , arrays, or the syntax of my if/else statements.
tl;dr: when the program is run only the "else" portion of the nested if-else statement is run. Not sure how to fix… I've gone through my code a number of times. The syntax, the arrays, and variables. Uncertain what's wrong.
You JS has if (index = 0). This should be if (index === 0).
Additionally, you need to cast the value of your input field to a number. You can do this using:
var guess = +$("#guess").val(); // + cast as a number
More syntax errors:
prevguess = guessArray[i - 1] --> prevguess = guessArray[index - 1];
Here is a partial working Fiddle. I ran through some scenarios, and the fiddle really only works if you give the application the right answer. The code has many syntax errors, bad refs and calculations. I would suggest opening the console or a debugger, identifying those issue, and fixing them.
Here is a Fully Functional Demo.

Categories

Resources