Skip to content

Instantly share code, notes, and snippets.

@getify
Last active January 9, 2018 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/cfe112c06b22634fc302c2915681bbc4 to your computer and use it in GitHub Desktop.
Save getify/cfe112c06b22634fc302c2915681bbc4 to your computer and use it in GitHub Desktop.
horribly convoluted bug, badly illustrated. **NOTE: this is not the real code, it's an ugly illustration of kinda what the bug was in my real code.
var y;
foo();
// values: 3 10
// value: 4 10
// *******************************
function foo() {
for (let i=0; i<2; i++) {
let obj = { x: 2 }; // <-- bug because of `let` here
bar(obj);
setTimeout(function(){
obj.x = 10;
},100);
}
}
function bar(obj) {
setTimeout(function(){
y.x++;
console.log(`values: ${y.x} ${obj.x}`);
},1000);
y = Object.assign({},obj);
}
var y;
foo();
// values: 3 2
// value: 4 10
// *******************************
function foo() {
for (let i=0; i<2; i++) {
var obj = { x: 2 }; // <-- no bug because of `var` here
bar(obj);
setTimeout(function(){
obj.x = 10;
},100);
}
}
function bar(obj) {
setTimeout(function(){
y.x++;
console.log(`values: ${y.x} ${obj.x}`);
},1000);
y = Object.assign({},obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment