Premium Javascript Course

JavaScript Variables

In JavaScript, variables are used to store data values. Understanding how to declare and use variables is fundamental to programming in JavaScript.

Declaring Variables

To declare a variable, you can use the let, const, or var keyword. Each keyword has different scopes and behavior:

Examples of Variable Declarations


// Using let
let name = "John";  // can be reassigned later
let age = 30;

// Using const
const birthYear = 1994;  // cannot be reassigned

// Using var (avoid using var in modern JavaScript)
var city = "New York";  // function-scoped variable
        

Variable Naming Rules

When naming variables in JavaScript, there are a few rules to follow:

Variable Scope

Scope refers to the context in which a variable is accessible. JavaScript has three types of scopes:

Example of Scope


let globalVariable = "I am global";

function checkScope() {
    var functionVariable = "I am inside a function";
    let blockVariable = "I am inside a block";
    
    console.log(globalVariable); // Accessible anywhere
    console.log(functionVariable); // Accessible within the function
    console.log(blockVariable);  // Accessible within the block
}
        

Reassigning and Redeclaring Variables

Variables declared with let can be reassigned, but they cannot be redeclared in the same scope:


// Reassigning with let
let x = 10;
x = 20;  // Valid reassignment

// Redeclaring with let (invalid in the same scope)
let y = 30;
let y = 40;  // SyntaxError: Identifier 'y' has already been declared
        

Constant Variables with const

Variables declared with const cannot be reassigned or redeclared in the same scope:


const z = 50;
z = 60;  // TypeError: Assignment to constant variable.
        

Best Practices for Using Variables

Conclusion

Understanding how to declare, use, and manage variables is a fundamental concept in JavaScript. By following best practices, you can write clean and efficient code that is easy to maintain and debug.