Popular Searches
Popular Course Categories
Popular Courses

let/const, arrow functions

let/const, arrow functions

27 mins Modern JavaScript (ES6+)

let/const, arrow functions in React JS

Course: React JS Training

Topic: let/const, arrow functions

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why let, const and Arrow Functions Matter

Modern JavaScript, usually called ES6+ JavaScript, is the version of the language that every current framework assumes you know, and React is no exception. Open any React codebase and you will see two patterns again and again: values stored with const, and functions written with a short => arrow. React learning resources describe arrow functions as the popular way to create functions in modern code, and the React checklist video in our course resources makes the same point: you cannot read React comfortably until these two syntax features feel natural.

Before ES6, JavaScript had only one way to declare a variable: the var keyword. var still works, but it behaves in surprising ways (you will see a famous example shortly), so modern code prefers let and const. Arrow functions arrived in the same era of the language. They do everything ordinary functions do, with less typing and, in one important case, more predictable behaviour: the this keyword.

2. Definitions in Simple Words

let and const: two modern ways to declare a variable

A variable is a named container for a value. let declares a container whose contents you may swap later; const declares a container that stays tied to one value. Both are visible only inside the block (the code between curly braces) where they are written, which stops them from leaking into unrelated parts of the program.

A useful picture: let is a whiteboard label you can erase and rewrite; const is a label carved in stone. The carving cannot change, but if the stone sits on top of a box of objects, you can still rearrange the box.

Arrow functions: a shorter function syntax

An arrow function is a normal function written in shorthand. Instead of the function keyword, you list the parameters, then an arrow made of an equals sign and a greater-than sign, then the body. The idea comes from mathematics, where a mapping such as "x maps to x squared" is written compactly.

Beyond shorter typing, arrow functions differ from traditional functions in one deep way: they do not create their own this. They borrow this from the code around them. Later sections show why that is usually a gift.

3. Key Terms You Will Meet

  • Scope — the region of a program where a name is visible and usable.
  • Block — code wrapped in curly braces, such as the body of an if or a loop.
  • Block scope — a variable declared inside a block exists only inside that block.
  • Function scope — a variable declared in a function exists anywhere inside that function, across all of its blocks.
  • Global scope — visible everywhere in the program; modern code keeps globals to a minimum.
  • Hoisting — the interpreter's setup phase moves declarations to the top of their scope before code runs. var hoists with the value undefined; let and const hoist but stay unusable until their line runs.
  • Temporal dead zone (TDZ) — the stretch between the start of a block and the let/const declaration line, where touching the variable throws a ReferenceError.
  • Reassignment vs redeclaration — reassignment gives an existing variable a new value; redeclaration creates the same name again. let allows the first and forbids the second; const forbids both.
  • Lexical this — an arrow function's this is fixed by where the function is written, not by how it is called.
  • Callback — a function handed to another function to run later, such as inside map or setTimeout. Arrow functions dominate here.
  • Implicit return — an arrow function with a one-expression body returns that expression automatically, with no return keyword.

4. Syntax of let and const

Declaring with let

let city = "Pune";      // declare and initialise in one line
city = "Mumbai";        // reassignment is allowed
let temperature;        // declaration without a value gives undefined
temperature = 31;

Declaring with const

const pinCode = "411001";   // const must be initialised immediately

// pinCode = "400001";
// TypeError: Assignment to constant variable.

// const discount;           // SyntaxError: missing initialiser

The rules in one list

  • Both let and const are block scoped.
  • Neither may be redeclared in the same scope; var allows this, which is one reason it is avoided.
  • const demands a value on the same line where it is declared.
  • Both stay in the temporal dead zone until their declaration line executes.
  • By convention, values that never change use const; only genuinely changeable values use let.

5. How Block Scope Works, Step by Step

Follow this small program one step at a time:

let score = 10;

if (true) {
  let score = 20;        // a brand-new variable, alive only in this block
  console.log(score);    // 20
}

console.log(score);      // 10 - the outer variable was never touched
  1. Execution begins outside the if block. let score = 10 creates a variable in the outer scope.
  2. The program enters the block. A second let score creates a separate, inner variable. This is called shadowing: the inner name temporarily hides the outer one.
  3. Every statement inside the block now reads the inner score, so the log prints 20.
  4. The block ends, and the inner variable is destroyed.
  5. The final log reads the outer score, still 10.

