Using javascript closures for context in loops - javascript

Is it bad practice to make a jQuery closure simply for the purpose of retaining context?
Example:
{
testFunction: function() {
//Instantiate variables etc...
for (var i = 0; i < columns.length; i++) {
for (var j = 0; j < columns[i].length; j++) {
// create a closure so the .then callback has the correct value for x
var func = function() {
var x = new testObject(columns[i][j].Id);
// find method returns a jQuery promise
x.find().then(function() {
// use x for some logic here
});
};
func();
}
}
}
}
In this case the closure is needed so that the function for the jQuery promise has context for what x is. Otherwise the x variable is changed after the next iteration of the loop. The jQuery promise object gets the value of whatever x was in the last iteration of the loop.
I'm looking for best practices here, just wondering what to do to keep code simple, readable and efficient.
Please note any performance issues that come along with closures/not using closures. References are appreciated.

Using a closure is definitely a good practice, but you can simplify it a little:
Pass in the object directly to your closure.
Use an IIFE instead of a named function declaration.
for (var i = 0; i < columns.length; i++) {
for (var j = 0; j < columns[i].length; j++) {
(function(x) {
x.find().then(function() {
// use x for some logic here
});
}( new testObject(columns[i][j].Id) ));
}
}
Note: you could simplify this code a little by using jQuery's $.each() method, but using a regular for loop is way faster.

jQuery (or ES5) iterators usually lead to cleaner code compared to loops. Consider:
$.each(columns, function() {
$.each(this, function() {
var x = new testObject(this.Id);
x.find().then(function() {
// stuff
});
});
});
Note that the scoping problem doesn't arise here, since you get a new scope on every iteration automatically. To address the performance question, iterators are slower than loops, but in the event-driven world you hardly need to worry about that.

Unfortunately there is no a better way to solve the problem. However, you miss to pass i and j:
for (var i = 0; i < columns.length; i++) {
for (var j = 0; j < columns[i].length; j++) {
// create a closure so the .then callback has the correct value for x
var func = function(i, j) {
var x = new testObject(columns[i][j].Id);
// find method returns a jQuery promise
x.find().then(function() {
// use x for some logic here
});
};
func(i, j);
}
}

It is ok and it's actually the only way to create a context.
Unfortunately for some reasons I don't really understand there are Javascript engines that limit the number of nested levels of functions you can create to very low numbers so just try to use them only when really needed (e.g. I found that my quite powerful Galaxy S4 with Android only can handle 18 nested levels).
For hand-written code this is not an issue normally, but for generated javascript code it's quite easy to get past those untold limits.

Related

javascript /jquery for loop doesn't work with extremely complicated expression

