Javascript Global and local variables

JavaScript Variables

There are two types of variables in JavaScript. Global variables can be accessed from any location in the script, whereas local variables can be accessed only within the function.

1- Global Variable

Those variables that can be accessed from any location in the script are called global variables.

2- Local Variable

Those variables that can't be accessed from any location and can be accessed within the function are called local variables.

Variable Declaration Syntax

Variables declare with keyword ' var ' . var variable_name; E.g var a;

Addition of two numbers using JavaScript Variable

<html> <head> <title>JavaScript Variable </title> </head> <body> <script type="text/javascript"> function addition(a, b) { var c; //Local variable c = a+b; return c; } var z = addition(11, 5); //Global variable document.write("Sum of Two number is: " + z); </script> </body> </html> Output: Sum of Two number is: 16
Chapter Next »