Increment a Number with JS

Increment a Number with JS
0

#1

Tell us what’s happening:

Your code so far


var myVar = 87;
// Only change code below this line
++myVar;

Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Mobile Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript/


#2

Yes, ++myVar, should also work, but I guess the test is set up to accept it if the operator follows the variable, like in the example.


#3

I agree with @kevinSmith, it’s probably got to do with how the testing environment is expecting to see the answer. However, it is worth noting that ++var and var++ aren’t technically the same.

++var returns the immediate increment of the var whereas var++ initially returns the original variable without being incremented

More reading for you: https://stackoverflow.com/questions/6867876/javascript-i-vs-i


#4

An example of what @huntinghawk1415 is referring to would be the following. Let’s say I have a global variable named globalCount and initialize it to 0. Let’s also say I want to create a function named newCount which increments the value of count by 1 and returns the new value of count. See the code below which uses the ++ operator before count to achieve this

var count= 0;

function newCount() {
  return ++count;
}
console.log( newCount() ); // displays 1

Now consider the same function but using count++

var count = 0;

function newCount() {
  return count++;
}
console.log( newCount() ); // displays 0

The above code returns the value of count before incrementing the value of count.