What are Variables in JavaScript?

Hey everyone! in this module, I am going to talk about What are Variables in JavaScript? And how to declare them in JavaScript. So, let’s start.

what are variables in javascript

What are Variables in JavaScript?

  • Variables as the name suggest are anything whose values vary.
  • You can assume a variable as a container or box which is used to hold values.
  • A JavaScript variable is a name given to a memory location that is used to store values.
  • Memory is allocated to a variable used in the program and is given some name.

why do we need variables

Why do we need variables?

Now, you might be thinking, why do we need variables? Let’s take an example.
Assume you want to use your name many times in a program, then you need to write your name again and again. This becomes tedious when the name is too long. The solution is to store your name in some container or you can say variable so that you can use it later whenever required.

Hence, to store the values and reuse them later in a program whenever required, we need variables. Let’s now see how to declare variables in JavaScript.

How to declare variables in JavaScript?

In JavaScript, we can declare variables using var, let, or const keywords. As we know JS is an untyped language, so we don’t need to specify the data type of variable.
Syntax

//Using var keyword
var variable_name= value;
//Here, initializing value is optional
var name=’Rahul’;
var num;
//Using let keyword
let variable_name=value;
//Here, the initialization of value is optional.
let name=’Neha’;
let num;
//Using const keyword
const variable_name= value;
const name=’Suraj’;

Here, the initialization of variables is mandatory when declaring variables using the const keyword otherwise you will get an error.

What are the rules for declaring variables?

  • A variable or identifier should begin with an underscore (_) symbol, a dollar ($) sign, or an alphabet (a-z or A-Z).
  • We can use digit (0-9) after underscore, dollar, or letter.
  • A variable name shouldn’t have any blank space or special character except the underscore (_) and dollar ($) sign.
  • A variable name or identifier cannot be a JavaScript keyword.

Let’s see some examples for valid identifiers or variable names:

  • _num is valid.
  • 123abc is invalid.
  • $name is valid.
  • %age is invalid.
  • name123 is valid.
  • abc^ is invalid.

You might be thinking what’s the difference between creating variables using var, let, and const keywords. But there’s a difference between them, let’s see each one of them.

  1. var is globally or function scoped whereas let and const are block-scoped i.e., can only be accessed within the block they were declared.
    Here’s an example:

    function fun(){
      {
        // Block scope
        let firstname='Rahul';
        const lastname='Sharma';
        var age=22;
        //Name:RahulSharma and Age:22
        console.log('Name: ',firstname+lastname,'and Age:',age);
      }
    
      // function scope
      console.log(‘Age:’,age); // 22
      console.log('Name: ',firstname+lastname); // Error
    }
    fun();
    

    In the above example, variable age has been declared using var keyword and firstname & lastname have been declared using let & const keywords.
    We see that age has been declared inside a block but we can still access it outside the block. Variables firstname & lastname are also declared inside a block but cannot be accessed outside that block so we will get an error.

  2. var keyword is used to declare variables till ES5 and from ES6 or ECMAScript 2015, let and const are also introduced to declare variables in JavaScript.
    // ES 5
    var x=4;
    console.log(x);
    
    // ES6
    let a=3;
    const age=18;
    console.log(a);
    console.log(age);</li>
    
  3. Using var and let keywords, we can update the values of variables but this is not allowed using const keyword.
    var a=5;
    a=6;
    let name=’Rahul’;
    name=’Neha’;
    const age=21;
    age=22; // error</li>
    
  4. Using var and let keywords, it is not mandatory to initialize the variable at the time of declaration but this is mandatory in the case of the
    const keyword.
    var a;
    a=10;
    let b;
    b=3;
    const c; // error
    c=10;
    
  5. var variables can be re-declared within their scope whereas let and const variables cannot be redeclared.
    var a=3;
    var a=5;
    let b=4;
    // Syntax Error
    let b=5;
    const c=7;
    // Syntax Error</li>
    

What is the hoisting of var, let, and const?

Hoisting is the default behaviour, of JavaScript in which function and variable declarations are placed at the top of scope before their code execution. In simple words, a variable is used or accessed before it has been declared. Hoisting will not work during initialization, it works only during declarations.

Variables declared with var are moved to the top of their scope and initialized with undefined whereas let and const variables are also hoisted to the top of the scope but there they are not initialized. It will throw a Reference Error.

console.log(a); // undefined
var a;
console.log(a); // Reference error: cannot access ‘a’ before initialization
let a=4;
console.log(a); // Reference error: cannot access ‘a’ before initialization
const a=5;

You might be thinking about which keyword to use when declaring variables in JavaScript.
Modern JavaScript uses let and const keywords rather than var to declare variables. When you want a variable that doesn’t change its value, then use the const keyword to declare variables.

What are the types of variables in JavaScript?

Local variables

Variables are declared and only accessed inside a block or function.

function check(){
  let age=18;
  if(age>=18)
    return 'Eligible';
  else
    return 'Not Eligible';
}
console.log(check());

In the above example, age is a local variable and can only be accessed within a function. Using outside it, we will get an error.

Global Variables

Variables that are declared outside the block or function accessed throughout the program from anywhere.

let age=18;
function check(){
  if(age>=18)
    return 'Eligible';
  else
    return 'Not Eligible';
}
console.log(check());
console.log(age);

In the above example, age is declared outside the function so it can be accessed from anywhere in the program.

I hope you have understood what are variables in JavaScript and how to declare them. If you want more tutorials like these, stay connected with us. Until then, Stay Safe, Stay healthy.