3 ms·
> Nothing is changed by creating a `const newStroke` and pushing it to the array. Not true. If you look carefully you will see the `const` and everything after
by neRok 2y ago
> Nothing is changed by creating a `const newStroke` and pushing it to the array.
Not true. If you look carefully you will see the `const` and everything after it is wrapped in curly braces, and those braces create a block...
> Traditionally (before ES6)... blocks with curly braces do not create scopes... [but] blocks are finally treated as scopes in ES6, but only if you declare variables with let or const. — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid...
So the curly braces with the use of const/let creates a new lexical scope, hence solving the issue. You can test it in the browser console to confirm;
var stack=[], cmd="";
cmd="success"; stack.push(()=>cmd);
cmd="fail"; stack.push(()=>cmd);
stack[0](); /* returns "fail" */
var stack=[], cmd="";
cmd="success"; {const c=cmd; stack.push(()=>c);}
cmd="fail"; {const c=cmd; stack.push(()=>c);}
stack[0](); /* returns "success" */
It's probably not a good idea to do it this way, because it's easily "overlooked". I would probably use a class or factory-function if I had the need.
- julik 2y agoTIL