Dive into hands-on exercises to master JavaScript variable declarations using var, let, and const. Enhance your coding skills with practical examples and solutions.
Welcome to the exciting world of JavaScript variables! In this section, we will engage in practical exercises to solidify your understanding of variable declarations using var
, let
, and const
. By the end of this chapter, you’ll be able to confidently declare and manipulate variables in various scopes and understand the nuances of reassignment and immutability.
Before diving into the exercises, let’s briefly recap the three primary ways to declare variables in JavaScript:
var
: The traditional way to declare variables. It has function scope and is hoisted to the top of its scope.let
: Introduced in ES6, let
provides block scope, making it more predictable and safer for modern JavaScript development.const
: Also introduced in ES6, const
is used to declare variables that should not be reassigned. It is block-scoped like let
.var
Task: Declare a variable using var
and assign it a value. Then, reassign it and log the result.
// Declare a variable using var
var greeting = "Hello, World!";
// Reassign the variable
greeting = "Hello, JavaScript!";
// Log the result
console.log(greeting); // Output: Hello, JavaScript!
Explanation: In this exercise, we declared a variable greeting
using var
and assigned it a string value. We then reassigned it to a new string and logged the result. Notice how var
allows reassignment.
var
Task: Declare a variable inside a function using var
and attempt to access it outside the function.
function showMessage() {
var message = "Inside function";
console.log(message); // Output: Inside function
}
showMessage();
// Try to access message outside the function
console.log(message); // Output: ReferenceError: message is not defined
Explanation: Variables declared with var
inside a function are scoped to that function. Attempting to access message
outside the function results in a ReferenceError
.
let
Task: Declare a variable using let
inside a block and observe its scope.
if (true) {
let blockScoped = "I am block scoped!";
console.log(blockScoped); // Output: I am block scoped!
}
// Try to access blockScoped outside the block
console.log(blockScoped); // Output: ReferenceError: blockScoped is not defined
Explanation: The let
keyword provides block scope, meaning the variable blockScoped
is only accessible within the block it was declared in.
let
Task: Declare a variable using let
, reassign it, and log the result.
let count = 1;
count = 2;
console.log(count); // Output: 2
Explanation: Similar to var
, variables declared with let
can be reassigned. Here, count
is initially set to 1
and then reassigned to 2
.
const
Task: Declare a constant using const
and attempt to reassign it.
const pi = 3.14;
// Try to reassign pi
pi = 3.14159; // Output: TypeError: Assignment to constant variable.
Explanation: Constants declared with const
cannot be reassigned. Attempting to do so results in a TypeError
.
const
Task: Declare a constant inside a block and observe its scope.
if (true) {
const blockConstant = "I am block scoped!";
console.log(blockConstant); // Output: I am block scoped!
}
// Try to access blockConstant outside the block
console.log(blockConstant); // Output: ReferenceError: blockConstant is not defined
Explanation: Like let
, const
is block-scoped. The constant blockConstant
is only accessible within the block it was declared in.
const
with ObjectsTask: Declare an object with const
and modify its properties.
const car = {
brand: "Toyota",
model: "Corolla"
};
// Modify the properties of the object
car.model = "Camry";
console.log(car.model); // Output: Camry
Explanation: While const
prevents reassignment of the variable itself, it does not prevent modification of the object’s properties.
Task: Predict the output of the following code snippet before running it.
var x = 10;
let y = 20;
const z = 30;
if (true) {
var x = 40; // Re-declares and reassigns x
let y = 50; // New block-scoped y
const z = 60; // New block-scoped z
console.log(x); // ?
console.log(y); // ?
console.log(z); // ?
}
console.log(x); // ?
console.log(y); // ?
console.log(z); // ?
Explanation:
x
is reassigned to 40
, affecting the outer x
due to var
’s function scope.y
and z
are block-scoped, so they do not affect the outer y
and z
.x
is 40
, y
is 50
, z
is 60
.x
is 40
, y
is 20
, z
is 30
.Now it’s your turn! Modify the code examples above and observe how changes affect the output. Try declaring variables with different scopes and see how reassignment works. Experimentation is key to mastering JavaScript variables!
To better understand how JavaScript handles variable scope and hoisting, let’s visualize it using a diagram.
graph TD; A[Global Scope] --> B[Function Scope] B --> C[Block Scope] A --> D[Hoisted Variables] B --> D C --> D
Diagram Description: This diagram illustrates the hierarchy of scopes in JavaScript. Variables declared in the global scope are accessible everywhere, while function-scoped variables are only accessible within the function. Block-scoped variables, declared with let
and const
, are confined to the block they are declared in. Hoisting affects variable declarations, moving them to the top of their scope.
Let’s reinforce what we’ve learned with a few questions:
var
and let
?const
variable?var
inside a function?let
?const
variable?In this section, we’ve explored the different ways to declare variables in JavaScript using var
, let
, and const
. We’ve seen how scope affects variable accessibility and how reassignment works with each keyword. Remember, practice makes perfect, so keep experimenting with these concepts in your own code!
Remember, this is just the beginning. As you progress, you’ll build more complex and interactive web pages. Keep experimenting, stay curious, and enjoy the journey!