JavaScript Variables

Variables are used as a containers to store the data values. We can place data into these containers and then refer to the data simply by naming the container.

JavaScript allows us to work with 3 primitive data types:

  • Numbers (Example 185, 9.5, etc.)
  • Strings (Example ‘This is string example’)
  • Boolean (true or false)

Before use, We must declare the variable in JavaScript, Variables are declared with the var keyword.

Example:

var num = 4;
var name, city;

In the above example x, name and city are the variables.

Variable num stores the value 4, while name and city are just declared, not contains any value right now.

Storing a value in a variable is call variable initialization. We can do variable initialization at the time of variable create (like we did with num) or at a later when we need that variable.

Example:

var num1 = 3;
var num2 = 5;
var total ;
total = num1 + num2;

Note – Use the var keyword only once for declaration or initialization of any variable name, we should not re-declare the same variable twice.

JavaScript variable can hold a value of any data type, that’s why JavaScript is called untyped language.

The variable’s value type can be change during the execution of the program and JS takes care of it automatically.

Scope of Variable

In JavaScript there are 2 types of scope:

  • Local scope
  • Global scope

The above scope determines the accessibility (visibility) of the variables.

Local Variables:

A local variable declared within a JavaScript function and visible only with a function where it is defined.

Since a local variable created with a function starts and deleted with the function is completed, we can define same name variable in different functions.

Example:

function myFun() {
var myNum = 8;
}

Global Variables:

Global variable declared outside a JavaScript function and accessible by all the functions on web page.

Example:

var myNum = 8;
function myFun() {
}

Note: If we declare a local variable or function parameter with the same name as a global variable, we effectively hide the global variable. Local variable takes precedence over a global variable with the same name.

Example:

<html>
<script>
var myNum = 8;
function myFun() {
var myNum = 9;
document.write(myNum);
}
<script>
</html>

Result : 9

Rules to define JavaScript Variable :

  • We should not use JavaScript reserved keywords as a variable name. Like for, break, Boolean, variable names are not valid.
  • Variable name should be start with character followed by numbers. Like num1 is valid and 1num is an invalid variable name.
  • In JavaScript variable names are case-sensitive. Like num1 and NUM1 are two different variables.

Leave a Reply