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

HTMLJavascriptProgramming Scripts

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

Example

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

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

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.
raja
Published on 26-Feb-2018 09:40:18
Advertisements