Michael Ouroumis logoichael Ouroumis
← Back to course

Functions & Scope

Learn how to define, call, and scope functions in JavaScript.

Lesson Objectives

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

  1. Declare named and arrow functions, understand parameters and return values.
  2. Differentiate between function scope and block scope.
  3. 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 explicitly return:

    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:

  1. Declare

    const numbers = [2, 4, 6, 8] const factor = 3
  2. Create a named function multiply(n, f) that returns n * f.

  3. Use .map() and your multiply to build a new array of numbers × factor.

  4. 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

  1. When should you use a named function vs. an arrow function?
  2. How does parameter defaulting help prevent undefined returns?
  3. Why are map and filter often preferred over manual loops?

Next Steps: Try writing your own .reduce() to sum an array, and compare it to a for-loop implementation!


Try It Yourself

// 1. data & DOM
const numbers = [2, 4, 6, 8]
const input = document.getElementById('factor')
const button = document.getElementById('runBtn')
const output = document.getElementById('app')

// 2. named multiply function
function multiply(n, f) {
  return n * f
}

// 3. run on click
button.addEventListener('click', () => {
  const factor = Number(input.value) || 1
  const result = numbers.map((n) => multiply(n, factor))
  output.textContent = JSON.stringify(result, null, 2)
})