defining functions
Overview
This lesson starts with students exploring decomposition of a problem and creating functions. Then, students learn how to create a function using Javascript. Finally, students cement understanding by completing codewars exercises.
Objectives
By the end of the lesson, students will be able to:
- recognize proper function syntax
- create a function to solve a problem
Explore
Build functions for a day
- Each student picks a relatively simple task such as getting ready for school in the morning. Get out of bed, get dressed, brush teeth, etc...
- Break the activity down into smaller actions and write those tasks.
- Have one student read the tasks to the instructor, who models them. Takes a long time, right? Hard to read all of those instructions?
- Each student names their list of actions. And then one by one, they call out their function, and the instructor enacts them one after the other.
- Now, pick your own order. Instead of writing all of individual actions, use the lists that your peers wrote. Put them together into a chain of actions to get ready in the morning.
Questions
- Why was creating the functions useful?
- How did you use a specific function?
Explain
- Defining a function teaches the program a new task.
- A function is a list of instructions, like the lists students generated during the explore phase, that is stored with a name for later use.
- The function won’t run until it is called.
Hello World Example
Create a function that says 'Hello World'. Students follow along by coding this example on their own computers
Define a function called helloWorld
function helloWorld () { // code goes here }Add the list of actions inside the curly braces. In this case we want to use return “Hello World”
function helloWorld () { console.log('Hello World') }- Why is the program not doing anything?
- The function won’t run until it is called
Call the function by writing the function’s name followed by parentheses
function helloWorld () { console.log('Hello World') } helloWorld()Functions can be called multiple times.
function helloWorld () { console.log('Hello World') } helloWorld() helloWorld() helloWorld()