r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

2

u/[deleted] May 28 '19

If you declare a var in a for() loop without intializing it to a value, once the value gets set it gets retained for subsequent iterations through the loop:

for (var i = 0; i < 3; i++) {

    var foo;

    if (someCondition()) foo = i;

    if (foo != null) {

        // This will be true if someCondition returned true in this loop

        // OR if it returned true in an earlier loop

    } 

}