Lesson 5: Function Expressions and Arrow Functions

Learning Objectives

By the end of this lesson, learners will be able to:

  • Understand what a function expression is and how it differs from a function declaration
  • Write functions using the arrow function syntax (ES6)
  • Recognize the use cases and limitations of arrow functions
  • Choose the appropriate function style for different situations

1. What Is a Function Expression?

A function expression is when you create a function and assign it to a variable.

Syntax:

const greet = function() {
  console.log("Hello!");
};

greet(); // Output: Hello!
  • The function has no name (anonymous function)
  • It’s assigned to the constant greet
  • You call it just like a regular function

Function Declaration vs. Function Expression

FeatureFunction DeclarationFunction Expression
Keyword usedfunction greet() {}const greet = function() {}
Can be hoisted✅ Yes❌ No
Must have a name✅ Usually❌ Optional
Defined as variable❌ No✅ Yes

Hoisting means that you can use the function before it’s defined — works only with function declarations.


2. What Are Arrow Functions?

Arrow functions were introduced in ES6 (ECMAScript 2015) as a shorter way to write functions.

Basic Syntax:

const greet = () => {
  console.log("Hello!");
};

greet(); // Output: Hello!

Breakdown:

  • const greet =: assign to variable
  • () => {}: the arrow function syntax

Example with Parameters

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

console.log(add(3, 4)); // Output: 7

Implicit Return (one-line arrow functions)

If the function has only one expression, you can omit return and braces {}:

const square = x => x * x;

console.log(square(5)); // Output: 25

✅ Cleaner and shorter for simple operations


Comparison: Traditional vs. Arrow Function

TaskTraditional SyntaxArrow Syntax
Greet userfunction greet() { ... }const greet = () => { ... }
Add numbersfunction add(a, b) { return a + b; }const add = (a, b) => a + b;

Limitations of Arrow Functions

Arrow functions do not have their own this context, which means they behave differently in certain object-related or class scenarios.

For example, in an object method:

const person = {
  name: "Ella",
  sayName: () => {
    console.log(this.name); // undefined
  }
};

person.sayName();

Use regular functions for object methods if you need access to this.


Practice Example

const isEven = num => num % 2 === 0;

console.log(isEven(4)); // true
console.log(isEven(7)); // false

✅ This is a short and readable way to define simple functions.


Summary

TermDescription
Function ExpressionA function assigned to a variable
Arrow FunctionA shorter way to write function expressions (ES6+)
Implicit ReturnWhen a single expression is returned without return keyword
Use CaseArrow functions are great for short, simple logic
LimitationArrow functions don’t bind their own this