Javascript event listener structure - javascript

I’m working on a code to get the index of a clicked element so it can add or remove a class to display or hide the information. For it I used for for iteration. But I don’t understand why is there an (i) after the event handler. I’m kind a newbie to coding so I want to understand everything.
Here’s the JavaScript code:
for (let i = 0; i < questions.length; i++) {
questions[i].addEventListener(‘click’,((e) => {
return function() {
if (clic[e].classList.contains(‘q-answered)) {
clic[e].classList.replace(‘q-answered’, ‘q-answeredno’);
} else if (clic[e].classList.contains(‘q-answeredno’)) {
clic[e].classList.replace(‘q-answeredno’, ‘q-answered’);
}
}
})(i))
}

Let's start by looking at what's happening as though you were using var to iterate through your questions
Put simply, it's making it an immediately-invoked function expression (or IIFE for short) and passing in a parameter you normally wouldn't otherwise have access to.
When a click event handler callback expects a function with a single variable. When the event is handled, the function is invoked and the JS runtime provides a pointer event back to your function to do something with. That's all well and good, but here you want to know the offset of the clicked element in the array from information gleaned out of the scope of this callback.
So you instead change the callback shape. You pass in your own function and wrap it in parentheses. In JS, you pass in the arguments to the function in parentheses following the definition. Your example uses the lambda syntax, so you start with the function itself:
(e) => {return ...;}
But if this is all that were passed in here, you'd get a PointerEvent assigned to e as it matches the anticipated callback shape. So you instead need to wrap this in parentheses:
((e) => {return ...;})
Great, but you want this function to have a very particular value passed in when it executes, so you define the arguments at the end. You're using i as the variable identifying the index of the offset element, so we'll pass that in here.
((e) => { return ...; })(i)
Now, this means that when your event handler function is invoked for the first element, it'll practically look like the following:
((e) => {return ...; })(0); //Zero for the first zero-based index
This precludes the event handler callback assigning its own value to your first variable and means that now the function will be invoked, you'll pass the 0 (or otherwise set index property value) to your e argument and the remainder of the return statement will execute accordingly.
What's this closure thing I've heard of and how might it apply here?
#t.niese brings up a great point in the comments that I originally missed about closures and why they're quite relevant here.
Put simply, in JavaScript, you can refer to variables that are defined within a function's scope, to variables of the calling function's (e.g. parent) scope or any variables on the global scope. A closure is any function that's able to keep these references to these variables regardless of whether the parent has already returned or not.
If I have something like the following:
function listFruits(fruits) {
var suffix = "s";
for (var a = 0; a < fruits.length; a++) {
console.log(`I like ${fruits[a]}${suffix}`);
}
}
listFruits(['grape', 'apple', 'orange']);
// >> "I like grapes"
// >> "I like apples"
// >> "I like oranges"
As you'd expect, despite assigning suffix outside of the loop, I'm able to use it within the loop to make each fruit name plural. But I can do this using an inner function as well:
function listFruits(fruits) {
var suffix = "s";
function pluralizeName(name) {
return `${name}${suffix}`;
}
for (var a = 0; a < fruits.length; a++) {
var pluralName = pluralizeName(fruits[a]);
console.log(`I like ${pluralName}`);
}
}
listFruits(['grape', 'apple', 'orange']);
// >> "I like grapes"
// >> "I like apples"
// >> "I like oranges"
Again, despite suffix being assigned in the parent of the pluralizeName function, I'm still able to assign it in the return string to log to the console in my loop.
So, let's put a timeout callback in there and see what happens:
function listFruits(fruits) {
var suffix = "s";
for (var a = 0; a < fruits.length; a++) {
setTimeout(function() {
console.log(`I like ${fruits[a]}${suffix}`);
}, 1000);
}
}
listFruits(['grape', 'apple', 'orange']);
// >> "I like undefineds"
// >> "I like undefineds"
// >> "I like undefineds"
Why didn't we list the fruit we like here as before? a is still being defined in the parent and it does attach the suffix value as it should, so what gives?
Well, our loop starts at a = 0, sets the timeout to execute the callback in 1000ms, then increments a to 1, sets the timeout to execute the callback in 1000ms, then increments a to 2, sets the timeout to execute the callback in 1000ms, then increments a to 3, sets the timeout to execute the callback in 1000ms, then increments a to 4 at which point a is greater than the number of fruits passed in (3) and the loop breaks out. But when the timeout callbacks run then, a now has a value of 4 and fruits[4] is undefined, so we see that in the console logs.
Ok, but we want to be able to reference the value of our iterating index locally so the first callback works against the first object, the second against the second and so on, so how do we make that available to the callback? We use the IIFE approach covered above.
function listFruits(fruits) {
var suffix = "s";
for (var a = 0; a < fruits.length; a++) {
(function() {
var current = a;
setTimeout( function() {
console.log(`I like ${fruits[current]}${suffix}`);
}, 1000);
})();
}
}
// >> "I like grapes"
// >> "I like apples"
// >> "I like oranges"
It works here because we create a new closure for each of the functions created by the loop. When the function is created, we take the current value of a from the parent and assign it to a local variable so that when the setTimeout method fires later, it uses that local current value to properly access the intended index of the fruits array.
But rather than capture the variable as I do above in var current = a;, I can instead pass the a variable into the IIFE as a parameter and it will have exactly the same effect:
function listFruits(fruits) {
var suffix = "s";
for (var a = 0; a < fruits.length; a++) {
(function(current) {
setTimeout( function() {
console.log(`I like ${fruits[current]}${suffix}`);
}, 1000);
})(a);
}
}
listFruits(['grape', 'apple', 'orange']);
// >> "I like grapes"
// >> "I like apples"
// >> "I like oranges"
Our IIFE populates the current variable with the argument a passed in making it available locally and we get the expected outcome.
But my sample uses let, so how does that change anything?
Prior to ES6, we had only the global and function scopes requiring the use of the IFFEs to introduce local function scopes as we saw above. With ES6, we got a new "block scope" which essentially scopes everything within two curly braces, including any number of child blocks within that, but only if the variable is assigned using the const or let keywords. var still only assigns to a global or function scope.
Let's revisit the example above in which we received all the undefined values and replace our use of var with let.
function listFruits(fruits) {
var suffix = "s";
for (let a = 0; a < fruits.length; a++) { //Note the change to 'let' here
setTimeout(function() {
console.log(`I like ${fruits[a]}${suffix}`);
}, 1000);
}
}
listFruits(['grape', 'apple', 'orange']);
// >> "I like grapes"
// >> "I like apples"
// >> "I like oranges"
And this time it works because the value of a persists as assigned to the setTimeout callback's block scope.
Ok, so what about my sample?
Let's bring it back full-circle then. If you were using var, your sample scopes the present value of i to the IIFE so each of your event handler callbacks can access the appropriate offset node.
But since you're using let, the use of an IFFE certainly won't hurt anything, but it's unnecessary as the intended value of i is available to your callback functions via their block scope. As such, you can simplify to remove the IIFE and suffer no consequences.
for (let i = 0; i < questions.length; i++) {
questions[i].addEventListener(‘click’, function() {
if (clic[i].classList.contains(‘q-answered)) {
clic[i].classList.replace(‘q-answered’, ‘q-answeredno’);
} else if (clic[i].classList.contains(‘q-answeredno’)) {
clic[i].classList.replace(‘q-answeredno’, ‘q-answered’);
}
});
}
Should you have questions about any of this, please leave a comment and I'd be happy to edit to address it.

