VARIABLE IN JS
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.
DECLARATION OF VARIABLE: 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.
SYNTAX:
var/let/const variable_name;
EXAMPLE:
var age;
let price;
const grade = 'A';
TYPES OF VARIABLES:
- Global variables.
- Local variables.
GLOBAL VARIABLE:
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.
EXAMPLE:
class GFG {
static globalVariable = 5;
static gfgFnc() {
console.log(GFG.globalVariable);
}
static main() {
console.log(GFG.globalVariable);
GFG.gfgFnc();
}
}
GFG.main();
LOCAL VARIABLE:
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.
EXAMPLE:
function gfgFnc() {
var localVariable2 = 10;
console.log(localVariable2);
}
function main() {
var localVariable1 = 5;
console.log(localVariable1);
gfgFnc();
if (true) {
var localVariable3 = 15;
console.log(localVariable3);
}
}
main();

Top comments (0)