Bitesize Bugs

Accidental Global Variables in JavaScript

Omitting the “var” keyword when declaring a variable in JavaScript will scope it to the global namespace.

Thus, the variable is no longer bound to the scope of the parent function or object instance, but accessibile to every other script through the global “window” object.

Example

See https://gist.github.com/1092039

Avoid accidentally creating global variables by always declaring them with ‘var’.

This problem gets especially frustrating when expecting variables to be private, bound to instances of an object. You soon realize that your instances’ internal states change unexpectedly.


 

 

 

 

 

Advertisements

Filed under: JavaScript, , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: