JavaScript tutorials > JavaScript Basics > Data Types & Variables > How do you declare a variable in JavaScript?

How do you declare a variable in JavaScript?

Learn how to declare variables in JavaScript using var, let, and const. Understand the differences and best practices for each keyword.

Introduction to Variable Declaration

In JavaScript, variables are used to store data. Declaring a variable means creating a named storage location in the computer's memory. JavaScript offers three keywords for declaring variables: var, let, and const. Each has its own characteristics and scope rules that determine where the variable can be accessed within your code.

Declaring Variables with var

The var keyword is the oldest way to declare variables in JavaScript. Variables declared with var have function scope, meaning they are accessible within the function in which they are declared. If declared outside of any function, they have global scope, accessible from anywhere in your code. var allows for redeclaration, meaning you can declare the same variable multiple times within the same scope.

var myVariable = 10;
console.log(myVariable); // Output: 10

var myVariable = 20; // Redeclaration allowed
console.log(myVariable); // Output: 20

Declaring Variables with let

The let keyword was introduced in ES6 (ECMAScript 2015). Variables declared with let have block scope, meaning they are only accessible within the block of code (e.g., inside an if statement, for loop, or a code block enclosed in curly braces {}) where they are defined. Unlike var, let does not allow redeclaration within the same scope, preventing accidental overwriting of variables. You can reassign a value to a let variable.

let myLetVariable = 30;
console.log(myLetVariable); // Output: 30

//let myLetVariable = 40; // Error: Identifier 'myLetVariable' has already been declared

myLetVariable = 40;
console.log(myLetVariable); // Output: 40

Declaring Variables with const

The const keyword, also introduced in ES6, is used to declare constants – variables whose values cannot be reassigned after initialization. Like let, const also has block scope. You must initialize a const variable when you declare it. While the variable itself cannot be reassigned, if the const variable holds an object or array, the properties of that object or elements of that array can still be modified.

const myConstVariable = 50;
console.log(myConstVariable); // Output: 50

//myConstVariable = 60; // Error: Assignment to constant variable
//const myConstVariable = 60; // Error: Identifier 'myConstVariable' has already been declared

Concepts Behind the Snippet: Scope

Scope determines the accessibility of variables. Variables declared with var have function scope, whereas let and const have block scope. This means variables declared with let and const are only accessible within the block of code in which they are defined. Variables declared outside of any function have global scope and can be accessed from anywhere in your code.

// Global scope
var globalVar = 'Global';
let globalLet = 'Global Let';
const globalConst = 'Global Const';

function exampleFunction() {
  // Function scope (for var)
  var functionVar = 'Function';

  if (true) {
    // Block scope (for let and const)
    let blockLet = 'Block Let';
    const blockConst = 'Block Const';
    console.log(globalVar); // Accessible
    console.log(globalLet); // Accessible
    console.log(globalConst); // Accessible
    console.log(functionVar); // Accessible
    console.log(blockLet); // Accessible
    console.log(blockConst); // Accessible
  }
  console.log(globalVar); // Accessible
  console.log(globalLet); // Accessible
  console.log(globalConst); // Accessible
  console.log(functionVar); // Accessible
  //console.log(blockLet); // Not accessible
  //console.log(blockConst); // Not accessible
}

exampleFunction();

console.log(globalVar); // Accessible
console.log(globalLet); // Accessible
console.log(globalConst); // Accessible
//console.log(functionVar); // Not accessible
//console.log(blockLet); // Not accessible
//console.log(blockConst); // Not accessible

Real-Life Use Case: Managing User Preferences

Consider a scenario where you need to manage user preferences, such as the website's theme. You can use const to store a list of valid themes, ensuring that this list remains unchanged. The user's chosen theme can be stored in a let variable as it may change over time. We initialize a const variable savedTheme with the value from localStorage, or default to 'light' if no theme is saved. Then we apply the theme to the webpage.

function updateUserPreferences(theme) {
  const validThemes = ['light', 'dark'];

  if (!validThemes.includes(theme)) {
    console.error('Invalid theme selected.');
    return;
  }

  localStorage.setItem('userTheme', theme);
  // Apply the theme to the website
  applyTheme(theme);
}

function applyTheme(theme) {
  document.body.className = theme;
}

const savedTheme = localStorage.getItem('userTheme') || 'light'; // Default theme
applyTheme(savedTheme);

// Example usage:
updateUserPreferences('dark');

Best Practices

  • Always use const for variables that should not be reassigned. This helps prevent accidental modification of important values.
  • Use let for variables that need to be reassigned within a scope.
  • Avoid using var in modern JavaScript. Stick to let and const to take advantage of block scope and prevent common errors.
  • Declare variables at the top of their scope for better readability.

Interview Tip

Be prepared to explain the differences between var, let, and const in detail, including their scope, hoisting behavior, and whether they allow redeclaration and reassignment. Understanding these distinctions is crucial for writing clean and maintainable JavaScript code.

When to use them

  • Use const when you have a variable that should never change its value after it's been assigned.
  • Use let when you have a variable whose value you'll need to change later on.
  • Avoid var in modern JavaScript code, particularly when you're writing complex applications.

Memory footprint

The memory footprint between var, let, and const is generally negligible in modern JavaScript engines. All three keywords reserve memory to store the variable's value. The key difference lies in how the variable is managed and accessed, not in the amount of memory allocated. Choosing the right keyword improves code readability and prevents unintended modifications which can indirectly impact performance.

Alternatives

While var, let, and const are the standard ways to declare variables in JavaScript, there aren't direct alternatives in terms of fundamental language features. However, depending on your specific need, you can use patterns or features that achieve similar goals:

  • Object Properties: Store related values within an object. The properties can be accessed and modified.
  • Closures: Create private variables by encapsulating them within a function's scope.
  • Immediately Invoked Function Expressions (IIFE): Create a new scope to avoid polluting the global namespace, though let and const largely replace the need for this.

Pros and Cons of Each Declaration Type

var

  • Pros: Widely supported across older browsers.
  • Cons: Function scope can lead to unexpected behavior due to hoisting and lack of block scope. Allows redeclaration and reassignment, potentially causing bugs.
let
  • Pros: Block scope helps prevent naming conflicts and accidental variable overwriting. Prevents redeclaration within the same scope, promoting code clarity.
  • Cons: Not supported in very old browsers (though transpilers can mitigate this).
const
  • Pros: Clearly indicates that a variable should not be reassigned, improving code readability and preventing errors. Block scope similar to let.
  • Cons: Not supported in very old browsers. Does not make the value immutable if it's an object or array, only the variable binding.

FAQ

  • What is the difference between let and const?

    Both let and const have block scope, but let allows you to reassign the variable after it's been initialized, while const does not. You must initialize a const variable when you declare it.
  • Why should I avoid using var?

    var has function scope, which can lead to unexpected behavior, especially in larger codebases. let and const provide block scope, which is more predictable and helps prevent errors related to variable hoisting and accidental overwriting.
  • What happens if I try to reassign a const variable?

    You will get a TypeError in strict mode. In non-strict mode, the assignment might silently fail.
  • Can I modify the properties of an object declared with const?

    Yes, you can modify the properties of an object declared with const. const only prevents reassignment of the variable itself, not modification of the value it holds. For example: const myObj = { name: 'Alice' }; myObj.name = 'Bob'; // This is allowed