Related

Does it ever make sense to include a value in the first next call to generator iterator?

As the question states, does it ever make sense to pass a value to the first iterator.next() call or will it always be ignored? As an example:
function* foo(x) {
var y = 2 * (yield(x + 1));
var z = yield(y / 3);
return (x + y + z);
}
var it = foo(5);
// note: not sending anything into `next()` here
console.log(it.next()); // { value:6, done:false }
console.log(it.next(12)); // { value:8, done:false }
console.log(it.next(13)); // { value:42, done:true }
Notice there is not a value being passed to the first next(). However, in the article I'm trying to learn from, it goes on to say:
But if we did pass in a value to that first next(..) call, nothing bad would happen. It would just be a tossed-away value
Okay. That makes sense. But now I'm curious to know if there is a use case (or if it's even possible to utilize) where passing in a value has a benefit.
Article: https://davidwalsh.name/es6-generators
Will it always be ignored?
Yes.
Is a use case where passing in a value has a benefit?
When it simplifies the rest of your code. In your example, that could be using a loop instead of writing it out:
const it = foo(5);
for (let i=11; i<=13; i++)
console.log(it.next(i));
Now we're passing 11 into the first call to .next even if there's no use for the value anywhere.

JavaScript Higher Order Function loop/recursion/confusion

