Understanding Variables in JavaScript: A Comprehensive Guide
Hello everyone and welcome to a new article on the JavaScript corner, your weekly Substack publication where, if you stick around long enough, you will learn the JavaScript’s features, from being a total beginner, to becoming comfortable in writing JavaScript code on your own.
Variables are fundamental building blocks in any programming language, and JavaScript is no exception. They serve as containers for storing data values that can be used and manipulated throughout your code. In this article, we'll dive deep into the world of JavaScript variables, exploring the different types, their scopes, and best practices for using them effectively.
The Evolution of Variable Declarations in JavaScript
JavaScript has evolved over the years, and with it, the ways we declare variables. Initially, we only had the `var` keyword, but ECMAScript 2015 (ES6) introduced `let` and `const`, providing developers with more options and better control over variable declarations.
var: The Original Variable Declaration
The `var` keyword has been around since the beginning of JavaScript. It has some unique characteristics that developers should be aware of:
1. Function-scoped or globally-scoped
2. Can be redeclared and reassigned
3. Hoisted to the top of its scope
Let's look at some examples:
```
var x = 10;
console.log(x); // Output: 10
var x = 20; // Redeclaration is allowed
console.log(x); // Output: 20
x = 30; // Reassignment is allowed
console.log(x); // Output: 30
function exampleFunction() {
var y = 5;
console.log(y); // Output: 5
}
exampleFunction();
console.log(y); // ReferenceError: y is not defined
```
In this example, we can see that `var` allows redeclaration and reassignment. Also, the variable `y` is only accessible within the function where it's declared.
let: Block-Scoped Variable Declaration
Introduced in ES6, `let` provides block-scoping for variables. This means that a variable declared with `let` is only accessible within the block it's declared in (including nested blocks). Key characteristics of `let` include:
1. Block-scoped
2. Cannot be redeclared in the same scope
3. Can be reassigned
4. Not hoisted
Here's an example illustrating the use of `let`:
let a = 5;
console.log(a); // Output: 5
// let a = 10; // SyntaxError: Identifier 'a' has already been declared
a = 15; // Reassignment is allowed
console.log(a); // Output: 15
if (true) {
    let b = 20;
    console.log(b); // Output: 20
}
// console.log(b); // ReferenceError: b is not defined
for (let i = 0; i < 3; i++) {
    console.log(i); // Output: 0, 1, 2
}
// console.log(i); // ReferenceError: i is not defined
As we can see, `let` provides better control over variable scope and prevents accidental redeclarations.
const: Constant Variable Declaration
Also introduced in ES6, `const` is used to declare constants - variables whose values cannot be reassigned. Key characteristics of `const` include:
1. Block-scoped
2. Cannot be redeclared or reassigned
3. Must be initialised at declaration
4. Not hoisted
Here's an example of using `const`:
const PI = 3.14159;
console.log(PI); // Output: 3.14159
// PI = 3.14; // TypeError: Assignment to a constant variable
// const PI = 3.14; // SyntaxError: Identifier 'PI' has already been declared
const user = { name: 'John', age: 30 };
user.age = 31; // This is allowed as we're modifying a property, not reassigning the variable
console.log(user); // Output: { name: 'John', age: 31 }
// user = { name: 'Jane', age: 25 }; // TypeError: Assignment to a constant variable
It's important to note that while `const` prevents reassignment of the variable itself, it doesn't make the value immutable if it's an object or array.
Global and Local Variables
Understanding the concept of global and local variables is crucial for writing clean and efficient JavaScript code.
Global Variables
Global variables are declared outside of any function or block and can be accessed from anywhere in your JavaScript code. They are properties of the global object (`window` in browsers, `global` in Node.js).
var globalVar = 'I am global';
let globalLet = 'I am also global';
function accessGlobal() {
    console.log(globalVar); // Output: I am global
    console.log(globalLet); // Output: I am also global
}
accessGlobal();
console.log(globalVar); // Output: I am global
console.log(globalLet); // Output: I am also global
While global variables can be convenient, they should be used sparingly as they can lead to naming conflicts and make code harder to maintain.
Local Variables
Local variables are declared inside a function or block and are only accessible within that function or block.
function localExample() {
    var functionVar = 'I am function-scoped';
    let blockLet = 'I am block-scoped';
    const blockConst = 'I am also block-scoped';
    console.log(functionVar); // Output: I am function-scoped
    console.log(blockLet); // Output: I am block-scoped
    console.log(blockConst); // Output: I am also block-scoped
    if (true) {
        let innerLet = 'I am inside the if block';
        console.log(innerLet); // Output: I am inside the if block
    }
    // console.log(innerLet); // ReferenceError: innerLet is not defined
}
localExample();
// console.log(functionVar); // ReferenceError: functionVar is not defined
// console.log(blockLet); // ReferenceError: blockLet is not defined
// console.log(blockConst); // ReferenceError: blockConst is not defined
Local variables help in encapsulating functionality and preventing unintended side effects in other parts of your code.
Best Practices for Using Variables in JavaScript
1. Use `const` by default, and only use `let` when you know the variable will be reassigned.
2. Avoid using `var` in modern JavaScript development.
3. Keep the scope of variables as narrow as possible.
4. Use descriptive and meaningful variable names.
5. Minimise the use of global variables.
6. Be aware of the temporal dead zone when using `let` and `const`.
7. When working with objects declared with `const`, remember that the properties can still be modified.
JavaScript Variable naming best practices
1. Use camelCase for variable and function names. Start with a lowercase letter and capitalise the first letter of each subsequent word. For example:
let firstName = 'John';
let numberOfUsers = 5000;
2. Use descriptive and meaningful names that clearly indicate the purpose of the variable. Avoid single letters or overly abbreviated names.
3. Keep names concise but not too short. Aim for 3-10 characters in length, but prioritise clarity over brevity.
4. For boolean variables, use "is" or "has" as prefixes:
let isActive = true;
let hasPermission = false;
5. For constants, use uppercase with underscores (UPPER_SNAKE_CASE):
const MAX_SIZE = 100;
const DEFAULT_COLOR = 'blue';
6. Avoid using reserved keywords, special characters (except $ and _), or starting with numbers.
7. For collections (arrays, lists), use plural nouns without adding type information:
let cars = ['Ford', 'Toyota', 'Honda'];
8. Avoid using Hungarian notation (prefixing variable names with their type).
9. Be consistent with your naming conventions throughout your codebase.
10. Use clear and relevant real-world examples in your variable names when possible, rather than placeholder names like 'foo' or 'bar'.
By following these conventions, you'll create more readable, maintainable, and professional JavaScript code. Remember that the goal is to make your code easily understandable by other developers (including your future self).
Conclusion
Understanding variables is crucial for mastering JavaScript. The introduction of `let` and `const` in ES6 has given developers more tools to write cleaner, more predictable code. By using these keywords appropriately and being mindful of variable scope, you can create more robust and maintainable JavaScript applications.
Remember, the choice between `var`, `let`, and `const` isn't just about personal preference – it's about writing code that clearly communicates your intentions and helps prevent bugs. As you continue to work with JavaScript, you'll develop a better intuition for when to use each type of variable declaration.
Till next week, happy coding!