Why is my Javascript increment operator (++) not working properly in my addOne function
Solution 1
There are two increment operators: prefix and postfix.
The postfix operator increments the variable after it is evaluated. For example, the following code produces 11, because it adds 5 and 6:
var a = 5;
(a++) + (a++)
The prefix operator increments the variable before it is evaluated. Sounds like that is what you want. The following code produces 13, because it adds 6 and 7:
var a = 5;
(++a) + (++a)
So your code should be:
function addOne(num) {
return ++num;
}
console.log(addOne(6));
Solution 2
That is not the correct use of ++, but also a lot of people would not recommend using ++ at all. ++ mutates the variable and returns its previous value. Try the example below.
var two = 2;
var three = two += 1;
alert(two + ' ' + three);
two = 2;
three = two++;
alert(two + ' ' + three);
two = 2;
three = two + 1;
alert(two + ' ' + three);
Solution 3
num+1 increments the number before the current expression is evaluted so log will be the number after increment, but num++ increments the number after the expression is evaluated, so log will log the num before increment then increment it.
if you like to do the same functionality as num+1 you may use ++num and it will do the same.
They both increment the number. ++i is equivalent to i = i + 1.
i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. See this question
Admin
Updated on June 21, 2022Comments
-
Admin almost 2 years
Please can someone explain to me why my addOne function doesn't work with the increment operator (++). Please see my code below.
// addOne Function function addOne(num){ return num + 1 } log(addOne(6)) => 7 // same function with ++ operator function addOne(num){ return num++ } log(addOne(6)) => 6 // Question - why am I getting 6 instead of 7 when I use ++ operator?