Lesson 2 of 1620 min read

JavaScript Variables

Discover the fundamentals of JavaScript variables in this comprehensive tutorial. Learn how to declare, initialize, and use variables with let, const, and var. Understand scope, naming conventions, and best practices that will set you up for success in JavaScript programming.

What Are Variables in JavaScript?

Variables are containers that store data values in your JavaScript programs. Think of them as labeled boxes where you can keep information and retrieve it later. JavaScript provides three ways to declare variables: let, const, and var.

Declaring Variables with let, const, and var

JavaScript let

The let keyword declares block-scoped variables that can be reassigned. It's the most commonly used declaration in modern JavaScript.
javascript - index.js
let userName = "Sarah";
let userAge = 28;
let isLoggedIn = true;

// You can reassign let variables
userName = "Michael";
When to use let: Use let when you know the variable's value will change during program execution.

JavaScript const

The const keyword creates block-scoped variables that cannot be reassigned. This is ideal for values that should remain constant throughout your code.

javascript
const PI = 3.14159;
const MAX_USERS = 100;
const API_KEY = "abc123xyz";

// This will cause an error:
// PI = 3.14; // TypeError: Assignment to constant variable
When to use const: Use const by default for all variables unless you specifically need to reassign them. This makes your code more predictable and easier to debug.

JavaScript var

The var keyword is the oldest way to declare variables in JavaScript. It has function scope rather than block scope, which can lead to unexpected behavior.

javascript
var oldStyleVariable = "I'm using var";
var counter = 0;
Best practice: Avoid using var in modern JavaScript. Use let or const instead for better scoping and fewer bugs.

Primitive Data Types in JavaScript

JavaScript has several primitive data types that represent simple values. Understanding these fundamentals is essential for effective programming.

Strings: Working with Text Data

Strings represent textual data enclosed in quotes. You can use single quotes, double quotes, or backticks.
javascript
let firstName = "John";
let lastName = 'Doe';
let greeting = `Hello, ${firstName}!`; // Template literal

// String concatenation
let fullName = firstName + " " + lastName;
<p>
  <strong>String Methods:</strong>
  JavaScript provides numerous built-in methods for string manipulation, including
  <code>length</code>, <code>toUpperCase()</code>, <code>toLowerCase()</code>, and
  <code>substring()</code>.
</p>

Numbers: Integer and Floating-Point Values

JavaScript uses a single number type for both integers and decimals, making numeric operations straightforward

javascript
let age = 25;              // Integer
let price = 19.99;         // Floating-point
let temperature = -5;      // Negative number
let billion = 1e9;         // Scientific notation

Special Numeric Values: JavaScript includes special numeric values such as Infinity, -Infinity, and NaN (Not a Number).

Booleans: True or False Values

Booleans represent logical values and are essential for conditional logic and control flow.

javascript
let isActive = true;
let hasPermission = false;
let isAdult = age >= 18;   // Result of comparison

Boolean Context: Many JavaScript operations automatically convert values to booleans, with falsy values including false, 0, empty strings, null, undefined, and NaN.

Understanding undefined and null

These two special values represent the absence of data but with subtle differences.

undefined: Uninitialized Variables

Variables declared without a value are automatically assigned undefined.
javascript
let notAssigned;
console.log(notAssigned);  // undefined

function noReturn() {}
console.log(noReturn());   // undefined

null: Intentional Absence of Value

null represents the deliberate absence of any object value. It's assigned explicitly by programmers.
javascript
let selectedUser = null;   // No user selected yet
let response = null;       // Placeholder for API response
Key difference: undefined means a variable exists but has no value, while null is an intentional assignment indicating "no value."

Basic JavaScript Operators

Operators allow you to perform operations on variables and values. Let's explore the most common types.

javascript
let a = 10;
let b = 3;

let sum = a + b;          // Addition: 13
let difference = a - b;   // Subtraction: 7
let product = a * b;      // Multiplication: 30
let quotient = a / b;     // Division: 3.333...
let remainder = a % b;    // Modulus: 1
let power = a ** b;       // Exponentiation: 1000

Increment and decrement: Use ++ and -- for adding or subtracting one.

Increment and decrement: Use ++ and -- for adding or subtracting one.
javascript
let count = 5;
count++;  // Now 6
count--;  // Back to 5

Assignment Operators

Assignment operators assign values to variables and can combine assignment with arithmetic operations.
javascript
let x = 10;        // Basic assignment

x += 5;            // x = x + 5 (now 15)
x -= 3;            // x = x - 3 (now 12)
x *= 2;            // x = x * 2 (now 24)
x /= 4;            // x = x / 4 (now 6)
x %= 4;            // x = x % 4 (now 2)
Shorthand benefits: These compound operators make code more concise and often clearer in intent.

Practical Examples: Putting It All Together

Here's a real-world example combining variables, data types, and operators:

javascript
// E-commerce cart calculation
const TAX_RATE = 0.08;
let itemPrice = 49.99;
let quantity = 3;

let subtotal = itemPrice * quantity;
let tax = subtotal * TAX_RATE;
let total = subtotal + tax;

console.log(`Subtotal: $${subtotal.toFixed(2)}`);
console.log(`Tax: $${tax.toFixed(2)}`);
console.log(`Total: $${total.toFixed(2)}`);

Best Practices for Variables and Data Types

Best Practices for Using Variables

  • Use descriptive names: Choose variable names that clearly indicate their purpose.
  • Prefer const by default: Only use let when you need to reassign values.
  • Avoid var: Stick with let and const for better scoping.
  • Initialize variables: Assign values when declaring to avoid undefined.
  • Use consistent naming: Follow the camelCase convention for variable names.
  • Type awareness: Understand implicit type conversion to avoid unexpected results.

Common Mistakes to Avoid

Common Mistakes When Working with Variables

  • Forgetting to declare variables, which accidentally creates global variables.
  • Confusing = (assignment) with == or === (comparison).
  • Trying to reassign const variables.
  • Not understanding the difference between null and undefined.
  • Performing operations on undefined or null values.

Frequently Asked Questions

let allows you to reassign the variable to a new value, while const creates a constant that cannot be reassigned. Use const by default and only use let when you know you'll need to change the value later.

Use const by default for all variables. Use let only when you need to reassign the variable. Avoid var completely in modern JavaScript as it has confusing scoping rules and can lead to bugs.

If you assign a value to a variable without declaring it, JavaScript creates a global variable automatically. This is considered bad practice and can cause bugs. Always declare your variables with let or const.

undefined means a variable exists but hasn't been assigned a value, while null is a value you explicitly assign to indicate "no value" or "empty." Think of undefined as "not set yet" and null as "intentionally empty."