Skip to content

Instantly share code, notes, and snippets.

@olov
Last active December 22, 2015 08:18
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 olov/6443605 to your computer and use it in GitHub Desktop.
Save olov/6443605 to your computer and use it in GitHub Desktop.
funny little ES6 for (let;;) example
// according to my guesses of what is to come in future ES6 specs:
// the loop should execute five times so the program should print five numbers at the end
// the fresh-per-iteration x is captured in a closure (that will increment it by 3),
// then executed (for side-effects only) in the cond-expr and post-expr.
// it will never ever modify the outer x thus five loop iterations
(function() {
let arr = [];
let fn = null;
let cnt = 0;
for (let x = 0; (fn && fn()), x < 5; (fn && fn()), x++) {
console.log("loop iteration " + ++cnt);
fn = function() { console.log("incrementing x with value " + x); x += 3 }
arr.push(function() {
console.log(x);
});
}
arr.forEach(function(f) { f(); });
})();
// how many iterations?
// arr printout?
(function() {
let arr = [];
let fn = null;
for (let x = 0; (fn && fn()), x < 5; (fn && fn()), x++) {
console.log("loop iteration");
fn = function() { x += 1; }
arr.push(function() {
console.log(x);
});
}
arr.forEach(function(f) { f(); });
})();
(function() {
let arr = [];
let cnt = 0;
let fn = null;
for (let x = 0; (fn = function() { console.log("incrementing x with value " + x); x += 3 }), x < 5; (fn && fn()), x++) {
console.log("loop iteration " + ++cnt);
arr.push(function() {
console.log(x);
});
}
arr.forEach(function(f) { f(); });
})();
// this should terminate!
(function() {
let fn = null;
for (let x = 0; ((!fn && (fn = function() { ++x }))), x < 2; fn()) {
}
})();
// how many iterations?
// arr printout?
(function() {
let arr = [];
let fn = null;
for (let x = 0; x < 5; x++) {
console.log("loop iteration");
fn = function() { x += 1; }
fn(); fn();
arr.push(function() {
console.log(x);
});
}
arr.forEach(function(f) { f(); });
})();
Copy link

ghost commented Sep 4, 2013

alternate.js

"loop iteration 1"
"incrementing x with value 0"
"incrementing x with value 3"
"loop iteration 2"
"incrementing x with value 4"
"incrementing x with value 7"
"4"
"7"

Copy link

ghost commented Sep 4, 2013

yoyoma.js

The log:

option 1

loop iteration
loop iteration
3
6

option 2

loop iteration
loop iteration
loop iteration
loop iteration
loop iteration
2
3
4
5
6

@olov
Copy link
Author

olov commented Sep 4, 2013

get rid of that 7 and I agree with you (option 2). :)

Copy link

ghost commented Sep 4, 2013

Just noticed and removed it! Bad head math =/. But yeah, it makes sense.

@olov
Copy link
Author

olov commented Sep 4, 2013

linking to https://gist.github.com/olov/6443290 before nap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment