In JavaScript, variables are used to store and manipulate data. They act as containers for storing values such as numbers, strings, objects, or functions. Variables play a crucial role in programming as they allow developers to work with dynamic data and perform operations on that data.
Variable Declaration and Initialization
In JavaScript, variables are declared using the var, let, or const keywords. Here's a brief explanation of each:
- var: Historically used for variable declaration but has some scoping issues. Not commonly used in modern JavaScript.
- let: Introduced in ES6 (ECMAScript 2015) and is block-scoped, meaning it is limited to the block (enclosed within {}) where it is declared.
- const: Also introduced in ES6 and is used for declaring constants whose values cannot be reassigned once initialized. It is also block-scoped.
Let's see some examples:
let y = 10; // Declaration and initialization of a variable using let
const PI = 3.14; // Declaration and initialization of a constant using const
Data Types in JavaScript Variables
JavaScript is a dynamically typed language, which means that variables can hold values of different types without explicitly specifying the type. Some common data types in JavaScript include:
- Numbers: Represents numeric values, e.g., 10, 3.14.
- Strings: Represents textual data enclosed within single ' or double " quotes, e.g., 'Hello', "JavaScript".
- Booleans: Represents true or false values, e.g., true, false.
- Objects: Represents complex data structures, e.g., {} (object literal), new Date() (date object).
- Arrays: Represents ordered collections of elements, e.g., ['apple', 'banana', 'cherry'].
- Functions: Represents reusable blocks of code, e.g., function add(a, b) { return a + b; }.
Variable Naming Rules
When naming variables in JavaScript, there are certain rules to follow:
- Variable names can contain letters, digits, underscores _, and dollar signs $.
- Variable names must start with a letter, underscore _, or dollar sign $. They cannot start with a digit.
- Variable names are case-sensitive (myVariable is different from myvariable).
- JavaScript reserves certain words (keywords) that cannot be used as variable names, such as if, else, function, etc.
Examples of JavaScript Variables
Let's look at some examples to understand how variables are used in JavaScript:
Example 1: Numeric Variables
let num1 = 10;
let num2 = 5;
let sum = num1 + num2;
console.log(sum); // Output: 15
In this example, num1 and num2 are numeric variables, and sum stores the result of adding num1 and num2.
Example 2: String Variables
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName;
console.log(fullName); // Output: John Doe
Here, firstName and lastName are string variables, and fullName stores their concatenated value.
Example 3: Boolean Variables
let isLogged = true;
if (isLogged) {
console.log('User is logged in.');
} else {
console.log('User is not logged in.');
}
The isLogged variable is a boolean variable that determines if a user is logged in or not.
Example 4: Array Variables
console.log(fruits[0]); // Output: apple
In this example, fruits is an array variable that stores a list of fruits.
Example 5: Object Variables
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
console.log(person.firstName); // Output: John
The person variable is an object variable that stores information about a person.
Example 6: Constant Variables
const PI = 3.14;
let radius = 5;
let area = PI * radius * radius;
console.log(area); // Output: 78.5
In this example, PI is a constant variable storing the value of π (pi), which remains constant throughout the program.
Scope of Variables
Variables in JavaScript have different scopes based on how and where they are declared:
Global Scope: Variables declared outside of any function have global scope and can be accessed throughout the program.
function myFunction() {
console.log(globalVar); // Output: I am global
}
myFunction();
Function Scope: Variables declared inside a function have function scope and can only be accessed within that function.
function myFunction() {
let localVar = 'I am local';
console.log(localVar); // Output: I am local
}
myFunction();
console.log(localVar); // Throws ReferenceError: localVar is not defined
Block Scope (let and const): Variables declared using let and const have block scope, which means they are limited to the block in which they are declared (e.g., inside {}).
if (true) {
let blockVar = 'I am in block';
console.log(blockVar); // Output: I am in block
}
console.log(blockVar); // Throws ReferenceError: blockVar is not defined
Practice Excercise Practice now