Is it a good practice to place all declarations at the top in JavaScript?

Yes, it is a good practice to place all the JavaScript declarations at the top. Let’s see an example −


      <title>JavaScript String match() Method</title>

         // all the variables declared at top
         var str, re, found;
         str = "For more information, see Chapter";
         re = /(chapter \d+(\.\d)*)/i;
         found = str.match( re );
         document.write(found );

The following are the valid reasons −

  • Gives a single place to check for all the variables.
  • Helps in avoiding global variables
  • Re-declarations are avoided.
  • The code is easy to read for others as well.