Loading...

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:

  1. Storing Data: They allow you to store data temporarily and use it throughout your code.
  2. Manipulating Values: You can perform calculations, update, or change values stored in variables, making your application interactive.
  3. Reducing Repetition: Instead of hardcoding values repeatedly, variables let you update a value once and reuse it across different parts of your code.
  4. 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
2 lines
|
28/ 500 tokens
1
2
let score = 100; // Declares a score variable with a value of 100
score = score + 10; // Updates score to 110
Code Tools

In this example:

  • score initially holds the value 100.
  • Later, it’s updated to 110 by adding 10 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 lines
|
18/ 500 tokens
1
const maxScore = 500; // Declares a constant with a fixed value of 500
Code Tools

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 lines
|
18/ 500 tokens
1
var playerName = "Alice"; // Declares playerName with a value of "Alice"
Code Tools

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 lines
|
7/ 500 tokens
1
let price = 150; // Number
Code Tools
  • Strings: Text values are called strings and should be enclosed in quotes (single or double).
javascript
1 lines
|
8/ 500 tokens
1
let userName = "John"; // String
Code Tools
  • Booleans: Variables can also store true or false values.
javascript
1 lines
|
8/ 500 tokens
1
let isActive = true; // Boolean
Code Tools
  • Undefined and Null: Variables can also have values of undefined (no value assigned) or null (an empty value).
javascript
2 lines
|
21/ 500 tokens
1
2
let userStatus; // Undefined, as no value is assigned
let emptyValue = null; // Null
Code Tools

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 and Score are different).
  • Descriptive names improve readability, such as userScore rather than x.
javascript
2 lines
|
13/ 500 tokens
1
2
let totalAmount = 500;
let isUserLoggedIn = true;
Code Tools

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
2 lines
|
14/ 500 tokens
1
2
let hours = 8;
hours = hours + 2; // Updates hours to 10
Code Tools

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
3 lines
|
23/ 500 tokens
1
2
3
let length = 10;
let width = 5;
let area = length * width; // Calculates area, result is 50
Code Tools

You can also combine strings (concatenate) using the + operator:

javascript
3 lines
|
31/ 500 tokens
1
2
3
let firstName = "Sarah";
let lastName = "Connor";
let fullName = firstName + " " + lastName; // Combines into "Sarah Connor"
Code Tools

Declaring Multiple Variables at Once

For convenience, you can declare multiple variables in one statement by separating them with commas.

javascript
1 lines
|
8/ 500 tokens
1
let x = 10, y = 20, z = x + y;
Code Tools

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
4 lines
|
23/ 500 tokens
1
2
3
4
let age;
console.log(age); // Output: undefined
age = 30;
console.log(age); // Output: 30
Code Tools

Re-declaring Variables

  • var: Allows re-declaration within the same scope.
  • let and const: Do not allow re-declaration in the same scope, which helps prevent accidental changes to variables.
javascript
5 lines
|
36/ 500 tokens
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
Code Tools

Frequently Asked Questions

JavaScript variables are containers that store data values which can be accessed and modified throughout the code.

JavaScript uses var, let, and const to declare variables, each with different scoping and reassignment rules.

The 7 data types in JavaScript are Undefined, Null, Boolean, Number, BigInt, String, and Symbol.

== compares values with type conversion, while === compares both value and type without converting types.

Variable names in JavaScript must start with a letter, underscore, or dollar sign and can include numbers after the first character.

Still have questions?Contact our support team