With var, step 2 would create nothing new: var has no block scope, so the inner assignment would overwrite the outer variable and the last log would print 20. That difference is exactly why loops and conditionals behave more predictably with let.

6. var Compared with let and const

Featurevarletconst
ScopeFunction or globalBlockBlock
Redeclare in same scopeAllowedErrorError
Reassign a new valueAllowedAllowedError
Initial value requiredNoNoYes
Reading before the declaration lineundefinedReferenceErrorReferenceError
Typical use todayLegacy code onlyValues that changeDefault choice

The classic demonstration is a loop that schedules delayed callbacks:

for (var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log("var i:", i);    // prints 3, 3, 3
  }, 100);
}

for (let j = 0; j < 3; j++) {
  setTimeout(function () {
    console.log("let j:", j);    // prints 0, 1, 2
  }, 100);
}

With var, all three callbacks share one variable, and by the time they run the loop has finished, so i is 3. With let, JavaScript creates a fresh binding on every iteration, so each callback remembers its own value. This example is the standard answer to "why does modern code avoid var?"

7. const with Objects and Arrays: What Is Really Fixed

const freezes the binding, not the value. The name cannot be pointed at a different value, but if the value is an object or an array, its contents remain editable:

const student = { name: "Asha", course: "React" };

student.course = "React JS Training";   // allowed: editing the object's contents
console.log(student.course);            // "React JS Training"

// student = { name: "Meena" };         // TypeError: reassignment is not allowed
const marks = [72, 88, 95];

marks.push(60);        // allowed: changing the array's contents
console.log(marks);    // [72, 88, 95, 60]

// marks = [];         // TypeError: reassignment is not allowed

If you truly need an unchangeable object, Object.freeze(student) stops content edits as well. In everyday code, though, teams rely on the simpler habit: const for the name, discipline for the contents.

8. Arrow Function Syntax: From Long Form to Shortest

The clearest way to learn arrow syntax is to shorten a function one step at a time. Each version below is a rewrite of the one above it:

// Traditional function declaration
function double(n) {
  return n * 2;
}

// Step 1: store a function expression in a const
const double = function (n) {
  return n * 2;
};

// Step 2: replace the keyword "function" with an arrow after the parameters
const double = (n) => {
  return n * 2;
};

// Step 3: one-expression body? drop the braces and the word "return"
const double = (n) => n * 2;

// Step 4: exactly one parameter? the parentheses become optional
const double = n => n * 2;

All four versions do the same job. In real projects you will mostly see steps 3 and 4.

Rules worth memorising

  • No parameters — empty parentheses are compulsory: const ping = () => "pong";
  • Several parameters — parentheses are compulsory: const add = (a, b) => a + b;
  • Block body — with braces, you must write return yourself.
  • Returning an object literal — wrap it in parentheses so the braces are not read as a block body: const point = (x, y) => ({ x: x, y: y });
  • Multi-line logic — prefer a block body for readability even when a one-liner is technically possible.

9. How an Arrow Function Runs, Step by Step

Take this call and trace it:

const greet = (name) => "Hello, " + name + "!";

console.log(greet("Priya"));   // Hello, Priya!
  1. The const declaration stores the arrow function under the name greet. Nothing inside the function runs yet.
  2. The call greet("Priya") hands the string "Priya" to the parameter name.
  3. The body has no braces, so it is a single expression, evaluated immediately: "Hello, " + "Priya" + "!".
  4. Because the body is an expression rather than a block, the result is returned automatically — no return keyword.
  5. The returned string reaches console.log and is printed.

Two engine-level details run quietly in the background. First, an arrow function does not receive its own this or its own arguments object; both lookups fall through to the surrounding code. Second, an arrow function cannot be called with new, because it has no internal constructor machinery. Both details matter in the next section.

10. Arrow Functions and this

In a traditional function, this depends on how the function is called, which is a classic source of bugs inside callbacks. An arrow function removes the problem by not having a this of its own — it simply uses the one from the scope where it was written.

const timer = {
  seconds: 10,
  start: function () {
    setInterval(() => {
      this.seconds = this.seconds - 1;
      console.log(this.seconds);
    }, 1000);
  }
};

timer.start();   // logs 9, 8, 7 ... because "this" is the timer object

Inside start, a traditional function, this is the timer object. The arrow function passed to setInterval inherits that same this, so the countdown works. Had we written the callback as a traditional function, this would not point at timer and the code would break.

