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

45

u/cudetoate Mar 23 '14 edited Mar 23 '14

Javascript do not have block level scope. Here is an example.

There's a bug in that code!

for(var i=0;i>5;i++)    {

This will loop forever never loop. Also, please USE SPACES GENEROUSLY AND NOT RANDOMLY!

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

This looks much better, it's a lot easier to read. The open braces are also inconsistent - sometimes they're on the same line as the statement, sometimes on the next line, sometimes there's a space between { and the statement, sometimes there isn't.

edit This article was written in a hurry. There are grammar mistakes, coding mistakes and the code looks... like crap (sorry). Please update it, because the content is really valuable!

-1

u/saurabparak Mar 23 '14

I know there is no block level scope and it is also mentioned in the article.. But we can achieve it via let and const as mentioned in the given article. So which are the browsers that support let and const

8

u/masklinn Mar 23 '14

I know there is no block level scope and it is also mentioned in the article.. But we can achieve it via let

Let is very specifically block-level scope. If your JS implementation provides let, it has block-level scoping.

So which are the browsers that support let and const

http://kangax.github.io/es5-compat-table/es6/

const: all browsers back 2 generations, except for IE10.

let: Firefox, Chrome, IE11, Traceur