Implement a function that takes a function as its first argument, a number num as its second argument, then executes the passed in function num times.
function repeat(operation, num) {
var num_array = new Array(num);
for(var i = 0; i < num_array.length; i++){
return operation(num);
}
}
//
// The next lines are from a CLI, I did not make it.
//
// Do not remove the line below
module.exports = repeat
RESULTS:
ACTUAL EXPECTED
------ --------
"Called function 1 times." "Called function 1 times."
"" != "Called function 2 times."
null != ""
# FAIL
Why doesn't this work?
I am assuming that I am starting a function called repeat. Repeat has two parameters and takes two arguments.
For the loop I create an array which has a length which is equal to the num passed in.
I then start a for loop, setting a counter variable i to 0. Then I set a conditional which states that i should always be less than the length of the num_array which was created earlier. Then the counter i is incremented up by one using the ++.
For every time that the conditional is true, we should return the value of calling running the function operation and passing the num as an argument.
The last two lines allow for easy running of the program through command line with pre programmed arguments being used.
Thank you for your time!
The return statement is breaking out of the function on the first iteration of the loop. You need to remove the return, and just call the function like this:
function repeat(operation, num) {
for(var i = 0; i < num; i++){
operation(num);
}
}
Note that I have removed the creation and iteration of the array, you do not need it for what you are doing here.
Also your initial question does not specify that you need to pass num to the function (but you do list it in your steps below), so you may be able to just do operation() instead of operation(num).
You probably want something like the below, rather than returning the result of the function operation(num) you want to store the value in teh array. return in a loop breaks out of the loop, so it would always only run once..
function repeat(operation, num) {
var num_array = new Array(num);
for(var i = 0; i < num_array.length; i++){
num_array[i] = operation(num);
}
}
//
// The next lines are from a CLI, I did not make it.
//
// Do not remove the line below
module.exports = repeat
If you are asking why the loop is not running, it's because you have to run the function after defining it (I'm assuming you are not already calling the function somewhere else).
Once calling the function repeat you will see that it is exiting after one iteration. This is because you are returning the operation - returning causes the function to end. To stay in the loop you just need to call operation(), without the return.
Also you don't need to create an array, you can just use the counter you are defining in the for loop.
So the code would look something like this:
var op = function(arg) {console.log(arg);},
n = 5;
function repeat(operation, num) {
for(var i = 0; i < num; i++){
operation(i);
}
}
repeat(op ,n);
// The next lines are from a CLI, I did not make it.
//
// Do not remove the line below
module.exports = repeat

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.

Reusing the same shortcut.js function to handle keyboard input

