JS Let & Const: Mastering Variable Declaration šŸŽÆ

beginner
21 min

JS Let & Const: Mastering Variable Declaration šŸŽÆ

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!

Understanding Variables šŸ“

A variable is a container used to store data in a program. In JavaScript, you can declare variables using the let or const keywords.

javascript
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 šŸ’”

Variable hoisting is a JavaScript feature that moves the declaration of variables to the top of the current scope. However, assignment is not hoisted.

javascript
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.

Block Scoping with let and const šŸ’”

Variables declared with let and const are block-scoped, meaning they are only accessible within the block they are declared in.

javascript
if (true) { let name = "John Doe"; } console.log(name); // ReferenceError: name is not defined

The var 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.

javascript
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!

Example Time! šŸŽÆ

Let's create a simple real-world example using let and const. We'll build a shopping cart calculator!

javascript
// 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.

Quiz Time! šŸŽÆ

Quick Quiz
Question 1 of 1

Which keyword should be used for unchangeable values like `pi`?

Quick Quiz
Question 1 of 1

What is the difference between variable hoisting and assignment hoisting in JavaScript?

Keep learning, and happy coding! šŸš€