Difficulties getting an if...else statement to work inside a function - javascript

I know I am very close, but I can't get the code to return anything but the 'savesTheDay' variable in the else option.I don't think I'm setting up my if....else conditionals properly. I think should be going with the "happy ending" for the if statement (in my case, the savesTheDay variable? Should I not define 'dangerLevel' inside the function since I want it to change? Thanks!
**Edited:
I am trying to get each of the phases to return when I call the assessSituation function. I can only get the saveTheDay message to return, even if the value is outside of the parameters of the condition i.e. assessSituation(1);. I'd expect to get the "Meh. Hard Pass." return value instead of saveTheDay.
Added new code, still isn't running though!**
function assessSituation (dangerLevel, saveTheDay, badExcuse) {
var saveTheDay = "Crime won't stand a chance against me!";
var dangerLevel = dangerLevel;
var badExcuse = "I'm scared, I've never gone up against this many villains";
if (10 < dangerLevel < 50) {
console.log(saveTheDay);
} else if (dangerLevel > 50) {
console.log(badExcuse);
} else
console.log("Meh. Hard Pass.");
}

JavaScript, like many other languages (C/C++, Java, etc.) except Python, does not have support for chaining comparison operators.
10 < dangerLevel < 50
is equivalent to
(10 < dangerLevel /* true or false */) < 50
(true) < 50
// or
(false) < 50
Since false == 0 and true == 1, the result will always be true since 0 and 1 are both less than 50.
To fix your logic, use the && (AND) operator:
if ((10 < dangerLevel) && (dangerLevel < 50))

I think it's only returning saveTheDay because it's the only conditional that is matched.
Your dangerLevel = 10, so dangerLevel is not > 50, and it's not smaller than 10, but it's definitely < 50. If you want another return you can change dangerLevel before if else clause.
Ps: I didn't see that your variable inside your function has the same name of the input. You should choose another name if you want to have both

If you’re passing dangerLevel into the function, you’re overwriting it when you create the dangerLevel variable inside the function. Remove “var dangerLevel = 10” and see if the output you get is what you expect.

you are setting dangerLevel = 10;
it doesn't matter what you pass in, 10 gets populated for dangerLevel, so:
10 will never be > 50
will never be <10
wil always be < 50
which is why you always get savesTheDay

You have two conflicting conditons. (dangerLevel<50) and (dangerLevel<10) so when your code runs with dangerLevel=10 its doesn't know wich one to choose. I suggest you remplace (dangerLevel<50) to (10<=dangerLevel<=50)

Related

Return only the values if not inside the array in for loop

This array contains 1,5,
let numberArray = [1,5];
I'm trying to print numbers from 1 to 280 except for the values inside the numberArray,
for (let i = 1; i < 281; i++) {
numberArray.forEach((number) => {
if (number != i) {
console.log(i);
}
});
}
I'm expecting the result to be 2,3,4,6,7...280 without printing 1 and 5 in this case. But I get like this,
It prints 2 times each number except 1 and 5. I want to completely omit the values inside the numberArray and print the other values. Really appreciate it if somebody could point me to the bug. Thanks.
It isn't a bug, your code is doing exactly what you are telling it too.
You have your for loop which happens 280 times and then you have a forEach loop inside that which is happening twice every time the loop goes around. So the Foreach loop is actually happening. 558 times.
You can just use the .includes method to check i doesn't exist within the numberArray.
for (let i = 1; i < 281; i++) {
if(!numberArray.includes(i)){
console.log(i);
}
}

BEGINNER HERE If/else statements with booleans 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;}

Setting variable to existing value versus return?