The flip side: an arrow function is the wrong choice when you actually want this to refer to the object:

const counter = {
  count: 0,
  showWithRegular: function () {
    console.log(this.count);   // works: "this" is the counter
  },
  showWithArrow: () => {
    console.log(this.count);   // broken: "this" belongs to the outer scope
  }
};

Rule of thumb: use a traditional function for object methods, and arrow functions for callbacks and standalone helpers.

11. Worked Examples: From Simple to Realistic

A grading helper

const grade = (marks) => {
  if (marks >= 80) return "A";
  if (marks >= 60) return "B";
  return "C";
};

console.log(grade(91));   // A
console.log(grade(64));   // B
console.log(grade(50));   // C

Several conditions need statements, so a block body with explicit return lines is the readable choice.

Filtering and totalling a shopping cart

const cart = [
  { item: "Keyboard", price: 1500, qty: 1 },
  { item: "Mouse",    price: 700,  qty: 2 },
  { item: "Monitor",  price: 8500, qty: 1 }
];

const affordable = cart.filter((product) => product.price < 2000);
const lineTotals = cart.map((product) => product.price * product.qty);
const grandTotal = lineTotals.reduce((sum, amount) => sum + amount, 0);

console.log(affordable.map((p) => p.item));   // ["Keyboard", "Mouse"]
console.log(lineTotals);                      // [1500, 1400, 8500]
console.log(grandTotal);                      // 11400

Array methods such as filter, map and reduce expect short callbacks, which is exactly what arrow functions provide. This pattern appears constantly in React when data is transformed before being rendered.

A first look at a React component

const WelcomeBanner = (props) => {
  return <p>Welcome, {props.studentName}!</p>;
};

Do not worry about the JSX angle brackets or props yet — those belong to the React modules. Notice only the shape: a component is just a const holding an arrow function that returns UI. The habit of writing const Name = () => ... starts on this page.

12. Choosing the Right Tool in Real Projects

  • Default to const. Reach for let only when a value genuinely changes, such as a running total or a loop counter. This default makes intent visible at a glance.
  • Never use var in new code. Its function scope and hoisting behaviour are legacy details you only need to recognise when reading older files.
  • Use arrow functions for callbacks — inside map, filter, reduce, event handlers and timers — where their brevity and inherited this shine.
  • Use traditional functions for object methods that need their own this, and for functions you want hoisted to the top of their scope.
  • Name arrow functions through const so the function cannot be silently reassigned later.
  • Keep one job per function; a short arrow function that does one thing is easier to test and reuse.

13. Common Mistakes to Watch Out For

Reassigning a const

const rate = 18;
// rate = 20;   // TypeError: Assignment to constant variable.

If the value must change, declare it with let instead.

Touching a variable in its temporal dead zone

console.log(userName);   // ReferenceError: Cannot access 'userName' before initialization
let userName = "Ravi";

Declare first, use later — the top-to-bottom order you would naturally write anyway.

Forgetting parentheses around a returned object

// Wrong: the braces are read as a function body, so this returns undefined
const makeUser = (name) => { name: name };

// Right: wrap the object literal in parentheses
const makeUser = (name) => ({ name: name });

Using an arrow function where this must be the object

Shown in the previous section: an object method written as an arrow loses the object's this. When a method needs this, write it with the function keyword or the method shorthand show() { ... }.

Expecting const to deep-freeze data

const stops reassignment, not edits to object or array contents. When immutability matters, create a new object or array instead of mutating the old one — a habit that pays off immediately in React state handling.

14. Advanced Real-World Usage of let, const and Arrow Functions

Default parameters in arrow functions

Arrow functions accept default parameter values, just like traditional functions. If the caller does not pass a value, the default is used. This keeps helper functions short and removes repetitive checks at the top of the body.

const applyDiscount = (price, percent = 10) => price - (price * percent) / 100;

console.log(applyDiscount(1000));      // 900 - uses the default 10%
console.log(applyDiscount(1000, 25));  // 750 - uses the given 25%

Chaining array methods into a data pipeline

Real applications rarely transform data in one step. A typical pipeline filters a list, picks out the needed fields, and reduces the result to a single number. Arrow functions keep each stage readable on its own line.

const orders = [
  { id: 1, city: "Pune",   amount: 1200, delivered: true },
  { id: 2, city: "Mumbai", amount: 800,  delivered: false },
  { id: 3, city: "Pune",   amount: 2500, delivered: true },
  { id: 4, city: "Delhi",  amount: 950,  delivered: true }
];

