Javascript

[JavaScript] JavaScript / Global Variables and Local Variables

OOQ 2022. 8. 5. 10:10
728x90
SMALL

#JavaScript

#Global Variables and Local Variables

global and local variables

Variables can be divided into Global Variables and Local Variables according to their scope.

A global variable is a variable declared outside a function and accessible throughout the program.
A local variable is a variable declared within a function that is created when the function is executed and destroyed when the function exits. It cannot be accessed outside the function.

example 1

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
  </head>
  <body>
    <script>
      var jbVar = 'Lorem';
      function jbFunc() {
        var jbVar = 'Ipsum';
      }
      document.write( jbVar );
    </script>
  </body>
</html>

I set the value of the variable jbVar to Lorem outside the function and Ipsum inside the function. Since I called jbVar outside the function, the value of the global variable

Lorem

is output.

example 2

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
  </head>
  <body>
    <script>
      var jbVar = 'Lorem';
      function jbFunc() {
        var jbVar = 'Ipsum';
        document.write( jbVar );
      }
      jbFunc();
    </script>
  </body>
</html>

Since I called the value of jbVar inside the function, the value of the local variable

Ipsum

is output.

example 3

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
  </head>
  <body>
    <script>
      var jbVar = 'Lorem';
      function jbFunc() {
        jbVar = 'Ipsum';
        document.write( jbVar );
      }
      jbFunc();
      document.write( jbVar );
    </script>
  </body>
</html>

Specifying the value of the variable without using var inside the function will change the value of the global variable. therefore,

IpsumIpsum

is output.

728x90
LIST