CodeBlanks Logo Icon CodeBlanks

Arrow syntax

Learn to write arrow functions and their types.

Arrow syntax

Arrow functions provide a shorter way to write functions. Write => after the parameters and specify the body. With a single expression, the return is implicit.

const topla = (a: number, b: number): number => a + b;
console.log(topla(2, 3));  // 5

Arrow functions simplify code, especially for short operations.

Arrow function with block body

When the body has multiple statements, curly braces are used and an explicit return is written. Without braces, the single expression is returned automatically.

// Single expression - implicit return
const kare = (x: number): number => x * x;
// Block body - explicit return
const detay = (x: number): number => {
  let t = x * x;
  return t;
};

Both forms are valid; choose as needed.

Practice Write an arrow function

Define an arrow function named topla with a: number and b: number parameters and return type number. It should return a + b with implicit return. Print the result of calling topla(3, 8) with console.log.

Starter code

index.ts
// topla adında bir ok fonksiyonu tanımla
// a ve b parametreleri number, dönüş türü number olsun
// parametrelerin toplamını örtük return ile döndür
// topla(3, 8) sonucunu yazdır

Sample solution

index.ts
const topla = (a: number, b: number): number => a + b;
console.log(topla(3, 8));

Expected output

11

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>(a: number, b: number): number =&gt; a + b</code> return?

  • The value a + b Correct answer
  • undefined
  • A string
  • An error

Explanation: In a single-expression arrow function, the expression is returned automatically; the result of <code>a + b</code> is returned.

2 Complete the arrow function

Question
const kare = (x: number): number => x * ____;
Answer
const kare = (x: number): number => x * x;

Explanation: The square function must return <code>x * x</code>; the <code>x</code> parameter is multiplied by itself. <code>a</code> and <code>y</code> are undefined variables, and <code>2</code> gives <code>x * 2</code>.

3 Arrow syntax concepts

Term Meaning
(a, b) => a + b Single expression, implicit return
(a, b) => { return a + b; } Block body, explicit return
=> Arrow operator
Arrow function Short function syntax

All lessons in Beginner