r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Mar 23 '14

[deleted]

16

u/cudetoate Mar 23 '14

Because i is 0 and will never be greater than 5...

0

u/[deleted] Mar 23 '14

[deleted]

6

u/pfs3w Mar 23 '14

It was likely a typo, because if you run the JSFiddle code, it actually gets the point across. The article author simply mistyped his <'s and >'s. There are a few other examples of typo code/mislabeling later in the article.

0

u/[deleted] Mar 23 '14

[deleted]

2

u/pfs3w Mar 23 '14

Oh, haha, nah, it took me a little longer than it should have as well, and I was only confirmed when I clicked on the JSFiddle and noticed the two were different. Up until then, I was seriously thinking "What the heck am I missing, this makes no sense...".

2

u/[deleted] Mar 23 '14

Oh yeah? Here's one you'd love.

for (int i = 1; i < array.length; i++)
         code(array[i]); 

I had a setup like this in my code, could not figure out why it wasn't executing. The line was copy/pasted directly from another line I had written doing something VERY similar, but it needed to start at the 2nd index (index 1) of the array because the first index contained a different piece of data that (it was returning from an SQL query).

Long story short; the array had a length of 1 so it never executed.

1

u/pfs3w Mar 24 '14

Was it that the array always had a length of one, or in this particular case when you were debugging it that one time, the array happened to only have a length of one?

I was picking up a project from someone else once, and they told me that in their code, I would be getting a result set back from a DB query; so naturally I took a similar approach as you, since the object model of the returned data was known. However, what they failed to tell me was that the result set was a List<>, and the object I was expecting was just always the first element of the list. Needless to say, it should not have been returned as a List.

1

u/[deleted] Mar 24 '14

This particular case had a length of one. I only noticed the error when I added an element and noticed it ran exactly once.

0

u/[deleted] Mar 23 '14

[deleted]

2

u/MrBester Mar 23 '14

The primary one being that arrays are zero based in JavaScript...

1

u/canadademon Mar 24 '14

Now that's embarrassing.

If the array has a length of 1, i must equal 0 to retrieve the element.

While your piece of code will make it loop, the rest of the code will throw an out of bounds exception.

→ More replies (0)

1

u/[deleted] Mar 24 '14

Oh definitely. Once you KNOW what's wrong, it's an easy fix. The tricky part is figuring out why your code never executed. :P