BEGINNER HERE If/else statements with booleans JAVASCRIPT - javascript

I am having some trouble with this current lesson on control flow with JavaScript...
The question states:
In this exercise, you will be given a variable, it will be called value.
You will also be given another variable, it will be called greaterThanFive.
Using an 'if statement' check to see if the value is greater than 5. If it is, re-assign the boolean true.
code with stars next to it is the code I was given.
**let greaterThan5 = false;**
if (value > 5 ) {
console.log("That is true");
}
**return greaterThanFive;**
I have tried a number of different ways on how to write the correct code but it obviously is not right.
I tried assigning var value = 10;and then finishing the code as above but it says value has already been assigned. I have tried changing the boolean to let greaterThanFive = true;
The hint only tells me that "should return boolean value equal to 10" and "expected true to be false"
Please help, I have been working on this simple code it may seem for a week and do not want to move on to the next lesson without fully understanding this question.
Thank You!

You have two different variables; greaterThan5 and greaterThanFive.You also have a return statement, which will only work inside of a function.
I believe what you're looking for is something like the following, which passes a value into the function, then checks whether the value is greater than five or not, setting the variable to true inside of the if conditional if it is. The function then returns the greaterThan5 variable's truthiness:
function greater(value) {
let greaterThan5 = false;
if (value > 5) {
greaterThan5 = true;
}
return greaterThan5;
}
console.log(greater(10));
console.log(greater(3));
Which can be further simplified to a simple one-line return statement:
function greater(value) {
return value > 5;
}
console.log(greater(10));
console.log(greater(3));

So, the first clue in the code is the return statement. That means you are likely being asked to write a function that, given some value, checks to see if that value is greater than 5.
Let's define it using your existing code:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
console.log("That is true");
}
return greaterThan5;
}
So right now, we're always going to return false. All you need to do is reassign the value of greaterThanFive if value > 5. So, you can simply do that in your if-statement:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
greaterThan5 = true;
}
return greaterThan5;
}
You can now test your code by calling the function with various values:
isGreaterThan5(1); // returns false
isGreaterThan5(5); // returns false
isGreaterThan5(6); // returns true
And we're done!
I'm wondering if what confused you was the use of let. You might want to read more about var, let, and const.

if (value > 5) {greaterThanFive = true;}

Related

Cannot complete the cycle of functions in my javascript code when manipulating the DOM

Being a beginner, I am trying to get my function to run my game code again after checking the answer and then running the level it was on. I have a function to calculate the sum of two numbers, and then I have another function to check the sum adds up to the correct answer and then runs the game again. I can get it to work out the sum, and say if it is correct of not, but I cannot seem to get it to run the game again.
In the function, I had tried creating a variable that gets elements by their class name, so it returns an array like object, to which I then used a for of loop to iterate through to check if an elements attribute is identical to a string and if so to then assign the string to the index of the loop. I would prefer to try run an if else if statement to return the sum of the numbers and then the string, so the other function I call this function in, can see the level but because its not a global variable it cannot see it, so I have been trying to go about storing the attribute data as a level with another variable but I cannot seem to get my head round it and how to get it right.
The function to check the sum of the two numbers and then the level
function calculateAnswer(operand1, operand2) {
operand1 = parseInt(document.getElementById("player-number").value);
operand2 = parseInt(document.getElementById("computer-number").innerText);
let levels = document.getElementsByClassName("levels");
for (level of levels) {
level.addEventListener('submit', function(gameType) {
if (this.getAttribute("data-entry").innerText === "level-one") {
gameType = "level-one";
} else if (this.getAttribute("data-entry") === "level-two") {
return [operand1 + operand2, "level-two"]
} else if (this.getAttribute("data-entry") === "level-three") {
return [operand1 + operand2, "level-three"]
}
})
}
return [operand1 + operand2, levels];
}
The function to then calculate if the answer is correct and run the gam again
function checkAnswer() {
let goalTarget = parseInt(document.getElementById("num-target").innerHTML);
let calculatedAnswer = calculateAnswer();
let isCorrect = goalTarget === calculatedAnswer[0];
if (isCorrect) {
alert("Well done, you got it right :D");
playerScore();
} else {
alert(`Sorry, that is incorrect, your total adds up to ${calculatedAnswer[0]}, try again`);
computerScore();
}
runGame(calculatedAnswer[1]);
}

My input-function in javascript always return false, even when a user inputs the correct value

