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
- What functions are and why we use them
- How to write and call functions in JavaScript
- How to use parameters and return values
- How to connect functions to HTML buttons
Why Use Functions?
- Break big problems into smaller steps
- Reuse code without repeating yourself
- Make your programs easier to read and fix
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() {
}
- function - keyword
- functionName - your chosen name
- () - parentheses (can hold parameters)
- {} - curly braces for the code block
Declaring a Function
function greet() {
alert("Welcome to my site!");
}
This code creates a function named greet.
Calling a Function
This runs the code inside the greet function.
Parameters & Arguments
function sayHelloTo(name) {
alert("Hello, " + name + "!");
}
sayHelloTo("Alex");
- Parameter: name in the function definition
- Argument: value you pass in ("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
- Forgetting to use
return when you want a value back
- Not calling the function (missing
())
- Using the wrong number of arguments
- Misspelling function names
Summary & Key Takeaways
- Functions help organize and reuse code
- Use parameters for flexible functions
- Return values let functions give back results
- Connect functions to HTML for interactivity
Challenge & Homework
- Write four math functions: add, subtract, multiply, divide
- Connect your functions to four different HTML buttons
- Display the result of each function in the html tag <div class="result"></div>
Optionally
Take the user input from two "input" elements with type="number", where each input provides the "x" and "y" variables.