JavaScript Variables
JavaScript Variables
JavaScript variables are fundamental building blocks that make dynamic programming possible. Think of variables as storage containers in which you can keep values—like numbers, text, or more complex data. Variables allow developers to store, manipulate, and reuse data, which is essential for building interactive and flexible applications.
Why Do We Need Variables in JavaScript?
Imagine building a website where you want to display a user’s score in a game, store their name, or adjust the price of a product based on user input. Variables make all of this possible by:
- Storing Data: They allow you to store data temporarily and use it throughout your code.
- Manipulating Values: You can perform calculations, update, or change values stored in variables, making your application interactive.
- Reducing Repetition: Instead of hardcoding values repeatedly, variables let you update a value once and reuse it across different parts of your code.
- Enhancing Readability: Named variables make your code easier to read and understand, as they can describe what data is being stored.
For example, if you're building a calculator, you might use variables to store numbers and then use those variables to perform calculations.
How to Declare Variables in JavaScript
JavaScript provides three main ways to declare variables: var
, let
, and const
. Each has different uses and scoping rules, which we’ll explore below.
JavaScript let
The let
keyword is used to declare variables that can change over time. Variables declared with let
are scoped to the block in which they are defined, meaning they only exist within specific parts of the code.
Example of Using let
:
1let score = 100; // Declares a score variable with a value of 100
2score = score + 10; // Updates score to 110
In this example:
score
initially holds the value100
.- Later, it’s updated to
110
by adding10
to it.
JavaScript Constants
The const
keyword is used to declare variables with values that shouldn’t change. Once a variable is assigned a value with const
, that value cannot be reassigned.
Example of Using const
:
1const maxScore = 500; // Declares a constant with a fixed value of 500
If you try to reassign maxScore
later in the code, JavaScript will throw an error because const
variables cannot be changed.
JavaScript Var
The var
keyword is the original way to declare variables in JavaScript. Variables declared with var
are function-scoped rather than block-scoped, meaning they can lead to unexpected behavior if used within loops or conditional statements.
Example of Using var
:
1var playerName = "Alice"; // Declares playerName with a value of "Alice"
Differences Between var, let, and const
var
: Has function scope; its use is mostly limited to older JavaScript code.let
: Has block scope, making it safer for variables that may change.const
: Also block-scoped but meant for variables with fixed values that should not change.
Working with Data Types in JavaScript Variables
JavaScript variables can hold different types of data, the most common being numbers and strings (text).
- Numbers: Numbers don’t require quotes and can be used in arithmetic calculations.
1let price = 150; // Number
- Strings: Text values are called strings and should be enclosed in quotes (single or double).
1let userName = "John"; // String
- Booleans: Variables can also store
true
orfalse
values.
1let isActive = true; // Boolean
- Undefined and Null: Variables can also have values of
undefined
(no value assigned) ornull
(an empty value).
1let userStatus; // Undefined, as no value is assigned
2let emptyValue = null; // Null
Naming Variables: Identifiers in JavaScript
When creating variables, naming them clearly is essential. JavaScript has rules for naming:
- Names must start with a letter, underscore
_
, or dollar sign$
. - Names are case-sensitive (
score
andScore
are different). - Descriptive names improve readability, such as
userScore
rather thanx
.
1let totalAmount = 500;
2let isUserLoggedIn = true;
Assigning Values to Variables
In JavaScript, the equal sign (=
) is used to assign values to variables. This is known as the assignment operator.
Example:
1let hours = 8;
2hours = hours + 2; // Updates hours to 10
The assignment operator is different from the "equals" sign in algebra; it simply assigns a calculated value to the variable on the left.
Variable Arithmetic
JavaScript lets you perform calculations with variables. Here’s a basic example:
1let length = 10;
2let width = 5;
3let area = length * width; // Calculates area, result is 50
You can also combine strings (concatenate) using the +
operator:
1let firstName = "Sarah";
2let lastName = "Connor";
3let fullName = firstName + " " + lastName; // Combines into "Sarah Connor"
Declaring Multiple Variables at Once
For convenience, you can declare multiple variables in one statement by separating them with commas.
1let x = 10, y = 20, z = x + y;
Uninitialized Variables and
Variables declared without a value will have a default value of undefined
. You can assign a value later in the code.
1let age;
2console.log(age); // Output: undefined
3age = 30;
4console.log(age); // Output: 30
Re-declaring Variables
var
: Allows re-declaration within the same scope.let
andconst
: Do not allow re-declaration in the same scope, which helps prevent accidental changes to variables.
1var city = "London";
2var city; // Re-declaration is allowed with var
3
4let country = "UK";
5// let country; // Error: Cannot re-declare with let