Variables in JavaScript

Introduction

In this Blog, we will cover Variables in JavaScript. 

What are Variables in JavaScript?

A variable is a named storage location in a computer's memory where data values can be stored and retrieved. In programming, variables are used to store values that can change during the execution of a program. Variables are declared using a specific syntax in each programming language and are given a unique name that is used to refer to the value stored in the memory location.

Types of Variable in Javascript?

There are Three Types of Variable in JavaScript

  • var
  • let
  • const

How to declare a variable in JavaScript?

var varVariable = value;
let letVariable = value; 
const constVariable = value;

Var in JavaScript

Variables declared with var have function scope, meaning that they are accessible within the function where they are declared and also within any nested functions. If a var variable is declared outside of a function, it has a global scope and is accessible throughout the entire program. var variables can be re-assigned to a new value, and they are also hoisted, meaning that they are moved to the top of their scope and can be accessed before they are declared.

var x = 2;

console.log(x);
// output: 2

 var example 1

function Print() {
  var x = 1;
  function InnerPrint() {
    var y = 2;
    console.log(x); // 1 
    console.log(y); // 2 
  }

  InnerPrint();
  console.log(x); // 1 
  console.log(y); // ReferenceError: y is not defined // as it is called outside the scope 
}

Print();

var example 2

Let in JavaScript

Variables declared with let have block scope, meaning that they are accessible within the block where they are declared, as well as within any nested blocks. let variables can be re-assigned to a new value, but they are not hoisted.

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // output: 2
}

console.log(x);
// output: 1

Let example

Const in JavaScript

Variables declared with const have block scope and cannot be re-assigned to a new value after they have been declared. const variables are also not hoisted.

const PI = 3.14;
PI = 3.15; // TypeError: Assignment to constant variable.

const example

Note. It's good practice to use const for values that you don't want to change and let for values that will change during the execution of your program.

Summary

In this blog, here we tried to understand the types of Variables in JavaScript.