Kodokon kodokon.com

Arrow functions, scope, and template literals

Master arrow syntax, block scope, and closures, then build dynamic strings with template literals.

8 min · 3 questions

Open this lesson in Kodokon

Arrow functions are everywhere in modern code: map and filter callbacks, event listeners, promises. Their strength: a compact syntax with an implicit return when the body fits in a single expression. As soon as you open curly braces, the return becomes mandatory again.

JAVASCRIPT
const double = (n) => n * 2;

const isAdult = (user) => user.age >= 18;

const buildUser = (name) => ({ name, active: true });

const sum = (a, b) => {
  const total = a + b;
  return total;
};

console.log(double(21)); // 42
console.log(buildUser("Ana").active); // true
Implicit return on an expression, explicit return with curly braces.

Scope determines where a variable is visible. With let and const, a variable declared inside a block (if, for, curly braces) only exists within that block. Another essential mechanism: a function keeps access to the variables of the scope where it was created, even after that scope has ended. This is a closure, and it's what makes counters, caches, and state managers work.

JAVASCRIPT
function createCounter() {
  let count = 0;
  return () => {
    count += 1;
    return count;
  };
}

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
The returned function keeps access to count: that's a closure.

Template literals, delimited by backticks, are a much better alternative to concatenation. You inject an expression with ${...}, and line breaks are preserved as-is, which is ideal for building messages or HTML fragments.

JAVASCRIPT
const user = { firstName: "Nadia", cartCount: 3 };

const message = `Hello ${user.firstName}, you
have ${user.cartCount} items in your cart.`;

console.log(message);
Interpolation and multi-line strings without any concatenation.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which syntax correctly returns an object from an arrow function with an implicit return?
    • (name) => { name: name }
    • (name) => ({ name })
    • (name) => return { name }
  2. Is a variable declared with let inside an if block accessible after that block?
    • Yes, just like with var
    • No, its scope is limited to the block
    • Only if it was initialized
  3. Which character delimits a template literal?
    • The single quote
    • The double quote
    • The backtick