By the end of this lesson, learners will be able to:
A function expression is when you create a function and assign it to a variable.
const greet = function() {
console.log("Hello!");
};
greet(); // Output: Hello!
greet
Feature | Function Declaration | Function Expression |
---|---|---|
Keyword used | function 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.
Arrow functions were introduced in ES6 (ECMAScript 2015) as a shorter way to write functions.
const greet = () => {
console.log("Hello!");
};
greet(); // Output: Hello!
const greet =
: assign to variable() => {}
: the arrow function syntaxconst add = (a, b) => {
return a + b;
};
console.log(add(3, 4)); // Output: 7
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
Task | Traditional Syntax | Arrow Syntax |
---|---|---|
Greet user | function greet() { ... } | const greet = () => { ... } |
Add numbers | function add(a, b) { return a + b; } | const add = (a, b) => a + b; |
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
.
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.
Term | Description |
---|---|
Function Expression | A function assigned to a variable |
Arrow Function | A shorter way to write function expressions (ES6+) |
Implicit Return | When a single expression is returned without return keyword |
Use Case | Arrow functions are great for short, simple logic |
Limitation | Arrow functions don’t bind their own this |