Javascript

Topic: JS Variables

What’s the difference between these two statements:var x = 3;x = 3;

The first puts the variable in the scope of whatever function it was defined. The second places the variable in global scope. It can potentially cause collision with other variables with the same name. Therefore, the keyword var should always be used when defining variables, and an anonymous function should be used as a closure if need be, encapsulating multiple functions which can share access to the same set of variables. That makes sure the variables stay sandboxed, accessible only by those functions which need them.

Browse random answers: