Variables in JavaScript

M2-R5.1 · Chapter 6: JavaScript and Angular JS · 3 min read

Variables in JavaScript

  • Variables are “containers” for storing information.

  • JavaScript variables are used to hold values or expressions.

  • A variable can have a short name, like x, or a more descriptive name, like carname

Rules for JavaScript variable names-

  1. Javascript variable can be declared with the var keyword.
  2. Variable names are case sensitive (y and Y are two different variables)
  3. Variable names must begin with a letter or the underscore character
  4. No Commas or Blank Spaces are allowed .
  5. Can not use any special character are allowed except Underscore(_).
  6. We can not take any keyword of JS as a variable.
  7. There are 3 ways to declare a javascript variable:
  • Using var
  • Using let
  • Using const

Example:

var a;

var name;

var address;

var salary;

After declaration, the variable has no value.

It has default value of undefined. You can use the equal(=) sign to assign a value to the variable.
Var address=”prayagraj”;

Declaring Multiple Javascript variables in single statement:-

It is possible to declare many variables using var keywords.Start with var keyword and then separate each variable with comma.

Example –

< html>
<head>
<title>javascript</title>
</head>
<body><h2>Multiple javascript variables</h2>
<p>In this example x,y and z are variables.</p>
<script>
var x=5,y=6;
var z=x+y;
document.write(z);
</script>
</body>
</html>

Scope of variable –


The scope of a variable is the area of the program where the variable is valid.

There are two types of variables in JavaScript –

  • Local variable

  • Global variable

Local variable-

  • A variable Is declared inside a block or function is known as Local variable.

  • It is accessible within function or block only.

<Script>
function f()
{
var a=10; // local variable
document.write(a);
}
f(); // calling JavaScript function
</Script>


Global variable –

  • A variable is declared out side the function is known as global variable.

  • It is accessible from any function or also outside the function.

<Script>
Var a=10; // Global variable
function f()
{
document.write(a);
}
f(); // calling JavaScript function
</Script>