Variables

Understand how variables store and manage data in JavaScript, including declaration keywords, scope, and best practices.

Present State

JavaScript variables are containers for storing data values. Variables can be declared using var, let, or const, each with different scoping and mutability rules. Understanding how variables behave in different scopes is key to writing effective JavaScript code.

Code Example

This example shows variable declaration and scope:

JavaScript Variables

// var: function scoped, can be redeclared and updated
var x = 10;
var x = 20; // redeclaration allowed
x = 30;     // update allowed

// let: block scoped, cannot be redeclared, can be updated
let y = 15;
// let y = 25; // Error: redeclaration not allowed
y = 35; // update allowed

// const: block scoped, cannot be redeclared or updated
const z = 50;
// z = 60; // Error: assignment to constant variable

console.log(x, y, z);
          

Key takeaways:

  • var has function scope and allows redeclaration.
  • let and const have block scope.
  • const variables must be initialized and cannot be reassigned.

Description

Variables in JavaScript are used to store data values which can be accessed and manipulated throughout the program. The three main keywords to declare variables are:
  • var: Function-scoped, can be redeclared and updated. Considered legacy and should generally be avoided in modern code.
  • let: Block-scoped, cannot be redeclared within the same scope but can be updated. Recommended for variables that will change.
  • const: Block-scoped, must be initialized at declaration, cannot be updated or redeclared. Ideal for constants or fixed references.
Understanding scope and hoisting of variables is important to prevent bugs and write predictable JavaScript.

Applications

  • State Management: Use variables to hold data state in applications.
  • Control Flow: Variables help track conditions and loop counters.
  • Data Storage: Store user input, API responses, and computed values.
  • Constants: Use const to protect important values from accidental reassignment.

Multiple Choice Questions

Q1: Which keyword is block scoped?

  • A. var
  • B. let
  • C. function
  • D. global

Answer: B. let

Q2: What happens if you redeclare a var variable?

  • A. Syntax Error
  • B. Runtime Error
  • C. It overwrites the previous variable
  • D. None of the above

Answer: C. It overwrites the previous variable

Q3: Can a const variable be reassigned?

  • A. Yes
  • B. No
  • C. Only inside functions
  • D. Only if declared globally

Answer: B. No

Q4: Which variable declaration keyword should be used for constants?

  • A. var
  • B. let
  • C. const
  • D. None of the above

Answer: C. const