0

Let's say I have the following code:

var app = {};

app.post = {
    foo: function() {
        // defining a variable without the 'var' keyword inside a function.
        bar = "Hello!";
    }
}

I think the way that I defined the bar variable is not good. I know you shouldn't have global variables. but, I defined it inside of a method which is inside of an object.

Is it a bad practice?

Akar
  • 5,075
  • 2
  • 25
  • 39
  • 1
    Yes. In "strict" mode it would cause an error. Without `var`, the variable is implicitly global. – Pointy May 09 '15 at 13:10
  • Without the `var` prefix if you do `alert(bar);` outside of the foo function you'll see the code above has made it globally accessible. – garryp May 09 '15 at 13:14
  • You should use `var` keyword not only for the interpreter, but for the human eyes: at first sight, `bar` looks global. – ern0 May 09 '15 at 13:14

1 Answers1

3

Yes, it's still a bad practice.

Without strict mode, this would cause bar to be implicitly declared global. With strict mode, this would cause an error.

Always use var to declare new variables, regardless of scope (and especially in inner scopes).

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308