Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The benefits of declaring variables at the top of the function body in JavaScript

Tags:

javascript

I am reading Douglas Crockford's book "Javascript: The Good Parts". He is talking about scope and saying that JS doesn't have block scope:

In many modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for Javascript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body.

However, I couldn't think of a good example why this statement makes sense and it would be really nice to see some examples which verify this statement.

like image 492
Tarik Avatar asked Sep 20 '14 05:09

Tarik


1 Answers

Declaring variables at the top helps you avoid situations like this:

function outer() {
  var i = 50;

  function inner() {
    alert(i);
    var i= 30;
  }
  inner();
}

outer();

Many people would expect the alert to show 50, and they would be surprised to see undefined. That's because the i variable is declared within the inner function, but it isn't initialized until after the alert. So it has full function scope, even though it's declared after its initial use.

like image 84
Rick Hitchcock Avatar answered Oct 19 '22 22:10

Rick Hitchcock