var, let, and const in JavaScript
Introduction
Declaring variables in JavaScript using different syntaxes allows you to store and manipulate data values throughout your code. There are three primary ways to declare variables: var, let, and const. Each of these has unique features regarding scope, mutability, and behaviour.
Although you can technically declare variables without a keyword, doing so is not advisable. This approach can lead to unintended global variables and various scope issues—where the visibility and lifetime of variables can become unpredictable, making your code more difficult to debug and maintain. It is always best practice to declare variables using var, let, or const. This provides clarity about their intended use, ensuring your code is predictable, maintainable, and safer.
Let's dive deeply into var, let, and const in JavaScript
var
The original way to declare variables is in JavaScript. Variables declared with
varcan be reassigned easily, enabling you to modify their values at any point in your code.// Example var name = "isaac"; console.log(name); // output: isaac name = "Donald"; console.log(name); // name have been reassigned, output: Donaldvaris also function-scoped, which means that it's accessible throughout an entire function, no matter where it's declared in the function.// Example function ageFunction() { console.log(myAge); // output: undefined var myAge = "I am 10 years old!"; // This variable is function-scoped console.log(myAge); // output: "I am 10 years old!" } ageFunction(); console.log(myAge); // This will throw a ReferenceError: myAge is not definedIn the
ageFunction, the variablemyAgeis declared usingvar, which causes its declaration to be hoisted to the top of the function scope. This leads to the firstconsole.log(myAge);outputtingundefinedinstead of"I am 10 years old!"since the initialization hasn't happened yet. After the linevar greeting="I am 10 years old!", the secondconsole.log(myAge);correctly logs"I am 10 years old!"because the variable is now initialized. However, if you try to logmyAgeoutside of the function, you'll encounter aReferenceError, as it isn't accessible in the global scope and is only defined within the function.// Example { var greeting = "Hello, World!"; // Declare a variable using var inside a block console.log(greeting); // Output: Hello, World! } console.log(greeting); // Output: Hello, World! (still accessible outside the block)Using
varwithin a block scope can result in unexpected behaviour sincevaris not limited to block scope; it is either function-scoped or globally scoped if declared outside of a function. Consequently, if you declare a variable withvarinside a block, it will remain accessible even outside that block.let
Introduced in ES6 (also known as ECMAScript 2015), the
letkeyword allows for block-scoped variables, meaning they are confined to the block{ }where they are declared. This feature makesleta safer and more predictable choice, particularly in complex code, as it minimizes the risk of unintentional variable conflicts or scope problems. Additionally,letis versatile and can be reassigned as needed, allowing for more flexible variable management within a block.// Example let weekDay = "monday" console.log(weekDay) // output: monday weekDay = "friday" console.log(weekDay) // weekDay reassigned, output: friday// Example { let weekend = "weekend is a good time to rest."; console.log(weekend); // Output: weekend is a good time to rest. } // Trying to access 'message' outside the block console.log(weekend); // This will throw a ReferenceErrorThe variable
weekendis declared inside a block, making it accessible only within that block. JavaScript doesn’t recognizedweekendin this context because it only exists within the{ ... }where it was defined. This leads to aReferenceError, which is JavaScript's way of signaling that it can't locate the variable in the current context.// Example function calculateArea(length, width) { let area = length * width; // Declare a variable 'area' using let console.log("Original Area:", area); // Output the original area // Reassigning the area to a new value (e.g., adding a fixed value) area += 10; // Add 10 to the original area console.log("New Area after reassignment:", area); // Output the new area return area; // Return the modified area } // Example usage console.log(calculateArea(10, 10)); // Output: Original Area: 100, New Area after reassignment: 110 console.log(calculateArea(7, 3)); // Output: Original Area: 21, New Area after reassignment: 31In the
calculateAreafunction, the area is initially determined by multiplying the length and width, and this value is displayed as the "Original Area." Then, the area is increased by 10, resulting in a "New Area after reassignment," which is also shown. Ultimately, the updated area value is returned, providing the result after the addition in each example calculation.const
Introduced in ES6,
constbehaves similarly toletregarding block scope but is specifically used for constants. Once a variable is declared withconstand assigned an initial value, it cannot be reassigned.// Example const birthYear = 2014 console.log(birthYear) // output: 2014 birthYear = 2010 console.log(birthYear) //Uncaught TypeError: Assignment to constant variable// Example { const message = "I am inside a block."; // Declare a constant inside the block console.log(message); // Output: I am inside a block. } // Trying to access the constant outside the block console.log(message); // This will throw a ReferenceErrorThe constant message is declared within a block, making it block-scoped and only accessible inside that block. If you try to access
messagefrom outside the block, it will result in a ReferenceError since it's outside its defined context.// Example function calculateArea(radius) { const pi = 3.14; // Declare a constant for π // Calculate area using the constant const area = pi * radius * radius; return area; // Return the calculated area } console.log(calculateArea(5)); // Output: 78.5 console.log(calculateArea(10)); // Output: 314In the
calculateAreafunction, a constant namedpiis defined as 3.14 to represent π. This value is then utilized to compute the area of a circle using the formulapi * radius * radius, and the function returns this calculated result. For instance, when you callcalculateArea(5), it returns 78.5, andcalculateArea(10)returns 314, based on the radius given.However, if the
constvariable refers to an object or an array, you can still change the contents of that object or array; only the reference to the variable itself remains unchanged// Example on array const numbers = [1, 2, 3]; console.log('Original numbers:', numbers); // Output: Original numbers: [1, 2, 3] // Modifying an element in the array numbers[0] = 10; // This changes the first element from 1 to 10 console.log('Modified numbers:', numbers); // Output: Modified numbers: [10, 2, 3]// Example on object const car = { brand: "Toyota", model: "Camry" }; console.log("Original car:", car); // Output: Original car: { brand: 'Toyota', model: 'Camry' } // Changing a property of the object car.model = "Corolla"; // This is allowed because we're modifying the content of the object, not the reference console.log("Updated car:", car); // Output: Updated car: { brand: 'Toyota', model: 'Corolla' }Conclusion
In JavaScript, the most common variable declarations are made using
var,let, andconst, with differences in scoping and reusability. Whilevaris either function-scoped or globally scoped and can be redeclared or reinitialized,letandconstcannot be redeclared, althoughletcan be reinitialized. In current JavaScript coding, it is recommended to employletandconststatements to avoid issues related to block scope variables and reassignment.Thank you!