JavaScript Variables

JavaScript variables are containers for storing data values.

In this example, xy, and z, are variables:

Example

var x = 5;
var y = 6;
var z = x + y;

 

JavaScript Datatypes

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript allows you to work with three primitive data types −

  • Numbers, eg. 123, 120.50, etc.

  • Strings of text e.g. "This text string" etc.

  • Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as an object. We will cover objects in detail in a separate chapter.

Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  • Global Variables − A global variable has a global scope which means it can be defined anywhere in your JavaScript code.

  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Example

<html>
   <body onload = checkscope();>   
      <script type = "text/javascript">
         <!--
            var myVar = "global";      // Declare a global variable
            function checkscope( ) {
               var myVar = "local";    // Declare a local variable
               document.write(myVar);
            }
         //-->
      </script>     
   </body>
</html>

local