Skip to content

Instantly share code, notes, and snippets.

@meandmax
Created September 11, 2014 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meandmax/13f8130d9830de45d559 to your computer and use it in GitHub Desktop.
Save meandmax/13f8130d9830de45d559 to your computer and use it in GitHub Desktop.
Try to find a generic way of incrementing a value without new assignments
// This doesn`t work, as val is a completly different value then count with own scope
var count = 0;
var increment = function(val){
val += 1;
}
increment(count);
console.log(count);
// doesn`t work because first assignment then incrementation
var value = 0;
var increment = function(otherValue){
value = otherValue++;
};
increment(value);
console.log(value);
// works but now I increment just value and if I pass something else to the function it is broke
var value = 0;
var increment = function(otherValue){
value = ++otherValue;
};
increment(value);
console.log(value);
// Best suited for the generic case, works fine for me, and I can pass what ever I want
var obj = {value: 0};
var increment = function(obj){
obj.value++;
};
increment(obj);
console.log(obj.value);
// Optimisation of the example above, without increment operator
var obj = {value: 0};
var increment = function(obj){
obj.value += 1;
};
increment(obj);
console.log(obj.value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment