JavaScript variables play a crucial role in storing and manipulating data within a program. They act as containers that hold different types of values, such as numbers, strings, booleans, and objects. In this article, we will explore the concept of JavaScript variables and provide examples to help you understand their usage.
Declaring Variables
In JavaScript, variables are declared using the var
, let
, or const
keywords. The var
keyword was traditionally used, but let
and const
were introduced in newer versions of JavaScript to provide better scoping and immutability.
Here’s an example of declaring a variable using the var
keyword:
var age = 25;
The above code declares a variable named age
and assigns it the value of 25.
Similarly, here’s an example using the let
keyword:
let name = "John";
In this case, the variable name
is declared and assigned the value “John”.
Lastly, the const
keyword is used to declare a constant variable whose value cannot be changed:
const PI = 3.14;
The variable PI
is assigned the value of 3.14 and cannot be reassigned later in the program.
Variable Scope
JavaScript variables have different scopes depending on how and where they are declared. The scope determines the accessibility and lifespan of a variable.
Variables declared with the var
keyword have function scope, meaning they are accessible within the function they are declared in, as well as any nested functions. However, they are not accessible outside of the function.
Variables declared with the let
and const
keywords have block scope, which means they are accessible within the block they are declared in, such as a loop or an if statement. They are not accessible outside of the block.
Using Variables
Once a variable is declared, you can use it to store and manipulate data. Here are a few examples:
// Numeric variables
var num1 = 10;
var num2 = 5;
var sum = num1 + num2;
console.log(sum); // Output: 15
// String variables
var firstName = "John";
var lastName = "Doe";
var fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
// Boolean variables
var isLogged = true;
var isLoggedIn = false;
console.log(isLogged); // Output: true
// Object variables
var person = {
name: "John",
age: 25
};
console.log(person.name); // Output: John
In the above examples, we perform arithmetic operations on numeric variables, concatenate strings, and access properties of an object using variables.
Conclusion
JavaScript variables are essential for storing and manipulating data within a program. They provide a way to reference and modify values throughout the execution of a script. By understanding how to declare, scope, and use variables effectively, you can write more dynamic and flexible JavaScript code.