Variables in JavaScript

Variables are used to reserve some space in the storage for storing a value. Moreover, a variable acts as a container which has a name, and it takes a value.

JavaScript is a smart language which detects the data type of the value itself and the variables are not bound to store a particular type of value.

Rules to create a variable name

1. Variable name starts with an alphabet, underscore(_) or dollar sign($) and not a digit.
2. It may be made up of alphabets, digits, underscore(_) and dollar sign($).
3. There must be no blank space between the characters.
4. It is not allowed to use keywords as variable names.

Valid variable names: Age, x, $y, new_value
Invalid variable names: 2x, new

Note: Variable names are case-sensitive, i.e city, City, CITY are three different variables.

How to create a Variable in JavaScript?

Basically, there are two ways to create or declare a variable.

  1. Using let Keyword
    Syntax:
    let variable_name;
    or
    let variable_name = value;

  2. Using var Keyword
    Syntax:
    var variable_ name;
    or
    var variable name = value;

At the time of declaration itself, you can initialize the variable, i.e. assign a value to it using assignment operator(=). However, it is entirely optional.

Example:

let x; 

var y = 10;

let z = 7.3;

var city = "Mumbai";

If you want to declare numerous variables in one statement, then individual variables must be separated by a comma.

Example:

let a, b, c;

How to store/change a value inside a variable?

While storing a value in a variable or changing the already stored value, there is no need to use the keyword var or let.

Syntax:
variable_name = value;

Example:

x = 50;
y = "new";

How to output the value of a Variable in JavaScript?

In JavaScript, there are various functions used to display the output. The data which is to be presented as output is passed as the parameter to these functions.

If you pass a character surrounded by the double quotes, it will be treated as a string and will be printed as it is. Therefore, while printing the value of a variable or a number, you must not use the quotation marks.

  • document.write(): This is a function which is used inside an HTML document to write something on the output.

Example:

<!DOCTYPE html>
<html lang="en">
 <head></head>
 <body>
  <script>
   var x = 10; 
   document.write("Value of x =", x); 
  </script>
 </body>
</html>

Output:

Value of x = 10

Note: If document.write() is executed after the page has loaded completely, all the HTML elements will disappear from the page.

  • console.log(): This is another function which logs (writes) the data on the browser console. However, you won't find any output on the webpage. To open the console in chrome, you can press F12.

It is useful for the purpose of debugging the JavaScript.

Example:

<!DOCTYPE html>
<html lang="en">
 <head></head>
 <body>
  <script>
   var name = "Akshay";
   console.log(name); 
  </script>
 </body>
</html>

Output:

Akshay
  • inner.HTML: This lets you write something inside the HTML elements like a Paragraph or a Heading.

Example:

<!DOCTYPE html>
<html lang="en">
 <head></head>
 <body>
  <h1 id="info"></h1>
   <script>
    document.getElementById("info").innerHTML= "JavaScript Tutorial"; 
   </script>
 </body>
</html>

Output:

JavaScript Tutorial
  • window.alert(): You can also display the data in the form of an alert box.

Example:

<!DOCTYPE html>
<html lang="en">
 <head></head>
 <body>
  <h1 id="info"></h1>
   <script>
    window.alert('JavaScript Tutorial');
   </script>
 </body>
</html>

Output:


Scope of Variables in JavaScript

Scope of variable refers to the area of accessibility. The part of the code where a variable can be used, is known as its scope.

It is quite obvious that a variable created inside a program can be accessed when the program starts. It can not be used after the program ends. The same way, a variable declared inside a function block can be accessed when the function starts and it can't be used after the end of the function block.

On the basis of scope, JavaScript variables are classified in two categories:

  • Global: As the name says, global variables can be accessed everywhere within a program. A global variable does not belong to any function in the program which means it is declared outside the block of every function.
  • Local: A variable declared inside a function is local variable of that function. It can not be used outside the block of the function.

Well, JavaScript has one more type.

  • Automatically Global: In case, a value is stored in an undeclared variable within a function. By undeclared, we mean that the variable has not been created yet and it is directly given a value. Then the scope of the variable becomes global (instead of being local) in that program.

Now let us see an example to understand the above three concepts.

Example:

let global_1 = 10;
 if(true){
  let local_1 = 20;
  new_value = 30;
  console.log('Inside the block:');
  console.log(global_1, local_1, new_value);
 }
console.log('Outside the block:');
console.log(global_1, local_1, new_value);

Output:

Inside the block:
10 20 30

Outside the block:
H:\Programming Stack\content\JavaScript\JS-codes\scope.js:11
console.log(global_1, local_1, new_value)
                      ^

Explanation:

  • In this program, global_1 is a global variable because it does not belong to block of any function.
  • A block of if statement is created, where a local variable named local_1 is created.
    One more variable named new_value, which is not declared yet is initialized within the block only. Since this variable belongs to the if block, it should behave like a local variable.
  • Now, all these three variables are accessed from inside and outside of the block using console.log().
  • In the output, you can clearly see that all the variables are successfully accessed inside the block. But, when acessed from outside, an error occured due to local_1. This shows that the local variable can not be accessed out of its block.

Now let us try to access only the global_1 and new_value outside the block.

let global_1 = 10;
 if(true){
  let local_1 = 20;
  new_value = 30;
  console.log('Inside the block:');
  console.log(global_1, local_1, new_value);
 }
console.log('Outside the block:');
console.log(global_1, new_value);

Output:

Inside the block:
10 20 30

Outside the block:
10 30

Explanation:

Now, the output shows that global_1 and new_value, both can be accessed from outside of the block. Here, new_value, which was directly initialized inside the if-block, automatically becomes a global variable.

Difference between let & var in JavaScript

Till now, you are aware that there are two keywords let and var which can declare the variables. So, there must be a difference between the two. This difference can be seen in case of local variables.

  • When the local variable is created using var keyowrd, it doesn't behaves as a local variable, it gains the global scope instead.
  • On the other hand, the scope of variable declared using let keyword remains local.

Therefore, it is highly recommended to use the keyword let while working with variables inside a function.

Example:

if(true){
 var local_1 = "I have used var keyword.";
 let local_2 = "I have used let keyword.";
}
console.log('Outside the block:');
console.log(local_1);
console.log(local_2);

Output:

Outside the block:
I have used var keyword.

H:\Programming Stack\content\JavaScript\JS-codes\scope.js:7
console.log(local_2);
^

Explanation:

In the above example, the if-block contains two variables,

  • local_1 which is created using var keyword 
  • local_2 which is declared using let keyword.

When both of these variables are accessed outside the function using console.log, you will find that the variable local_1 is accessible inspite of being a local variable. Whereas the variable local_2 is not accessible, it generates an error.