1 / 15

Functions & Code Organization

Breaking Problems Into Pieces

Lesson 6: Reusable Code

Make your code neat, powerful, and easy to use!

What We'll Learn Today

Why Use Functions?

What is a Function?

A function is a named block of code that does a specific job.

function sayHello() {
  alert("Hello!");
}

Function Syntax

function functionName() {
  // code goes here
}

Declaring a Function

function greet() {
  alert("Welcome to my site!");
}

This code creates a function named greet.

Calling a Function

greet();

This runs the code inside the greet function.

Parameters & Arguments

function sayHelloTo(name) {
  alert("Hello, " + name + "!");
}
sayHelloTo("Alex");

Return Values

function add(a, b) {
  return a + b;
}
let sum = add(3, 4);

The return keyword sends a value back from the function.

Example: Simple Calculator

function multiply(x, y) {
  return x * y;
}
let result = multiply(5, 6);
alert("5 x 6 = " + result);

Functions & HTML Buttons

You can call functions when a button is clicked!

function showMessage() {
  alert("Button clicked!");
}
<button onclick="showMessage()">Click me!</button>

Activity: Write Your Own Function

Write a function that greets the user by name. Try calling it with different names!

function greetUser(name) {
  alert("Hi, " + name + "!");
}
greetUser("Sam");
greetUser("Taylor");

Common Mistakes

Summary & Key Takeaways

Challenge & Homework

Optionally

Take the user input from two "input" elements with type="number", where each input provides the "x" and "y" variables.