What Are Variables in JavaScript?
Declaring Variables with let, const, and var
JavaScript let
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.
const PI = 3.14159;
const MAX_USERS = 100;
const API_KEY = "abc123xyz";
// This will cause an error:
// PI = 3.14; // TypeError: Assignment to constant variableWhen 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.
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
Strings: Working with Text Data
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
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.
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
undefined: Uninitialized Variables
let notAssigned;
console.log(notAssigned); // undefined
function noReturn() {}
console.log(noReturn()); // undefinednull: Intentional Absence of Value
let selectedUser = null; // No user selected yet
let response = null; // Placeholder for API responseKey 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.
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: 1000Increment and decrement: Use ++ and -- for adding or subtracting one.
let count = 5;
count++; // Now 6
count--; // Back to 5Assignment Operators
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:
// 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
constby default: Only useletwhen you need to reassign values. - Avoid
var: Stick withletandconstfor 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
constvariables. - Not understanding the difference between
nullandundefined. - Performing operations on
undefinedornullvalues.