Question

Though you can use a variable without declaring it in javascript, the misuse of variable will cause hard-to-solve errors. For example, the following code will cause endless loop.

  for(i=0;i<100;i++){
    document.write(fiveTimes(i));
  }
  ...

  function fiveTimes(x){
    i=5;
    return (i*x);
  }

I'd like to know if there is a way to force every variable in the javascript to be declared before use. Or anybody knows how to check for variable declaration-before-using in tons of javascript files and blocks in a huge web server.

Was it helpful?

Solution

You can enable "Strict Mode" and you can pass your code through jsLint (Or jsHint if you have sensitive feelings :))These steps will go a long way toward making your code execute predictably.

OTHER TIPS

The main architecture behind JavaScript doesn't allow you to achieve this without parsing the code with another compiler ( jsHint, etc ... ). What will happen there is that the library will double check your code for some dangerous ( unwanted ) results. If you are good enough and know what you are doing, you can avoid using those and just be careful of what you are doing.

Also, there are a lot of languages that compile to JS ( CoffeeScript, etc. ) that has automatic variable declaration for every function and more stuff you might be interested in.

This solution has to tell you that JavaScript isn't supposed to do that internally and there is no forced use of 'strict' mode at least at this time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top