Modern Variables and Objects: let, const, and Destructuring
By the end of this lesson, you'll be able to:
- Use let and const appropriately in place of var
- Explain block scoping and why it matters
- Destructure objects and arrays to extract values concisely
Prerequisites: Module 3: "Styling with CSS, SLDS, and Static Resources"
let and const vs. var
let count = 0; // reassignable, block-scoped
const MAX = 100; // NOT reassignable, block-scoped
var oldStyle = 'x'; // function-scoped — avoid in modern code
let and const are block-scoped — confined to the nearest { }, unlike the older var, which is function-scoped and a real source of bugs inside loops and conditionals. Default to const; only reach for let when a variable genuinely needs to be reassigned later.
const Doesn't Mean "Fully Immutable"
const record = { name: 'Acme' };
record.name = 'Globomantics'; // allowed — the object's contents can change
record = {}; // NOT allowed — reassigning the variable itself fails
const only prevents the variable from being reassigned to point at something else — it does not freeze the object's internal properties. This distinction matters a lot once Module 3's reactivity and Lesson 7's immutability patterns come into play.
Destructuring Objects and Arrays
// Object destructuring — pulling specific properties out
const { data, error } = wireResult;
// Array destructuring — pulling items by position
const [first, second] = accountList;
Destructuring is used constantly in LWC — most commonly to pull data and error out of a @wire result, a pattern Module 6 relies on directly.
Why This Matters in Real Projects
LWC class fields and Apex/wire responses are almost always objects. Destructuring lets you extract exactly what you need in one clean line, instead of repeatedly writing wireResult.data, wireResult.error throughout a method.
Exercise
Rewrite this using destructuring: const name = record.Name; const email = record.Email;
Show hint
Object destructuring pulls multiple properties in one statement.
Exercise
Challenge: explain, as a comment, why declaring a variable with var inside a for loop can cause subtle bugs that let does not.
Show hint
Think about function scope vs. block scope.
Modern Variables and Objects: let, const, and Destructuring Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
LWC code is written entirely in modern JavaScript — this lesson covers the variable declarations and destructuring syntax you'll use in literally every component file you write.