Variable in JavaScript
Variable in JavaScript
In programming, we often need a named storage location to store the data or values. Using
variables, we can store the data in our program and access it afterward. In this article, we will learn
about variables in programming, their types, declarations, initialization, naming conventions, etc.
Variables in Programming
A Variables In Programming is a named storage location that holds a value or data. These values
can change during the execution of a program, hence the term “variable.” Variables are essential for
storing and manipulating data in computer programs. A variable is the basic building block of a
program that can be used in expressions as a substitute in place of the value it stores.
In programming, the declaration of variables involves specifying the type and name of a variable
before it is used in the program. The syntax can vary slightly between programming languages, but
the fundamental concept remains consistent.
C++
Java
Python3
C#
Javascript
var age;
let price;
C++
Java
Python
C#
Javascript
1. Global Variables:
Global variables in programming are declared outside any function or block in a program
and accessible throughout the entire codebase. In simpler words, Global variables can be accessed
in any part of the program, including functions, blocks, or modules.
C++
Java
Python3
C#
Javascript
class GFG {
static gfgFnc() {
console.log(GFG.globalVariable);
static main() {
console.log(GFG.globalVariable);
GFG.gfgFnc();
GFG.main();
Output
2. Local Variables:
Local variables in programming are declared within a specific function, block, or scope and are
only accessible within that limited context. In simpler words, Local variables are confined to the
block or function where they are declared and cannot be directly accessed outside that scope.
C++
Java
Python3
C#
Javascript
function gfgFnc() {
console.log(localVariable2);
function main() {
var localVariable1 = 5;
console.log(localVariable1);
gfgFnc();
if (true) {
console.log(localVariable3);
main();
Output
10
15
Difference between Variable and Constant:
Used for storing values that Used for storing fixed values
may vary or change during or parameters that should not
Use Cases program execution. be modified.
May have a default value, can May not have a default value,
be initialized outside and must be explicitly
Initialization functions or blocks initialized within the scope.