Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 모든 선언을 맨 위에 두는 것이 좋은 방법입니까?

<시간/>

예, 모든 JavaScript 선언을 맨 위에 배치하는 것이 좋습니다. 예를 들어 보겠습니다 -

예시

<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>

다음은 유효한 이유입니다 -

  • 모든 변수를 확인할 수 있는 단일 위치를 제공합니다.
  • 전역 변수 방지에 도움
  • 재선언을 피합니다.
  • 다른 사람도 쉽게 읽을 수 있는 코드입니다.