I have this javascript:
<script>
$("#P1").on("blur", function(){$("#Y1").val(getClass(this));});
$("#P2").on("blur", function(){$("#Y2").val(getClass(this));});
$("#P3").on("blur", function(){$("#Y3").val(getClass(this));});
$("#P4").on("blur", function(){$("#Y4").val(getClass(this));});
<script>
It's written in jquery. I want to tokenize it in a for loop. I have tried several iterations of syntax, but I can't get one that works with the complex expression.
<script>
var i;
for (i = 0; i < 5; i++) {
$("#P" +i).on("blur", function(){$("#Y" +i).val(getClass(this));});
}
</script>
How come this doesn't work?
At the end of the for loop, i has a value of 5, so every time the blur handler is called, the interpreter will see i with a value of 5 - and #Y5 doesn't exist if you only have #Y1-4.
Use let instead, which has block scope rather than function scope, so that every iteration has a separate binding for i:
for (let i = 1; i < 5; i++) {
$("#P" + i).on("blur", function(){
$("#Y" + i).val(getClass(this));
});
}
Always use let (or const if you can) when you're using for loops, especially if there's anything asynchronous involved. (Actually, you should be using let or const everywhere you can regardless, but it's especially important with for to avoid bugs)

functions within loops, why are they considered an 'error'

For complex functions declared within a loop, I can see why I wouldn't want to do this, but why would it be be considered bad javascript?
We can name the function and place it outside the loop of course, but upsets the flow for something that is simple ( no async ).
Eg, below is a simple inline function declaration within a loop ( JSHINT/LINT complains, why this is considered a no no ?
for (var i = 0, len=arr.length; i < len; ++i) {
dosomething(arr[i], function(returnvalue) {
console.log(returnvalue);
});
};
Here's one reason why you wouldn't want that. The function references the same vars.
http://jsfiddle.net/RCzyF/
var a = [];
for(var i=0; i<10; i++) {
a.push(function () {
return i;
});
}
h = "";
for(var j=0; j<10; j++) {
h += "" + a[j]();
}
alert(h);
One could expect to see 0123456789 but it will append 10 10 times to h instead. It can make code really hard to understand when one function might change the content of other functions.
Here's a more complex example how things can get wrong.
var a = [];
for(var i=0; i<10; i++) {
a.push(function () {
return i++;
});
}
h = "";
for(var j=0; j<10; j++) {
h += "" + a[j]();
}
alert(h);
When the functions are created, they point to the same lexical scope. When the function are executed, they change the value inside the function and each function in the array still point to the same value. This can lead to really hard bug to debug when a variable gets modified but you didn't directly modify it.
Also here's the real answer coming from jslint itself: http://jslinterrors.com/dont-make-functions-within-a-loop/
Creating a function at each iteration is uselessly heavy.
Most of the time, in client side JavaScript, performance doesn't matter and there's no problem but it's better to take and keep good habits than having later to optimize the code (as long as the readability isn't hindered).
Here's a proof that you create a new function at each iteration :
var old;
function compare(_, a){
if (old) console.log('equal ?', old==a);
else old = a;
}
for (var i=0; i<2; i++){
compare(i, function(i) { return i*i });
}
It logs 'equal' ? false
testable jsbin

What is the most idiomatic way to handle variables declared in multiple for loops? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
JavaScript only has function scope. Thus, variables declared in for loops are visible for the entire function.
For example,
function foo() {
for(var i = 0; i < n; i++) {
// Do something
}
// i is still in scope here
}
When we have multiple for-loops, this opens the question of how we handle the variables in these other for loops.
Do we use a different variable?
for(var i = 0; i < n; i++) { }
for(var j = 0; j < n; j++) { }
Or do we use the same variable but just assign a value (instead of declaring it)?
for(var i = 0; i < n; i++) { }
for(i = 0; i < n; i++) { }
Or declare i outside of the loops?
var i;
for(i = 0; i < n; i++) { }
for(i = 0; i < n; i++) { }
Or redeclare i?
for(var i = 0; i < n; i++) { }
for(var i = 0; i < n; i++) { }
All of these work (or at least they do on the latest versions of my browsers). JSHint doesn't like the last approach, though.
Is there an approach which is most idiomatic or otherwise preferable?
It really depends on who you're coding for. If you're coding for a company or contributing to a library you of course follow their style guide. I've seen all of these (expect the last) used in libraries. If you like the Douglas Crockford style you'll go with the second to last and place all your variables at the top of function scope (or jslint will shout at you).
Taking an example from the jQuery style guide:
This is considered Good style
var i = 0;
if ( condition ) {
doSomething();
}
while ( !condition ) {
iterating++;
}
for ( ; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
}
While this is poor style:
// Bad
if(condition) doSomething();
while(!condition) iterating++;
for(var i=0;i<100;i++) object[array[i]] = someFn(i);
Anyway, because this is style I'm going to reference how several libraries write their for each loops:
jQuery uses the Crockford style in core as does lodash
Underscore js uses the last style as seen here. Mootools also uses this style
If your code is going to be minimized before you release it, it will not matter as minifiers will mangle it to pretty much the same end representation in the processing.
Using different variables we have no problems.
Reusing and reassigning makes the code less readable, and if we remove the declaration at a later time, we risk assigning i to something outside of the function scope.
Declaring i outside the loops, we have no problems.
Redeclaring will be an issue if your lint tool, IDE, etc complain.
So I would argue for the first or third option. If number of variables is a concern using the first option, then you are may be in need of a refactoring.
Another take that answers the question in a different way.
A function with multiple loops makes me suspicious because:
It may be doing too much and should be decomposed anyway, and
It may be better to write it more functionally and eliminate the index altogether (it's available in some each-/map-y functions anyway)
Another approach is to use iterator functions. For example, in modern browsers an Array will have a forEach method:
var items = ["one", "two", "three"];
var things = ["hello", "goodbye"];
items.forEach(function (item, index) {
// Do stuff
});
things.forEach(function (item, index) {
// Do stuff
});
If you're using older browsers (or custom collections), you can make your own iterator like this:
Array.prototype.forEach = function(callback) {
for(var i = 0; i < this.length; i++) {
callback.apply(this, [this[i], i, this]);
}
};
For more information see: Array.prototype.forEach()
Any variables declared within a function are interpreted as being declared at the beginning of the function. Doug Crockford argues that you should declare all of your variables at the first line of every function.
doSomething = function() {
var i, ... other variables ...;
...
for (i = 0; i < x; i += 1) {
...
}
...
for (i = 0; i < x; i += 1) {
...
}
}
This way the code reads in the same way it will be parsed by the javascript engine.

let keyword in the for loop

ECMAScript 6's let is supposed to provide block scope without hoisting headaches. Can some explain why in the code below i in the function resolves to the last value from the loop (just like with var) instead of the value from the current iteration?
"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
things["fun" + i] = function() {
console.log(i);
};
}
things["fun0"](); // prints 3
things["fun1"](); // prints 3
things["fun2"](); // prints 3
According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block. Why is that necessary?
"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
let index = i;
things["fun" + i] = function() {
console.log(index);
};
}
things["fun0"](); // prints 0
things["fun1"](); // prints 1
things["fun2"](); // prints 2
I tested the script with Traceur and node --harmony.
squint's answer is no longer up-to-date. In ECMA 6 specification, the specified behaviour is that in
for(let i;;){}
i gets a new binding for every iteration of the loop.
This means that every closure captures a different i instance. So the result of 012 is the correct result as of now. When you run this in Chrome v47+, you get the correct result. When you run it in IE11 and Edge, currently the incorrect result (333) seems to be produced.
More information regarding this bug/feature can be found in the links in this page;
Since when the let expression is used, every iteration creates a new lexical scope chained up to the previous scope. This has performance implications for using the let expression, which is reported here.
I passed this code through Babel so we can understand the behaviour in terms of familiar ES5:
for (let i = 0; i < 3; i++) {
i++;
things["fun" + i] = function() {
console.log(i);
};
i--;
}
Here is the code transpiled to ES5:
var _loop = function _loop(_i) {
_i++;
things["fun" + _i] = function () {
console.log(_i);
};
_i--;
i = _i;
};
for (var i = 0; i < 3; i++) {
_loop(i);
}
We can see that two variables are used.
In the outer scope i is the variable that changes as we iterate.
In the inner scope _i is a unique variable for each iteration. There will eventually be three separate instances of _i.
Each callback function can see its corresponding _i, and could even manipulate it if it wanted to, independently of the _is in other scopes.
(You can confirm that there are three different _is by doing console.log(i++) inside the callback. Changing _i in an earlier callback does not affect the output from later callbacks.)
At the end of each iteration, the value of _i is copied into i. Therefore changing the unique inner variable during the iteration will affect the outer iterated variable.
It is good to see that ES6 has continued the long-standing tradition of WTFJS.
IMHO -- the programmers who first implemented this LET (producing your initial version's results) did it correctly with respect to sanity; they may not have glanced at the spec during that implementation.
It makes more sense that a single variable is being used, but scoped to the for loop. Especially since one should feel free to change that variable depending on conditions within the loop.
But wait -- you can change the loop variable. WTFJS!! However, if you attempt to change it in your inner scope, it won't work now because it is a new variable.
I don't like what I have to do To get what I want (a single variable that is local to the for):
{
let x = 0;
for (; x < length; x++)
{
things["fun" + x] = function() {
console.log(x);
};
}
}
Where as to modify the more intuitive (if imaginary) version to handle a new variable per iteration:
for (let x = 0; x < length; x++)
{
let y = x;
things["fun" + y] = function() {
console.log(y);
};
}
It is crystal clear what my intention with the y variable is.. Or would have been if SANITY ruled the universe.
So your first example now works in FF; it produces the 0, 1, 2. You get to call the issue fixed. I call the issue WTFJS.
ps. My reference to WTFJS is from JoeyTwiddle above; It sounds like a meme I should have known before today, but today was a great time to learn it.

Variable definitions in nested for loops?

Some static languages like Java seem to have very special rules for variables defined in the first argument of a for loop. They are accessible only by the given loop, which makes them behave pretty much like javascript functions' local variables and arguments. I mean stuff like this:
class ForVariable {
public static void main(String[] args) {
for(int i = 0; i != 0; i++) {}
System.out.println(i); // Throws an Exception
}
}
Javascript doesn't behave like that, which makes nesting loops quite a messy business. My question is: Is it valid to declare variables in the subsequent loops via the var keyword? In other words - which of the following examples is valid?
for(var i = 0, j; i < 5; i++) {
for(j = 0; j < 10; j++) <do some stuff>;
}
OR
for(var i = 0; i < 5; i++) {
for(var j = 0; j < 10; j++) <do some stuff>;
}
Clearly it is wrong to declare a variable several times, which would make the 2nd example a no-go, but given the fact that the 1st example is the way loops nesting is done in most languages I know, I'm rather hesitant to declare the winner.
Those are both valid. Function scoped vs block scoped. Basically both loops in JavaScript become:
function a () {
var i, j;
for(i = 0, j; i < 5; i++) {
for(j = 0; j < 10; j++) <do some stuff>;
}
}
because the var declarations are hoisted to the top
Its not wrong to declare a variable several times. For instance there is really no problem with:
var i = 0;
var i = 1;
That's valid JavaScript. Good tools like the Closure Compiler will generate a warning though because you typically don't intend to do that.
That being said, even the Closure Compiler won't generate a warning for your example #2. It's just common convention in JS even if you are technically re-declaring.
Either of your two examples is fine but the second one is a little more sensible to parse. I wouldn't worry about it either way.
You don't want to be using the var keyword, but rather function arguments, because javascript is not block-scoped. For example:
[100,200,300].forEach(function (x,i) {
[10,20,30].forEach(function (y,j) {
console.log('loop variables, indices '+[i,j]+' have values: '+[x,y]);
});
})
or
[100,200,300].map(function (x,i) {
return [10,20,30].map(function (y,j) {
return x+y;
});
})
// result: [[110,120,130],[210,220,230],[310,320,330]]

Categories