Jay
Jay

Reputation: 21

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;}

Upvotes: 0

Views: 210

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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.

Upvotes: 10

Jonas Wilms
Jonas Wilms

Reputation: 138235

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;
}

Upvotes: 0

Related Questions