What are variables in JavaScript
Imagine variables as labeled containers where you can store different kinds of information. Think of them like boxes in your closet – you label each box so you know what’s inside. In JavaScript, variables hold data that your program can use and change.
1. Purpose of Variables
- Storing Data: Variables hold data like numbers, text, or even more complex things.
- Making Code Reusable: Instead of writing the same value multiple times, you store it in a variable and use the variable’s name wherever you need that value. This makes your code easier to update.
- Making Code Readable: Using descriptive variable names makes your code easier to understand.
2. Syntax for Declaring Variables
You declare (create) a variable using keywords like let, const, or var, followed by the variable’s name.
- let: Use let for variables that you might reassign later.
- const: Use const for variables whose values you don’t intend to change (constants).
- var: var is an older way to declare variables. While it still works, let and const are generally preferred in modern JavaScript.
- Example of Declaring Variables in JavaScript:
let myName; // Declares a variable named myName (using let)
const PI = 3.14; // Declares a constant named PI (using const)
var age; // Declares a variable named age (using var)
3. Naming Variables
- Variable names are case-sensitive (myName and myname are different).
- They can contain letters, numbers, underscores (_), and dollar signs ($).
- They must start with a letter, underscore, or dollar sign.
- They1 cannot be keywords (like let, const, if, for, etc.).
4. Assigning Values to Variables
- You assign a value to a variable using the assignment operator (=).
- Example of Assigning values to variables in JavaScript:
myName = "Alice"; // Assigns the string "Alice" to the variable myName
age = 25; // Assigns the number 25 to the variable age
5. Example of a simple JavaScript program
let message = "Hello, "; // Store "Hello, " in the variable message
let name = "Bob"; // Store "Bob" in the variable name
let greeting = message + name + "!"; // Combine the strings and store the result in the greeting variable
console.log(greeting); // Output: Hello, Bob!
- We declare two variables, message and name, and assign them string values.
- We create a new variable greeting and use the + operator to combine (concatenate) the strings from message, name, and “!”.
- console.log() displays the value of the greeting variable in the browser’s console.