A variable is a named storage location in a computer’s memory that holds a value that can be modified during program execution.
Variables act as containers for storing data values. Each variable has a name (identifier) and a data type, which determines the kind of values it can hold (such as integers, floating-point numbers, strings, etc.). Variables provide a way to label and work with data in a readable and organized manner.
Example: Here is an example of using variables in JavaScript:
// Variable declaration and initialization
let name = 'Alice'; // 'name' is a variable of type string
const age = 30; // 'age' is a constant variable of type number
// Reassigning a new value to the variable
name = 'Bob';
// Printing the values to the console
console.log(name); // Output: Bob
console.log(age); // Output: 30
// Using a variable in a function
function greet() {
let greeting = 'Hello, ' + name + '!';
console.log(greeting);
}
greet(); // Output: Hello, Bob!
Explanation of the Example:
- Declaration and Initialization:
let name = 'Alice';declares a variablenameof type string and initializes it with the value'Alice'.const age = 30;declares a constant variableageof type number and initializes it with the value30. - Reassignment: The value of the variable
nameis changed to'Bob'. - Function Scope: A local variable
greetingis declared within thegreetfunction, which combines the string'Hello, 'with the value of the variablename. - Console Output: The
console.logstatements print the values ofnameandage, and thegreetfunction prints the greeting message.