In Javascript, I have a function that sets a variable. If the function tries to set the variable to its current value, is it more "efficient" to break out of the function, or let the function re-set the variable's value?
Example
var a;
function setStuff(x) {
if (a == x) { return; }
a = x;
}
versus
var a;
function setStuff(x) {
a = x;
}
This function will be called on page scroll, so it will be called at a high frequency.
I don't think the issue is "efficiency".
I do however think there's a practice at play here, which is to generally not manipulate values outside the scope of the function. Having many functions like these in your application will drive you nuts, wondering which function is changing what.
Instead return a new value.
var setStuff = function() {
return newValue;
}
var a = setStuff();
I wrote a simple test snippet:
var a;
function setStuffCheck(x) {
if (a == x) { return; }
a = x;
}
function setStuff(x) {
a = x;
}
function benchmark(func){
var startTime = Date.now();
var callCount = 1000000;
for(var i = 0; i < callCount; i++){
func(10);
}
console.log((Date.now() - startTime) + "ms for "+callCount+" calls setting always the same value");
startTime = Date.now();
for(var i = 0; i < callCount; i++){
func(i);
}
console.log((Date.now() - startTime) + "ms for "+callCount+" calls setting always different values");
}
benchmark(setStuffCheck);
benchmark(setStuff);
By copying and pasting it in the console (Firefox 46.0.1), I have something like this:
138ms for 1000000 calls setting always the same value
216ms for 1000000 calls setting always different values
77ms for 1000000 calls setting always the same value
78ms for 1000000 calls setting always different values
So the second way seems to be always better. But the results may be different on each computers. However, the difference is noticable only for 1 millions of calls (try changing it to 1000, there'll be no differences).
The second option makes more sense to me and is more viable as there is very less logic written as compared to the first one as it is checking whether two values are equal or not , whereas in the second option its just re-assigning the variable to a new value.
if condition is always slower compared to when just assigning a new value . So i think you should go with second option.
There are potentially two factors that will likely drown out any practical performance difference between the two options. In practice, I would suggest that you use the version that is the easiest to understand and explain to others. I think that would probably be the unconditional update but it would be more up to you.
The two things that are likely going to obfuscate any real differences are:
What else are you doing in the function
What effect branch prediction has on your conditional.
Now, specifically to the question of what version is faster. I have set up the following test with each option executed a million times with 10 runs of each test. The global is set to itself 1 in 10 times but you can change that to some other frequency by setting aNew
var a = 10;
var ittr = 1000 * 1000;
function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function set1(x){
if (a === x){ return; }
a = x;
}
function set2(x){
a = x;
}
for (var j = 0; j < 10; j++){
var start = performance.now();
for (var i = 0; i< ittr; i++){
var aNew = a - 10 + getRandomIntInclusive(1,19);
set1(aNew);
}
console.log("conditional : " + (performance.now() - start));
}
for (var j = 0; j < 10; j++){
var start = performance.now();
for (var i = 0; i< ittr; i++){
var aNew = a - 10 + getRandomIntInclusive(1,19);
set2(aNew);
}
console.log("unconditional : " + (performance.now() - start));
}
Your results may vary but the I see conditional set() averages about 18 after settling down. The unconditional about the same, maybe 17.5.
Note that the vast bulk of the time here is taken by the call to random(). If you consistently just set the global to itself both functions time at around 1.8 rather than 18, suggesting that whatever else you might do in your set() is likely to obfuscate any performance difference.
The two do not have necessarily have identical results. Consider this series of calls:
var a;
function setStuff(x) {
if (a == x) { return; }
a = x;
}
setStuffCheck(0) ;
setStuffCheck('0');
console.log(a);
Output is not '0', but 0.
For a good comparison, the setStuffCheck function should use the strict equality operator ===.
In my tests in FireFox I see the performance of both functions show very little difference. setStuffCheck seems to take slightly more time to execute than setStuff when the argument has a different value than a, but it is the opposite (also slightly) when the values are the same. The difference in either way is in the order of 2%, which is the kind of fluctuations you get anyway on a typical device/PC for other causes, that have nothing to do with the code.
Anyway, this also means that this slight performance difference will depend on how often you expect to call the function with an argument that is equal to a.
However, the difference is only noticeable when you would do hundreds of millions of calls. If you don't have that many calls, then don't even bother and choose for setStuff.

If statement reiterates when values are same

I have this Javascript/jQuery code:
for (i = 0; i < 100; i++) {
if(!(html == $("#chat-box").html()))
{
$("#chat-box").html(html);
console.log("a");
}
}
I have this iterating on a for loop 100 times. You would think that at least after the 1st time it would stop iterating unless one of the two values changed (which they don't), but it does not. I do not know why. I tried using if(htm1 != ...) and that did not work.
I believe using the text() method for your comparison will area the issue:
if(!(html == $("#chat-box").text()))
{
$("#chat-box").html(html);
}
Reason being is that jQuery processes the text to prevent issues with special characters with html(), where as with text() it returns the raw value. If it still doesn't work, console.log() out both method return values and the comparison variable to better visualize.
Your variable html is never being initialized or assigned to. What is it's value? With only the code you provided, it's value is undefined. So when you try to do this:
$("#chat-box").html(html);
What happens is this:
$("#chat-box").html(undefined);
Which has no effect. But if you were to initialize html first, it works:
var html = 'stufffff';
for (i = 0; i < 5; i++) {
if(html !== $("#chat-box").html()) {
$("#chat-box").html(html);
console.log("a");
}
}
Also, you should use !== instead of !=.

javascript (nodejs) while loop bug

running the following code in nodejs cli:
var my_function = function() {
var next_value = 1
, value = undefined
, difference = undefined
, prev_difference = undefined
while ((typeof prev_difference === 'undefined') || (prev_difference > 0)) {
value = next_value
next_value = 2
difference = next_value - value
if (difference > prev_difference) {
throw new Error('Diminishing')
}
prev_difference = 0
}
return next_value
}
for (var i = 0; i< 300; i++) { console.log(i); console.log(my_function()) }
At iteration 282 of the loop I start getting the value '1' instead of '2'. Can't for the life of me understand why. This chunk of code is a reduction from something else I've been working on, hence the seemingly unnecessary if statement within the loop. There are a few ways to change this code such that the execution path does not get screwed up, but I'd like to understand why it's breaking with the current setup.
Also, if you have any tips for tools that could aid me in debugging something like this in the future I would be very grateful. For the most part I used console.log to narrow this down.
node.js version v0.8.6. Running on Mac OSX version 10.7.5.
Thanks
If you take out the IF statement it is gonna be fine, it will return only '2' on every iteration. The variable prev_difference is 'undefined' every time and this seems to cause issues.

Categories