Variable

Suggest Improvement

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 variable name of type string and initializes it with the value 'Alice'. const age = 30; declares a constant variable age of type number and initializes it with the value 30.
  • Reassignment: The value of the variable name is changed to 'Bob'.
  • Function Scope: A local variable greeting is declared within the greet function, which combines the string 'Hello, ' with the value of the variable name.
  • Console Output: The console.log statements print the values of name and age, and the greet function prints the greeting message.