← React / TypeScript

React / TypeScript · 05 / 18

Functions and scope

Write reusable calculations and understand local variables.

  • Small
  • Basics
  • 15 min

Prerequisites: Loops in JavaScript

A function groups instructions under a name. Parameters are its inputs. return supplies a result. Scope determines where a name can be used. We normalise an entered title and convert cents to euros. Both are small tasks that can be checked without React.

Example files

01Declare a function

normalizeTitle takes title. trim removes whitespace at the beginning and end. The function returns new text. It does not change a persisted record or display an interface.

functions.mjs · javascriptOpen file
function normalizeTitle(title) {
  return title.trim();
}
const euros = (cents) => cents / 100;
console.log(normalizeTitle('  Roof repair  '));
console.log(euros(12990));

Run / check

node functions.mjs

02Read arrow functions

const euros = (cents) => cents / 100 defines a function in a variable. Without curly braces, the expression is returned directly. With curly braces, a result requires an explicit return.

03Keep names local

title and cents are available only within their respective function calls. This prevents accidental dependencies on global state. Later, services also receive their required data and interfaces explicitly.

Expected result

Roof repair and 129.9

Your exercise

Add an isValidTitle function that checks whether at least one character remains after trim.

Show the solution and explanation

const isValidTitle = (title) => title.trim().length > 0 returns true for "Roof" and false for " ". The caller can then choose the display or error message.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.