I want to know why my function always returns false, and how I can fix it.
At first I thought it had something to do with my syntax at check = ("stairway to heaven"===value || "Stairway to heaven"===value);. But no matter how I put it, it's always false.
I tried reading into this, but as far as I could understand, it doesn't help me.
I've created this in JavaScript to do different things depending on if the result of check is true or false.
else if (textNodes[15].id === 16 && nextTextNodeId === 16) {
showSongContainer();
if(check) {
showTextNode(17);
}
if (!check) {
textElement.innerText = 'That’s superwrong! Maybe if you would use that small brain of yours you’d figure it out!';
showTextNode(11);
}
The above code runs this function first, to determine if a text input returns true (stairway to heaven) or false (anything other than stairway to heaven):
function showSongContainer() {
songContainer.style.display = 'unset';
const songInput = document.getElementById('songInput');
const songButton = document.getElementById('songButton');
songButton.addEventListener('click', (e) => {
e.preventDefault();
let value = songInput.value;
check = ("stairway to heaven"===value || "Stairway to heaven"===value);
});
}
However, when the first else ifstarts (in the first codeblock), it always goes to the if(!check), before the text input has even been entered. Why is this? And how do I make it so that it returns the first if (in the first code block) if the text input is correct, and the other if, if incorrect?
I also have let check = ''; in a global scope at the beginning of my code, if that has anything to do with it.

Javascript: For Loop, need help understanding this exercise with if/else

I have this exercise that already got the answer, but after hearing the explanations, still don't understand. This is the exercise:
"write a function isUniform() which takes an array as an argument and
returns true if all elements in the array are identical"
This is the solution
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
}
return true;
}
I got it almost right, but i did a else statement with the "return true" and it didn't work. Why does it work with the "return true" outside of the for loop?
(edited) This is how i did the first time:
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
else {
return true;
}
}
}
If you return true outside the loop, then it checks every element in the loop until one matches the if test or it gets to the end of the loop.
If you return true inside the loop then it will always hit a return statement for the first element and then stop the loop.
I got it almost right, but i did a else statement with the "return
true" and it didn't work
The solution below would return the wrong results in some cases because all it does is find the first element within the array that's equal to first variable and return true, even though it hasn't searched the entire array.
function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
else {
return true;
}
}
}
I have this exercise that already got the answer, but after hearing
the explanations, still don't understand.
let's assume this is your array:
[10,10,13,10,10]
let's assume this is the variable first:
first = 10;
The if statement below which is within the for loop basically says if the variable first ( 10 ) is not equal to the element at the current index i (nth number within the array) then return false. This makes sense because if at this moment the variable first is not the same with the element at the specified index for example index 2 (number 13) then there is no point to carry on. Hence, it will return false.
if (numArr[i] !== first) {
return false;
}
now let's assume the array is:
[10,10,10,10,10]
let's assume this is the variable first:
first = 10;
now the variable first will be compared against each elementwithin the array and it says "is 10 not equal to the current element". in this case that's false because 10 is equal to 10. This will propagate down the array and control will never pass inside the if block. Eventually, control passes down to the return true statement.
if (numArr[i] !== first) {
return false;
}
It works because is the final statement in your function. Basically your function will return true if the condition inside for loop will not be triggered
Let's say you've got a broken printer which once in a while messes the printout. Now you printed 20 copies and want to know if every paper is fine. So now you would have to iteratively compare every copy until you found one which is not matching (and know it's time to get a new printer?). Or you've gone the way through the hole stack and know every copy is fine (and you've wasted time for nothing).

If block of conditional logs a message, but a variable is still being set in the else block

So I have this javascript function, reOrderJSON, and it orders an array, and, if the argument, order equates to "reverse", it reverse the array right after it has been sorted.
I also have a function bound to the click event of an associated link.
function reOrderJSON(subj,att,order,limit){
subj.sort(function (a, b,order) {
a = a[att],
b = b[att];
return a.localeCompare(b);
});
if(order === "reverse"){
subj.reverse();
console.log("Reverse passed a parameter to reOrderJSON")
}
layoutDate(subj,limit)
return depos = subj;
}
function clickReorder(e){
var orderingLink = e.target;
var reverseOrder = "";
var order = $(orderingLink).attr('data-order');
if(order === "desc" || order === "undefined"){
$(orderingLink).attr('data-order','asc');
console.log("Order detected as "+order)
reverseOrder = false;
}else{
$(orderingLink).attr('data-order','desc');
console.log("Order detected as "+order)
reverseOrder = "reverse";
}
var limit = $('.entries-per-page').val();
reOrderJSON(e.data.orderedObject,$(e.target).data('assoc'),reverseOrder,limit);
$('.result th').css('background','transparent');
$(orderingLink).closest('th').css({'background':'pink'});
return false;
}
$('.result').on("click", "th a", { orderedObject: depos }, clickReorder);
The link looks like this at the start:
<th>County</th>
As you can tell, I'm logging some debug text to tell what's going on. The first time I click a link, I always get these two lines returned in the log:
Order detected as undefined
Reverse passed a parameter to reOrderJSON
I don't understand how this is happening, order should not be passed as "reverse" the first time. What am I missing here?
depos is an array object, if that makes any difference.
Your comparison
order === "undefined"
is currently checking for the string "undefined", but you actually want to be checking for an undefined value in a variable.
You really want:
order == undefined // no quotes -- it's not a string
Or, even better:
typeof order == "undefined"
since undefined can be overwritten in non-strict mode.

JavaScript: Do I need a recursive function to solve this problem?

In this fiddle http://jsfiddle.net/5L8Q8/28/, if you click the black button, it randomly selects one of two values (red or blue) from an array. The randomly selected value is assigned to ran. In my real life application, there will be 16 elements in that array.
If you the pink "playagain" button, it chooses a random element from the same array but I want to make sure it's not the same one chosen as last time.
Therefore, when I click playagain, I assign ran to lastran and compare it to the next randomly chosen value from the array and, if they are the same, choose randomly again. However, the way I have it isn't guaranteeing that (upon the completion of playagain) ran is different.
I think I need a recursive function where comment 2 is in the code below, but I keep breaking my code when I try to create it.
Can you comment on the 3 comments in the code below?
Note, I'm a relative newbie, so this code is probably awful...
$("#playagain").click(function(){
lastran = ran;
ran = getRandom(myArray, true);
if (ran === lastran) {
ran = getRandom(myArray, true); //1. do I need to return this?
//2. want to test ran === lastran again.. How to set up recursive function?
} else {
return; //3.is this the right thing to do here?
}
});
while( (ran = getRandom(myArray, true)) === lastran)
;
Is what you want. The statement
ran = getRandom(myArray, true)
does not only set ran to getRandom(), but returns the value of ran. (This is a fairly common idiom in JavaScript, a carry over from C.)
So your full code can be:
$("#playagain").click(function(){
/*var */lastran = ran;
while( (ran = getRandom(myArray, true)) === lastran)
;
// update UI here
});
You can use a while loop instead of the if.
while(ran == lastran)
{
ran = getRandom(myArray, true);
}
It'll keep trying until it gets a different value.
After each run, simply remove that "key" from array and push lastran to the end of it. Then the updated getRandom function as following could be used both for #button and #playagain. http://jsfiddle.net/ghostoy/5L8Q8/32/
function getRandom(array, getVal) {
var key = Math.floor(Math.random() * array.length),
value = array[key];
if (lastran) {
array.push(lastran);
}
array.splice(key, 1);
lastran = value;
if (getVal) {
return value;
}
return key;
}
I think your approach is not the best way to deal with this. In theory you could get the same number many times in a row making this a 'slow' algorythm and you are making it more complex than needed.
An alternative approach in text:
- if no previous element has been picked pick a number between 0 and the number of elements in your array (16) otherwise pick a number between 0 and #elements-1 (15)
- if the chosen element is greater or equal to the last element picked add 1 to it
- store this index number as the last picked element
- return the array[picked-element]'s value
You could make getRandom itself recursive:
function getRandom(array, getVal, lastRan) {
var key = Math.floor(Math.random() * array.length);
if ((!getVal && key == lastRan) || (getVal && array[key] == lastRan))
return getRandom(array, getVal, lastRan);
return getVal ? array[key] : key;
}
Call it passing the last random value:
getRandom(myArray, true, lastran)
It works like this. You always pass getRandom the last random value that was retrieved. In the first conditional, we check to see if we just generated a duplicate of this value (either using the key itself or its corresponding value in the array, depending on whether getVal is true). If so, we return the result of calling getRandom again, once again passing the last random number that was used. This can happen as many times as necessary.
When one of these calls to getRandom produces a new number, then the expression in the first conditional will be false. In this case, we return the wanted value (via the second return statement) and all of the recursive calls to getRandom are "unrolled". (Remember, we returned the value of each call to getRandom at each step.)

Categories