Why is my Javascript increment operator (++) not working properly in my addOne function [duplicate]
Asked Answered
A

3

10

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?
Anse answered 26/9, 2016 at 15:13 Comment(3)
The post increment operator does exactly what it should: it returns the original value and then increments the variable.Percival
at first it returns and then increments. use prefix notation in your caseTidwell
Your explanation makes absolute sense. Thank you so much.Anse
U
18

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));
Ulrikaumeko answered 26/9, 2016 at 15:17 Comment(1)
Thank you so much for your explanation. You really broke it down.Anse
M
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);
Militarism answered 26/9, 2016 at 15:38 Comment(0)
F
1

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

Ferrante answered 26/9, 2016 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.