DEV Community

Cover image for JavaScript and Scope IV - Blocks
Todd Chaffee
Todd Chaffee

Posted on • Updated on • Originally published at

JavaScript and Scope IV - Blocks

In JavaScript and Scope I, II, and III we looked at scope and functions. What about other statements that use blocks? Blocks being sections of code enclosed by curly brackets {}.

For example, we often declare variables in a for loop with a block.

var buzz = 3;

for (var buzz = 1; buzz < 10; buzz++) {
  if (buzz === 9) { 
    console.log('for loop buzz:', buzz); // logs 9

console.log('global scope buzz:', buzz); // logs 10

Edit in JSFiddle

When you run the code above, you'll see there is only one buzz variable. The one declared in the global scope. The for loop changes the global variable. The buzz variable will have a value of 10 when the last console.log runs.

What about if statements?

var cute = 'not';

if (true) {
  var cute = 'cat';

console.log(cute); // logs 'cat'

Edit in JSFiddle

Again, there is only one cute variable and the final value of the variable in the global scope will be 'cat'. The re-declaration of the variable inside the block does not create a new scope and variable.

Both of the examples above are the opposite of what we saw for functions. Functions create a new scope for variables. Blocks do not create a new scope for variables declared with var.

Did you know you can declare blocks all on their own without using an if or for statement or anything else? I will leave you with this one final very simple example to help you memorize the rule: blocks do not create a new scope for variables declared with var.

var toto = 'wants';

  var toto = 'a puppy';

console.log(toto); // logs 'a puppy'

Edit in JSFiddle

Discussion (0)