Understanding function scope [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I have code on JavaScript.
var a = [];
for (var i = 0; i < 5; i++) {
a[i] = function () {
alert(i);
};
}
a[2]();
If I invoke a[2]() I expect to see a message with 2 but instead of this I see 5.
To fix it I can rewrite it like this:
for (var i = 0; i < 5; i++) {
(function (v) {
a[i] = function () {
alert(v);
}
})(i)
}
But I cannot understand how does it work. So why I need to wrap my function code to closure?

Related

javascript how to fix pitfalls counter [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 months ago.
I'm trying to run a for loop and print the current index without use let
here my code:
function init() {
for (var index = 0; index < 5; ++index) {
setTimeout(() => {
console.log(index);
}, index);
}
}
I expected to: 0 1 2 3 4
but i get 5 5 5 5 5
Once the Var replace in Let the problem will be solved
I want to stay with Var
How can the problem be solved?
Thanks
function init() {
for (var index = 0; index < 5; ++index) {
const i = index;
setTimeout(() => {
console.log(i);
}, i);
}
}
This should work.

How to understand Incrementing variables in JS? [duplicate]

This question already has answers here:
For (;;) loop explanation
(7 answers)
How can I process each letter of text using Javascript?
(24 answers)
Closed 2 years ago.
I am a junior developer learning JS. Here is the piece of code I am practicing today.
I see the line " (var x=0; x < str1.length; x++) " almost every example I work on.
Can someone please explain what the mechanics are doing? Why do we always set a var equal to 0?
What role does str1.length play in this line?
function vowel_count(str1) {
var vowel_list = 'aeiouAEIOU';
var vcount = 0;
for (var x = 0; x < str1.length; x++){
if (vowel_list.indexOf(str1[x]) !== -1)
{
vcount += 1;
}
}
return vcount;
}
console.log(vowel_count("The quick black panther."));

Explain javascript code syntax [duplicate]

This question already has answers here:
What does the leading semicolon in JavaScript libraries do?
(6 answers)
Closed 7 years ago.
;(function () {
var n = readline(), r = 0;
for (var i = 0; i < n; i++)
r += readline().split(' ').filter(function(v){ return v == 1;}).length > 1;
print(r);
}).call(this);
Why we add ; before the function and why we don't put {} for the for loop?.
The parenthesis in the for loop are omitted because it's only one line of code, in that case you do not need them. The ; is a fail-safe if you include this in other scripts.

JavaScript Closure in Loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I wanted to solve this question posted as a public question on testdome. Each as[i] should be a function that does alert(i).
The code to be bug-fixed is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (i = as.length; i-- >= 0;) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}
The solution I attempted is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
//made the loop variables more explicit
for (i = as.length-1; i >=0; i--) {
var x = i;
as[x].onclick = function() {
alert(x);
return false;
}
}
}
I though that variable i is persistent, so I kept its copy in variable x, and use variable x instead of i. But it does not solve the problem completely. Please let me know what is my misunderstanding.
Your i and x values are declared in exactly the same scope, so by the time the function is executed x will be its final value. You could create a closure like this:
function registerHandlers() {
var links = document.getElementsByTagName('a');
for (var i = 0, len = links.length; i < len; i += 1) {
links[i].onclick = generateHandler(i);
}
function generateHandler (index) {
return function () {
alert(index);
return false;
}
}
}

How to show current loop iteration in click function, javascript [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
JSFiddle
var arr = [ [0], [1], [2], [3] ];
for ( var i = 0; i < arr.length; i++ ) {
$('#btn-' + i).click(function() {
console.log(i);
});
}
When I'm clicking on corresponding button console.log always shows me last iteration instead of the current iteration. Why?
Try creating a closure, In other words, create a scope per iteration. Now in your code all the event handlers are created in a single scope and the i inside of that scope would get updated instantly to 4. So as a result, when you clicking on all the buttons the result would be same. That is the updated one of i
for ( var i = 0; i < arr.length; i++ ) {
var j = function(x) {
$('#btn-' + x).click(function() {
console.log(x);
});
}
j(i);
}
DEMO
Because of closure! For that you can do this:
for (var i = 0; i < arr.length; i++) {
(function(n) {
$('#btn-' + i).click(function() {
console.log(n);
});
})(i);
}
DEMO

Categories