Variables are the constructing blocks of any programming language. In JavaScript, a variable can be utilized to retailer reusable values. These values might be something from Quantity, Boolean, String, and even a worth returned from a operate. The values of the variables are allotted utilizing the task operator(“=”).
There are some fundamental guidelines to declare a variable in JavaScript:
- These are case-sensitive
- Can solely start with a letter, underscore(“_”) or “$” image
- It could comprise letters, numbers, underscore, or “$” image
- A variable title can’t be a reserved key phrase.
JavaScript is a dynamically typed language so the kind of variables is set at runtime. Subsequently there isn’t a must explicitly outline the kind of a variable. We are able to declare variables in JavaScript in 3 ways:
Syntax:
var geek = "Good day Geek" // declaration utilizing var let $ = "Welcome" // declaration utilizing let const _example = "Gfg" // declaration utilizing const
All three key phrases do the essential job of declaring a variable however with some variations Initially, all of the variables in JavaScript had been written utilizing the var key phrase however in ES6 the key phrases let and const had been launched.
Instance 1: On this instance, we are going to declare variables utilizing var
Javascript
|
Output:
Good day Geeks 10 12 22
Instance 2: On this instance, we are going to declare variables utilizing let
Javascript
|
Good day learners becoming a member of 12 becoming a member of 12
To be taught extra about JavaScript let examine this text JavaScript Let
Instance 3: On this instance, we are going to declare the variable utilizing the const key phrase
Javascript
|
Output:

Clarification: const key phrase is used after we assign a worth completely to a variable. So after we attempt to change the worth of a variable declared with the const key phrase it can throw an error. The variables declared with var and let are mutable that’s their worth might be modified however variables declared utilizing const are immutable.
To be taught extra about JavaScript const examine this text JavaScript Const
Be aware: The newly launched key phrases let and const are block scoped whereas var is operate scoped.
Allow us to see an instance to grasp the distinction:
Instance:
Javascript
|
Output:

Clarification: Since variables “a” and “c” are block scoped so we weren’t capable of entry them outdoors their block.
To be taught extra concerning the scope of variables confer with this text Understanding variable scopes in JavaScript
Comparability of properties of let, var, and const key phrases in JavaScript:
Property |
var |
let |
const |
---|---|---|---|
Scope | operate scoped | block scoped | block scoped |
Updation | mutable | mutable | immutable |
Redeclarartion | might be redeclared | can’t be redeclared | can’t be redeclared |
Hoisting | hoisted at high | hoisted at high | hoisted at high |