search ]

JavaScript Variables and Constants for Beginners

JavaScript variables and constants are fundamental to any script. They are used to store data values that can be retrieved and manipulated later. This post will explore how to declare and use variables and constants in JavaScript with practical examples.

What are JavaScript Variables & How to Declare a Variable?

Variables in JavaScript are containers for storing data values. You can declare a variable using the var, let, or const keyword.

Using var

The var keyword declares a variable. It has function scope and can be redeclared.

var name = "John Doe";
console.log(name); // Output: John Doe
var name = "Jane Doe";
console.log(name); // Output: Jane Doe

Using let

The let keyword also declares a variable but with block scope. It cannot be redeclared within the same block.

let age = 25;
console.log(age); // Output: 25
age = 26;
console.log(age); // Output: 26
// let age = 30; // Error: Identifier 'age' has already been declared

Using const

The const keyword declares a constant, a variable whose value cannot be changed. It also has block scope.

const birthYear = 1995;
console.log(birthYear); // Output: 1995
// birthYear = 2000; // Error: Assignment to constant variable.

Scope of Variables

Understanding the scope is crucial when working with variables:

  • Global Scope: Variables declared outside any function have global scope and can be accessed from anywhere in the code.
  • Function Scope: Variables declared with var inside a function are local to that function.
  • Block Scope: Variables declared with let or const inside a block (e.g., inside a loop or an if statement) are local to that block.
var globalVar = "I am a global variable";

function testVar() {
    var functionVar = "I am a function variable";
    console.log(globalVar); // Accessible
    console.log(functionVar); // Accessible
}

if (true) {
    let blockVar = "I am a block variable";
    console.log(blockVar); // Accessible
}

testVar();
// console.log(functionVar); // Error: functionVar is not defined
// console.log(blockVar); // Error: blockVar is not defined

In the above example, globalVar is accessible globally, functionVar is accessible only within the testVar function, and blockVar is accessible only within the block where it is declared. Attempting to access functionVar or blockVar outside their respective scopes results in an error.

The next example demonstrates the differences between global, function, and block scopes. globalVar is accessible anywhere, functionVar is only accessible within the function, and blockVar is only accessible within the block it is defined in.

var globalVar = "I am a global variable";

function testScope() {
    var functionVar = "I am a function variable";
    if (true) {
        let blockVar = "I am a block variable";
        console.log(blockVar); // Accessible within the block
    }
    console.log(functionVar); // Accessible within the function
    // console.log(blockVar); // Error: blockVar is not defined outside the block
}

This table compares the behavior of JavaScript’s var, let, and const by key properties such as scope, re-declaration, re-assignment, hoisting, and their use in loops, helping developers understand the differences and choose the appropriate keyword based on the specific use case.

testScope();
console.log(globalVar); // Accessible globally
// console.log(functionVar); // Error: functionVar is not defined outside the function

This following table compares the behavior of JavaScript’s var, let, and const by key properties such as scope, re-declaration, re-assignment, hoisting, and their use in loops, helping developers understand the differences and choose the appropriate keyword based on the specific use case.

Propertyvarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Re-declarationAllowedNot allowedNot allowed
Re-assignmentAllowedAllowedNot allowed
HoistingYes, but initialized with undefinedYes, but in Temporal Dead Zone (TDZ) until declaredYes, but in Temporal Dead Zone (TDZ) until declared
InitializationOptionalOptionalRequired
Use in loopsNot suited for loops due to scope issuesBetter suited for loops due to block scopeWorks in loops but value cannot be reassigned

Rules for Naming JavaScript Variables

Naming variables in JavaScript follows specific rules to ensure clarity and avoid errors. Here are the key rules with examples:

  • Begin with a Letter, Underscore, or Dollar Sign: Variable names must start with a letter, an underscore (_), or a dollar sign ($).
let name = "John";
 let _private = "secret";
 let $price = 20;
    
  • Case-Sensitive: Variable names are case-sensitive, meaning name and Name are different variables.
let age = 30;
 let Age = 25;
    
  • No Reserved Keywords: Variable names cannot be reserved keywords like var, function, or class.
// let var = "value"; // Error: var is a reserved keyword
    let variable = "value"; // Correct
    
  • Use CamelCase for Multi-word Names: Use camelCase for variable names that consist of multiple words.
let firstName = "John";
 let totalPrice = 50;
    

Following these rules ensures that your code is readable and avoids common errors related to variable naming.

Best Practices

Here are some best practices when using variables and constants in JavaScript:

  • Use const by default, unless you know the value will change.
  • Use let for variables that will change.
  • Avoid using var as it has more complicated scoping rules and can lead to bugs.
  • Always declare variables before using them to avoid hoisting issues.

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compile phase, making them accessible before their actual declaration in the code. However, only the declarations are hoisted, not the initializations.

So generally using const  is a good practice because it ensures the variables you define cannot be reassigned, leading to fewer bugs and a more predictable codebase. Only use let when you know the variable’s value will change, such as in loops or conditional statements. This makes your intentions clear and improves code readability.

Avoid var due to its function-scoped nature and potential for hoisting issues, which can lead to unexpected behavior. Block-scoped let and const provide more reliable behavior and are easier to manage. Finally, always declare variables before using them to prevent hoisting-related bugs and improve code clarity.

Conclusion

Variables and constants are fundamental to programming in JavaScript. Understanding the differences between var, let, and const, as well as their scope, is crucial for writing clean and efficient code.

By following best practices, you can avoid common pitfalls and ensure your code is robust and maintainable.

Roee Yossef
Roee Yossef

I develop custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...

Recently Updated