const puneDeliveredTotal = orders
  .filter((order) => order.city === "Pune" && order.delivered)
  .map((order) => order.amount)
  .reduce((sum, amount) => sum + amount, 0);

console.log(puneDeliveredTotal);   // 3700

Fixed configuration with const and Object.freeze

Applications often hold settings that must never change while the program runs, such as a tax rate or a currency code. Declaring them with const protects the name; wrapping the object in Object.freeze also protects the contents.

const SETTINGS = Object.freeze({
  currency: "INR",
  taxRate: 0.18
});

// SETTINGS.taxRate = 0.05;   // has no effect, or throws an error in strict mode
console.log(SETTINGS.taxRate);   // 0.18

let as an accumulator in loops

let is the natural choice when a value grows across iterations. Notice that the loop variable itself can be const in a for...of loop, because each iteration receives a fresh binding.

const words = ["learn", "modern", "javascript"];
let sentence = "";

for (const word of words) {
  sentence += word + " ";
}

console.log(sentence.trim());   // "learn modern javascript"

15. How These Features Show Up in React Code

Components as const arrow functions

React components are, at their core, functions that return UI. The community style is to declare each component with const and an arrow, which prevents the component from being accidentally reassigned later. Even as React moves toward server-first patterns such as Server Components, the JavaScript you write every day is still built from these two features.

const Badge = (props) => {
  return <span className="badge">{props.label}</span>;
};

Event handlers and hooks

Handlers are almost always arrows, because an arrow inherits the surrounding this and needs no extra binding work. State variables declared with hooks also use const, since the setter replaces the value rather than reassigning the variable.

const SaveButton = () => {
  const handleClick = () => {
    console.log("Saved!");
  };

  return <button onClick={handleClick}>Save</button>;
};

You will also meet lines like const [count, setCount] = useState(0); in the React modules. That combines const with a pattern called destructuring, which has its own sub-module page later in this course.

16. More Common Mistakes and the Correct Way

Calling an arrow function before it is defined

Arrow functions stored in const or let are not callable before their line runs.

sayHello();   // ReferenceError: Cannot access 'sayHello' before initialization

const sayHello = () => console.log("Hello!");

Correct way: define the function above its first use. If you truly need a function that can be called from lines above its definition, use a traditional function declaration, which is hoisted completely.

Forgetting the return in a block body

// Wrong: braces make this a block body, so nothing is returned
const double = (n) => { n * 2 };
console.log(double(5));   // undefined

// Correct option A: add return inside the braces
const doubleA = (n) => { return n * 2; };

// Correct option B: drop the braces for a one-expression body
const doubleB = (n) => n * 2;

Using const for a counter that changes

// Wrong: i++ tries to reassign a const
for (const i = 0; i < 3; i++) { }   // TypeError: Assignment to constant variable.

// Correct: let for a counter that is updated each pass
for (let i = 0; i < 3; i++) {
  console.log(i);   // 0, 1, 2
}

// Also correct: const is fine with for...of, since each iteration gets a fresh binding
for (const item of ["a", "b", "c"]) {
  console.log(item);
}

Reaching for arguments inside an arrow function

Arrow functions have no arguments object of their own, so a lookup inside an arrow falls through to the surrounding scope, which usually causes an error or gives the wrong data.

const showArgs = () => {
  console.log(arguments);   // not the arrow's own arguments
};

Correct way: modern code collects extra parameters with rest parameters, written as ...args in the parameter list. That syntax is taught in the next sub-module, Destructuring, Spread & Rest.

Accidental shadowing that breaks the logic

let total = 100;

const addFee = () => {
  let total = total + 20;   // ReferenceError: the inner total is read in its own dead zone
};

Correct way: either update the outer variable directly, or give the inner variable a different name when shadowing is intentional.

let total = 100;

const addFee = () => {
  total = total + 20;   // updates the outer variable
};

17. Reading the Error Messages: Debugging Scope Problems

Scope and this bugs produce very consistent error messages. Learn to read them and most problems take seconds to fix.

Error messageUsual causeFix
ReferenceError: Cannot access 'x' before initializationThe variable was used inside its temporal dead zoneMove the declaration above the first use
SyntaxError: Missing initializer in const declarationA const was declared without a valueAdd a value on the same line, or use let
TypeError: Assignment to constant variableCode reassigns a constUse let if the value must change
ReferenceError: x is not definedThe name does not exist in this scope, or is misspeltCheck the spelling and where the variable was declared
A method logs undefined for this.somethingAn arrow function was used where this should be the objectRewrite the method with the function keyword or method shorthand