I'm using shortcut.js to handle keyboard input and I'm wondering if there is a more efficient way to achieve my goal (currently most of the same code is copied and pasted).
For example, i have:
shortcut.add("0",function() {
points = -1;
sec = 0;
});
shortcut.add("1",function() {
points = 1;
sec = 0;
});
shortcut.add("2",function() {
points = 2;
sec = 0;
});
shortcut.add("3",function() {
points = 3;
sec = 0;
});
Ideally, I can generalize the function so that whatever key is entered is actually assigned to the points variable, except in the case where the user enters 0. In that case, the points variable is set to -1.
Any ideas on how to make this happen? Thank you!
A loop with a closure should do the trick:
for (var i = 0; i <= 9; ++i) {
(function(i) { // Capture current value of 'i' in this scope.
shortcut.add(i.toString(), function() {
points = i || -1; // 'i' if 'i' is not 0, else -1.
sec = 0;
});
})(i);
}
Update following comment: So why do we need a closure here? And what does the final (i); mean?
Basically, we need a closure because the anonymous functions passed to shortcut.add() will not be called right away, but some time in the future, after the loop has terminated. The functions capture i by reference, not by value, which means they will see the value of i that is current at the time they run, not at the time they're defined.
So, if we call shortcut.add() directly from the loop body, all the anonymous functions we pass will end up seeing the value of i that is current after the loop has terminated, which will always be the same (10).
Creating a new variable in each iteration looks like it could work, but doesn't:
for (var i = 0; i <= 9; ++i) {
var _i = i; // Create new variable containing current value of 'i'.
shortcut.add(i.toString(), function() {
points = _i || -1; // Won't work, '_i' is always 9.
sec = 0;
});
}
Since for loop bodies do not have their own scope in Javascript, _i ends up in function scope, the same as i, and will be captured the same way (its final value will be 9 instead of 10 because ++i does not apply to it).
So, what we really need here is a new scope in each iteration. To achieve this, we can define a function inside the loop, and call it immediately, passing it the current value of i:
var newScope = function(i) {
// Here, the value of 'i' will be the one current when 'newScope' is called
// and will not change, even if 'i' is captured by other functions.
};
newScope(i); // Call function with current value of 'i'.
Finally, we can do that without introducing the newScope name, by directly applying the call operator () to the function definition:
(function(i) {
// Here, the value of 'i' will be the one current when this function is
// called and will not change, even if 'i' is captured by other functions.
})(i); // Call function with current value of 'i'.
I hope this appropriately answers your questions, feel free to leave further comments if it does not. For more information about closures, see Closures on MDN.

JavaScript Broken Closures and Wrapper Function from John Resig #62 and #63

The first example below is #62 from John Resign`s Learning Advanced JavaScript http://ejohn.org/apps/learn/#62. It is called Fix the Broken Closures. Example 1 fails 4 times. Example 2, which is only different because it has a wrapper function, passes 4 times. It is example #63 from the same tutorial
Can someone please explain
1) why i == count++ in example 1 fails.
2) why i == count++ passes with the help of the wrapper function. How does the wrapper function change things to make it work?
Thanks in advance.
Example 1
var count = 0;
for ( var i = 0; i < 4; i++ ) {
setTimeout(function(){
assert( i == count++, "Check the value of i." );
}, i * 200);
}
Example 2
var count = 0;
for ( var i = 0; i < 4; i++ ) (function(i){
setTimeout(function(){
assert( i == count++, "Check the value of i." );
}, i * 200);
})(i);
This is pretty straight forward.
Since setTimeout executes "asynchronously", there is no way of telling the exact value of i when the function executes, since the loop carries on running.
By using a function wrapper, effectively you are treating the body of the call as a function and are EXPLICITLY passing in the value of i.
You could clear this up by renaming the function i param to j or something else and update the innards of the function to from i to j
Basically it boils down to scoping
Since i is being incremented in the loop the odds are strong that each time the setTimeout callback is invoked the value of i will be 4.
The wrapper function introduces a new scope allowing the value of the parameter i to maintain its value even though the surrounding i is being incremented by the loop.
function outerScope() {
var x = 2, y = 3;
function innerScope() {
var x = 3;
// Obviously this alerts 3.
alert(x);
// Since we have no 'y' defined, alert the value 3 from the outer scope.
alert(y);
}
// Introduce a new scope.
innerScope();
// Since we have left the inner scope x is now 2.
alert(x);
// Obviously this alerts 3.
alert(y);
}

Categories