Welcome to your JS Let & Const journey! In this comprehensive guide, we'll explore variable declaration and understand the importance of let and const in JavaScript. Let's dive in!
A variable is a container used to store data in a program. In JavaScript, you can declare variables using the let or const keywords.
let name; // Declare a variable with let
const pi = 3.14; // Declare a constant with constš” Pro Tip: Use const for unchangeable values like pi and let for variables that may change throughout the program.
Variable hoisting is a JavaScript feature that moves the declaration of variables to the top of the current scope. However, assignment is not hoisted.
console.log(name); // undefined
let name = "John Doe";In the example above, the variable name is declared before being assigned a value, but the output is undefined because assignment is not hoisted.
let and const š”Variables declared with let and const are block-scoped, meaning they are only accessible within the block they are declared in.
if (true) {
let name = "John Doe";
}
console.log(name); // ReferenceError: name is not definedvar Keyword (Avoid it!) šThe var keyword is an older way to declare variables in JavaScript. It has function scope, not block scope, and can lead to confusion and unintended global variables.
function example() {
var name; // Function scope
console.log(name); // undefined
var name = "John Doe";
console.log(name); // John Doe
}
example();
console.log(name); // John Doe (because of function scope!)š” Pro Tip: Avoid using var in new JavaScript projects!
Let's create a simple real-world example using let and const. We'll build a shopping cart calculator!
// Declare variables using let and const
let items = [];
const cartTotal = document.getElementById("cartTotal");
// Add item to the cart
function addToCart(itemName, itemPrice) {
// Create new item object with name and price
const newItem = { name: itemName, price: itemPrice };
// Add new item to the cart
items.push(newItem);
// Calculate and display the total cart value
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
cartTotal.textContent = total;
}
// Test the function
addToCart("Shirt", 20);
addToCart("Pants", 30);In this example, we declared variables items and cartTotal with let and const, respectively. Then, we created a function addToCart() that allows adding items to the cart and updating the cart total.
Which keyword should be used for unchangeable values like `pi`?
What is the difference between variable hoisting and assignment hoisting in JavaScript?
Keep learning, and happy coding! š