A reliable debugging routine:

  1. Read the error message completely; it names the exact problem.
  2. Open the file and line number given in the message.
  3. Ask which scope the variable belongs to and whether it was declared before use.
  4. If this looks wrong, check whether the function is an arrow or a traditional function.

18. Best Practices for let, const and Arrow Functions

PracticeWhy it helps
Default to const for every declarationIntent is visible at a glance and accidental reassignment becomes impossible
Use let only when the value genuinely changesReaders can trust that a let variable will be updated somewhere nearby
Never use var in new codeFunction scope and hoisting surprises have no benefit in modern programs
Keep each function single-purpose and smallSmall functions are easier to test, reuse and read; the same habit scales up to small React components
Prefer implicit return for one-line transformsmap and filter chains stay short and readable
Use traditional methods for object methods that need thisThe method correctly receives the object as this
Name fixed configuration in UPPER_SNAKE_CASESignals to every reader that the value is a constant setting
Declare variables before using themAvoids temporal dead zone errors entirely, instead of debugging them

19. Practical Project: Monthly Expense Report

This small console project combines everything on the page: const for fixed data and helpers, let for a value that grows, and arrow functions for every transformation. Follow the steps, then run the complete program with Node.js or in a browser console.

  1. Store the raw data as a const array of objects. The data itself never changes identity during the run.
  2. Write two tiny arrow helpers: one test (isFood) and one formatter (toRupees). Each does exactly one job.
  3. Use filter and reduce with arrow callbacks to compute the food total and the grand total.
  4. Compute the food share as a percentage and round it with toFixed(1).
  5. Build the report line by line into a let string, because the string grows with each expense.
  6. Print the finished report with console.log.
const expenses = [
  { label: "Groceries",         category: "food",   amount: 2400 },
  { label: "Auto fare",         category: "travel", amount: 180 },
  { label: "Movie tickets",     category: "fun",    amount: 600 },
  { label: "Restaurant dinner", category: "food",   amount: 1100 },
  { label: "Bus pass",          category: "travel", amount: 450 }
];

const isFood = (expense) => expense.category === "food";
const toRupees = (amount) => "Rs. " + amount.toFixed(2);

const foodTotal = expenses
  .filter(isFood)
  .reduce((sum, expense) => sum + expense.amount, 0);

const grandTotal = expenses.reduce((sum, expense) => sum + expense.amount, 0);
const foodShare = ((foodTotal / grandTotal) * 100).toFixed(1);

let report = "MONTHLY EXPENSE REPORT";
report += "\n----------------------";

expenses.forEach((expense) => {
  report += "\n" + expense.label + ": " + toRupees(expense.amount);
});

report += "\n----------------------";
report += "\nFood total: " + toRupees(foodTotal);
report += "\nGrand total: " + toRupees(grandTotal);
report += "\nFood share: " + foodShare + "%";

console.log(report);
MONTHLY EXPENSE REPORT
----------------------
Groceries: Rs. 2400.00
Auto fare: Rs. 180.00
Movie tickets: Rs. 600.00
Restaurant dinner: Rs. 1100.00
Bus pass: Rs. 450.00
----------------------
Food total: Rs. 3500.00
Grand total: Rs. 4730.00
Food share: 74.0%

Notice the decision behind every keyword: const for the data, helpers and computed totals; let only for the report string that is appended to inside the loop.

20. Practice Exercises

  1. Take a loop that declares its counter with var and schedules three setTimeout callbacks. Convert it to let and write down the output before and after, with a one-line reason for each.
  2. Rewrite three traditional function declarations as arrow functions: one with no parameters, one with two parameters, and one with a default parameter. Keep the behaviour identical.
  3. Write an object with a counter property and two methods: one that reads the counter with this using a traditional method, and one broken arrow version. Explain in a comment why the arrow version fails.
  4. Given a snippet that logs a let variable before its declaration line, predict the exact error message, then fix the snippet by reordering the lines.
  5. Create three helpers — isPositive, square and sumAll — as arrow functions, then chain them over an array of numbers to keep only positive values, square them, and total the result.
  6. Refactor a classic for loop that adds numbers into a single reduce call with an arrow callback, and confirm both versions print the same total.

