JavaScript Variables

What is a Variable?

In JavaScript, a variable is a container for storing data values. Variables allow programmers to label data with a descriptive name, so the program can be understood more clearly by the reader and maintained more easily. JavaScript uses the keywords var, let, and const for variable declarations, each serving different purposes and scopes.

These distinctions are crucial for writing clear, effective code and understanding how variables behave differently depending on their declaration context in JavaScript. Understanding the scope and mutability of variables declared with var, let, and const can help prevent bugs and aid in maintaining code.

Practical Examples

Using var

var greeting = 'Hello World!';
    console.log(greeting); // Outputs: Hello World!
    // Re-declaring and updating var
    var greeting = 'Hello again!';
    console.log(greeting); // Outputs: Hello again!

Using let

let counter = 1;
    counter = 2; // Updating let variable
    console.log(counter); // Outputs: 2
    // let cannot be re-declared in the same scope
    // let counter = 3; // This would cause an error

Using const

const pi = 3.14;
    console.log(pi); // Outputs: 3.14
    // const must be initialized and cannot be re-assigned
    // pi = 1.59; // This would cause an error

These examples show the typical use cases for var, let, and const in JavaScript, highlighting the importance of choosing the right type of variable based on the needs of your code.

Try it Yourself

Type your own greeting message and see it displayed below:

Test Your Knowledge: JavaScript Variables

Which keyword declares a variable that cannot be reassigned?