Functions
A function is a reusable, named block of code. Instead of writing the same logic repeatedly, you define it once and call it wherever you need it. function greet(name) { return `Hello, ${name}!`; } defines a function called greet that takes one parameter, name, and returns a value with the return keyword. Calling it, greet("Ali"), runs the code inside with name set to "Ali", and evaluates to "Hello, Ali!". A function can take multiple parameters, separated by commas: function add(a, b) { return a + b; }. Parameters can also have default values: function greet(name = "friend") { ... } if greet() is called with no argument at all, name automatically becomes "friend". return immediately exits the function and sends a value back to wherever it was called. A function with no return statement returns undefined by default. Functions are one of the most important ideas in this entire course almost everything else builds on top of them.
Why this matters
- ·Functions let you write logic once and reuse it anywhere, instead of duplicating code.
- ·Parameters let the same function behave differently depending on what's passed in.
- ·Default parameter values make a function easier and safer to call with fewer arguments.
Common mistakes
- ·Forgetting return means a function does its work but sends back undefined, which can cause confusing bugs downstream.
- ·Calling a function with the wrong number or order of arguments can silently produce wrong results.
- ·Defining a function but forgetting to actually call it means its code never runs at all.
Frequently asked questions
It immediately exits the function and sends the given value back to wherever the function was called.
Practice questions
Question 1
Write a function called square that takes a number and returns its square.
Question 2
Write a function called isEven that takes a number and returns true or false.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 3