21. Interview Questions and Answers

What is the difference between var, let and const?

var is function scoped, allows redeclaration, and reads as undefined before its line runs. let and const are block scoped, forbid redeclaration in the same scope, and stay in the temporal dead zone until their declaration line. const additionally forbids reassignment and must be initialised immediately. Modern code uses const by default and let only for values that change.

What is the temporal dead zone?

It is the stretch of code between the start of a block and the line where a let or const variable is declared. The variable exists in that window but cannot be touched, so reading it throws ReferenceError: Cannot access 'x' before initialization. Declaring variables before use avoids the problem entirely.

Does const make an object immutable?

No. const fixes the binding between the name and the value, so the name cannot be reassigned. If the value is an object or array, its contents can still be edited. To stop content changes as well, pass the object to Object.freeze, which prevents adding, removing or changing its properties.

How do arrow functions differ from traditional functions?

Arrow functions have shorter syntax, including an implicit return for one-expression bodies. They do not get their own this or arguments — both come from the surrounding scope. They cannot be called with new, and when stored in a const or let they are not callable before their definition line.

How does this behave inside an arrow function?

An arrow function captures this lexically, from the scope where it was written, and keeps it no matter how it is later called. That is why an arrow callback inside a timer or event handler can safely use the outer object's this without any bind call.

When should you avoid arrow functions?

Avoid them for object methods that need this to point at the object, for functions that must be hoisted above their definition, and anywhere you need the function's own arguments object. They also cannot serve as constructors with new.

What does an arrow function with a block body and no return statement return?

It returns undefined. Braces create a block body in which return must be written explicitly. If the body is a single expression, either add return or drop the braces to get the implicit return.

Why does let fix the classic setTimeout loop problem?

With var, every callback shares one function-scoped variable, so after the loop finishes they all see the final value, printing 3, 3, 3. With let, each iteration creates a fresh binding captured by that iteration's callback, so the callbacks print 0, 1, 2.

What is shadowing?

Shadowing happens when an inner scope declares a variable with the same name as an outer one. Inside the inner block, the name refers to the new variable and the outer one is temporarily hidden. It is useful when done deliberately, but accidental shadowing is a common source of bugs.

Are arrow functions hoisted?

Not in a usable way. An arrow function is an expression, so the const or let name is known to the engine but sits in the temporal dead zone until the definition line runs. Traditional function declarations, by contrast, are fully hoisted and callable from anywhere in their scope.

Why do modern codebases declare everything with const by default?

It communicates intent — the reader knows the value will not be swapped — and it turns accidental reassignment into an immediate, visible error. This default also matches React style, where components and hook values are declared with const.

Where do arrow functions appear in React code?

Everywhere: components are commonly declared as const Name = (props) => ..., event handlers are written inline as onClick={() => ...}, and data is transformed with arrows inside map and filter before rendering. Their lexical this and short syntax make them the natural fit for callbacks.

22. Quick Revision Checklist

  • let: block scoped, reassignable, not redeclarable. const: block scoped, must be initialised, never reassigned. var: legacy, function scoped.
  • Curly braces create block scope; an inner declaration with the same name shadows the outer one.
  • The temporal dead zone ends at the declaration line — always declare before use.
  • const fixes the name, not the contents of objects and arrays; Object.freeze handles contents.
  • Arrow forms: (a, b) => expression, a => expression, () => expression, and block bodies with an explicit return.
  • Returning an object literal from a one-line arrow needs parentheses around the object.
  • Arrow functions inherit this from the surrounding scope and have no arguments of their own.
  • Use traditional methods for object methods that need this; use arrows for callbacks and handlers.
  • Default to const; switch to let only when a value changes; avoid var in new code.
  • Classic for counters need let; for...of works happily with const.

23. Official Documentation and Further Reading

No official MDN or React documentation addresses are included in this course's resource list for this page, so the curated resources below come from the course link list.

Conclusion

let, const and arrow functions are the grammar of modern JavaScript. Block scope makes programs predictable, const makes intent visible, and arrow functions make callbacks short while removing the classic this surprises. Every React file you open from now on will assume these habits, so the goal is not just to recognise the syntax but to reach for it automatically.

Carry three defaults forward: declare with const, switch to let only when a value must change, and write callbacks as arrows. The next sub-module, Destructuring, Spread & Rest, builds directly on this foundation and shows how to pull values out of objects and arrays with the same clean style.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp