Variables in Javascript



Like every other programming language, Javascript uses variables to store data. There are 3 keywords to create a variable in Javascript.

  1. let
  2. const
  3. var

Javascript Image

Let us try to understand each of these keywords

A. let

To create a regular variable in Javascript, we can use let keyword. An example usage is shown below:

let age;

Once the variable is created, you can assign a value to the variable using = operator as shown below:

age=17;

The variable can be declared and initialized with a value in the same line as well:

let age=17;

let keyword can be used to create variables of any data type such as number, string, boolean, etc. For e.g.

let city=”London”
city=”Beijing”

Unlike other programming languages like C or Java where the data type needs to be explicitly defined at the time of declaring a variable, Javascript can automatically guess the data type without the need for explicit data type declaration.



B. const

const keyword is used to declare a variable whose value is going to be constant and will not be changed. For e.g.

const MAX_AGE=100;

The const variables needs to be initialized at the time of declaration itself.

Unlike variables created using the let keyword, variables created using const keywords cannot be modified once initialized.

For e.g. If you try to execute below code, you will get an error

const PI=3.14;
PI=8;



C. var

This is the old keyword for variable declaration. It behaves the same way as let keyword with slight differences.

Variables can be declared using the var keyword in the following way:

var carName=”Toyota”

Similar to the way of variables declared using let keywords, variables created using var keyword can also be modified during runtime.

carName=”Kia”

The only difference between var and let keyword is that let keyword has block scope vs var keyword has function scope. In modern scripts, we should try to use let keyword instead of the old var keyword.

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount