scoping issues with const in a loop
See original GitHub issueI’m not sure if const is actually supported, but it does not error (however results are not expected).
when using const in a for…of loop in ejs the first value is all that is used for the rest of the iterations.
sample code:
test.js -
var ejs = require('ejs');
console.log(ejs.render(require('fs').readFileSync('test.ejs', 'utf8'), {
arr: [{
name: 'apples',
color: 'red'
}, {
name: 'apples',
color: 'green'
}, {
name: 'banana',
color: 'yellow'
}]
}));
test.ejs -
<% for( var foo of arr ) { %>
<div><%= foo.name %> - <%= foo.color %></div>
<% } %>
<% for( const bar of arr ) { %>
<div><%= bar.name %> - <%= bar.color %></div>
<% } %>
result -
<div>apples - red</div> <div>apples - green</div> <div>banana - yellow</div> <div>apples - red</div> <div>apples - red</div> <div>apples - red</div>
If this is expected behavior (or const is outright not supported and I missed that note) I apologize for wasting everyones time. I haven’t tried let because node doesn’t like it outside of strict yet (actually throws an error).
using ejs 2.4.1
Issue Analytics
- State:
- Created 7 years ago
- Comments:8
Top Results From Across the Web
'const' scope in for loop JavaScript [duplicate] - Stack Overflow
Just to confirm what block scoping is, this code is totally valid, {const x=1; {const x=2; { const x = 3; }}} as...
Read more >ES6 Variable Declaration & For Loops — Why 'const' works in ...
Const is special, because variables defined with it are constants that can't be reassigned or redeclared.
Read more >Why is it possible to use Const variables in for...of loops?
var has some weird (uncommon) scoping that doesn't really have any benefits, and only causes issues in certain situations. It's like saying you ......
Read more >Incorrect work of 'const' inside while loop - PTC Community
The problem lies deeper: it turns out that in the context of the Rhino JavaScript engine, a loop scope is not a closure...
Read more >Block scope with let and const - Dave Ceddia
const is block-scoped, just like let . The only difference is that it can't be reassigned or redeclared. You also must give it...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
yes it seems to be a node issue. My apologies. v5.2.0 also suffers from it, v6.0.0 is working as expected.
My bad.
good to know, this was a kick in the butt to stop being lazy and upgrade my node version.