Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate variables in JavaScript

Tags:

javascript

Is there is any way/tool to detect the duplicated variables/methods names in the project JavaScript files?


2 Answers

There is no such thing as duplicate names in Javascript. You will never get an error when re-declaring a name that already exists.

To avoid overwriting existing names in Javascript, good developers do at least one of these things:

1) Carefully keep their variables out of the global scope, usually adding all names needed for the app under just one or two globally-scoped objects.

// No 
var foo = 1;
var bar = 2;
var bas = 3;

// Yes
var MyApp = {
    foo:1,
    bar:2,
    bas:3
}

2) Check that a variable name does not yet exist before creating it.

// No
var MyObj = {};

// Yes
var MyObj = MyObj || {} // Use MyObj if it exists, else default to empty object.
like image 111
Kenan Banks Avatar answered Oct 22 '25 18:10

Kenan Banks


jsLint might help you

http://www.jslint.com/

like image 30
Rik Heywood Avatar answered Oct 22 '25 18:10

Rik Heywood