Defining functions
// Declaration (hoisted)
function add(a, b) {
return a + b;
}
// Expression
const multiply = function (a, b) {
return a * b;
};
// Arrow function
const greet = (name = 'friend') => `Hello, ${name}!`;
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
console.log(greet('Ahbab')); // Hello, Ahbab!
Parameters and scope
let message = 'global';
function demo(param) {
const local = 'local';
console.log(message, param, local);
}
demo('value');
// console.log(local); // ❌ ReferenceError: local is not defined
Practice
- Write a
sumfunction that sums an array of numbers. - Create a function that formats a user's full name from first/last.
- Convert a declaration to an arrow function.
Next up
Quick Check
What keyword immediately returns a value from a function?