Lesson Objectives
By the end of this lesson, you will be able to:
- Declare named and arrow functions, understand parameters and return values.
- Differentiate between function scope and block scope.
- Use higher-order functions (
map
,filter
) to process arrays.
1. Declaring & Calling Functions
Named functions
function greet(name) { return `Hello, ${name}!` } console.log(greet('Alice')) // "Hello, Alice!"
Arrow functions
const add = (a, b) => { return a + b } const square = (x) => x * x
2. Parameters, Returns & Default Values
-
You can give defaults:
function say(msg = 'Hi') { console.log(msg) }
-
Functions always return
undefined
if you donât explicitlyreturn
:function noReturn() {} console.log(noReturn()) // undefined
3. Scope: Local vs Block
-
Function scope: variables declared inside a function arenât visible outside.
function foo() { let x = 10 console.log(x) } console.log(x) // ReferenceError
-
Block scope with
let
/const
:if (true) { const y = 5 } console.log(y) // ReferenceError
4. Higher-Order Array Methods
Rather than writing loops, you can pass callbacks:
const nums = [1, 2, 3, 4, 5] // map â new array of squares const squares = nums.map((n) => n * n) // filter â only even const evens = nums.filter((n) => n % 2 === 0)
Task: Build a Multiplier Map
In your scaffold/index.js
:
-
Declare
const numbers = [2, 4, 6, 8] const factor = 3
-
Create a named function
multiply(n, f)
that returnsn * f
. -
Use
.map()
and yourmultiply
to build a new array ofnumbers
Ăfactor
. -
Render into
<div id="app">
, e.g.[ 6, 12, 18, 24 ]
Bonus: Let the user input the factor via an
<input>
and update on button click.
Reflection
- When should you use a named function vs. an arrow function?
- How does parameter defaulting help prevent
undefined
returns? - Why are
map
andfilter
often preferred over manual loops?
Next Steps: Try writing your own .reduce()
to sum an array, and compare it to a for
-loop implementation!