Lessons
JavaScript Basics
Operators in JavaScript
Conditional Statements in JavaScript
JavaScript Strings
JavaScript Arrays
JavaScript Loop
JavaScript Functions
Conclusion
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
:
javascript
1 2
let score = 100; // Declares a score variable with a value of 100 score = 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
:
javascript
1
const 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
:
javascript
1
var 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.
javascript
1
let price = 150; // Number
- Strings: Text values are called strings and should be enclosed in quotes (single or double).
javascript
1
let userName = "John"; // String
- Booleans: Variables can also store
true
orfalse
values.
javascript
1
let isActive = true; // Boolean
- Undefined and Null: Variables can also have values of
undefined
(no value assigned) ornull
(an empty value).
javascript
1 2
let userStatus; // Undefined, as no value is assigned let 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
.
javascript
1 2
let totalAmount = 500; let 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:
javascript
1 2
let hours = 8; hours = 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:
javascript
1 2 3
let length = 10; let width = 5; let area = length * width; // Calculates area, result is 50
You can also combine strings (concatenate) using the +
operator:
javascript
1 2 3
let firstName = "Sarah"; let lastName = "Connor"; let 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.
javascript
1
let 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.
javascript
1 2 3 4
let age; console.log(age); // Output: undefined age = 30; console.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.
javascript
1 2 3 4 5
var city = "London"; var city; // Re-declaration is allowed with var let country = "UK"; // let country; // Error: Cannot re-declare with let