1

I want to pass a global variable to a javascript .each function and keep its value while the iteration.

Here is the code.

 var year = false;
 page.posts.each(function(item, year){
   year = true;
 });

The year is still false. How can year keeps its value in the iteration?

2
  • 1
    This may sound silly, but did you actually call the function? Commented Aug 9, 2013 at 12:10
  • Yes. The function will be called for each elements in page.posts. Commented Aug 9, 2013 at 12:11

4 Answers 4

1

You have a name conflict between the function parameter and the global variable. As the function parameter name is closer to the executed code, when JavaScript looks up through the variable names to find out what you meant, it finds the parameter name first, so that is what becomes set.

If you want to explicitly set the global variable, you'll have to access it though window, i.e.

window.year = true; // explicit global
Sign up to request clarification or add additional context in comments.

2 Comments

It is in fact in an ejs context, can I still use this method?
I don't know if variables from ejs are global; the other solution would be to rename your variables so you don't experience the conflict.
0

There is a conflict in your variable names.

var year = false;
 page.posts.each(function(item, yr){
   year = true;
 });

Comments

0

Try attaching to window document and see.

 window.year = false;
 page.posts.each(function(item, year){
   year = true;
 });

Comments

0

you can rename variable year to avoid conflict, or if you just want to change global variable , you should use window.year = true

page.posts.each(function(item, year){
   year = true;  
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.