Variables are the constructing blocks of any programming language. In JavaScript, a variable can be utilized to retailer reusable values. These values will be something from Quantity, Boolean, String, and even a price returned from a operate. The values of the variables are allotted utilizing the task operator(“=”).
There are some primary guidelines to declare a variable in JavaScript:
- These are case-sensitive
- Can solely start with a letter, underscore(“_”) or “$” image
- It could possibly include 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 determined at runtime. Subsequently there is no such thing as a have to explicitly outline the kind of a variable. We are able to declare variables in JavaScript in 3 ways:
Syntax:
var geek = "Whats up Geek" // declaration utilizing var let $ = "Welcome" // declaration utilizing let const _example = "Gfg" // declaration utilizing const
All three key phrases do the fundamental process of declaring a variable however with some variations Initially, all of the variables in JavaScript have been written utilizing the var key phrase however in ES6 the key phrases let and const have been launched.
Instance 1: On this instance, we are going to declare variables utilizing var
Javascript
|
Output:
Whats up Geeks 10 12 22
Instance 2: On this instance, we are going to declare variables utilizing let
Javascript
|
Whats up learners becoming a member of 12 becoming a member of 12
To study extra about JavaScript let verify 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 price completely to a variable. So after we attempt to change the worth of a variable declared with the const key phrase it’s going to throw an error. The variables declared with var and let are mutable that’s their worth will be modified however variables declared utilizing const are immutable.
To study extra about JavaScript const verify this text JavaScript Const
Observe: 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 in a position to entry them outdoors their block.
To study 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 | will be redeclared | can’t be redeclared | can’t be redeclared |
Hoisting | hoisted at prime | hoisted at prime | hoisted at prime |