Learn Javascript

Functions

How to reuse code, protect variables, and organize code

slides | md

Introduction

Review the following sections and perform the activities on your own or with your group.

Perform the task(s) when you see this 👉 emoji

Learning Objectives

Students who complete this module will be able to:

  • Explain the benefits of using functions
  • Compare global and local scope
  • Create a function and call it from javascript code
Homework

About Functions

  • Functions are a way to organize and reuse blocks of code.
  • Javascript contains several built-in functions that make it easy to perform common tasks.*
  • To use a function, "call" it with the name and two parentheses ()
*Functions are also called "methods", especially in OOP (Object Oriented Programming).
// these built-in functions ...
alert("hello world!");

// all require parameters ...
console.log(123); // -> 123

// to do things 
Math.ceil(1.3); // -> 2
The task a function performs can be customized using one or more parameters placed between the parentheses.

Create a Function

Use the function keyword to create a new function. Include parameters to customize its task. Use return to send data back to the code where it was called.

👉 Paste into the console function square() { return num * num }, then call it with square(2) or square(12)

Code Reuse

Writing the same code over and over is not only inefficient and boring, it also makes it difficult to detect and fix errors.

let hex = "0123456789abcdef"
document.body.backgroundColor = "#" + 
	// create a random number between 0-15 to get a hexadecimal character
    hex[Math.floor(Math.random() * hex.length)] + 
    hex[Math.floor(Math.random() * hex.length)] +
    hex[Math.floor(Math.random() * hex.length)] +
    hex[Math.floor(Math.random() * hex.length)] +
    hex[Math.floor(Math.random() * hex.length)] +
    hex[Math.floor(Math.random() * hex.length)]
Several lines of code in this example perform the same task!

Custom Functions

If you find yourself typing the same instructions, consider using a custom function to make it easier to write and manage the code.

let hex = "0123456789abcdef"
function rand(arr){
	return arr[Math.floor(Math.random() * arr.length)]
}
document.body.backgroundColor = "#" + 
	rand() + rand() + rand() + rand() + rand() + rand();
In the updated example the repeated code is "wrapped" with a function which "returns" the value of the expression back to the location where it was called. The changes reflect the D.R.Y. ("Don't Repeat Yourself") principle in action.

Global Scope

The location in your code where you declare a variable determines its scope, or how it can be accessed by other parts of your program. With global scope, variables can be accessed from anywhere.

let foo = "hello";
function updateFoo() {
	foo = "goodbye"; // ✅ we can access a global variable
}
updateFoo();
console.log("foo =", foo); // -> "goodbye"

Local Scope

Alternately, with local scope, variables are accessible only within the statement block (and nested blocks) where they were declared.

function updateBar() {
	let bar = 123; // variable declared with local scope
}
updateBar();
// ❌ bar is local because was defined (scoped) in a block
console.log("bar =", bar);
// -> "Uncaught ReferenceError: bar is not defined"

Function Expressions

So far we've used function declarations. The function expression is also common.

const getCurrentHour = () => {
    let today = new Date();
    return today.getHours();  
}
console.log(getCurrentHour());

The arrow function is succinct when the function body can fit on a single line.

const getCurrentHour = () => new Date().getHours(); 
console.log(getCurrentHour());

Anonymous Functions

  • A function expression without a name is anonymous.
  • Often used as callbacks from jquery and other event listeners.
  • Callbacks can be stored as function expressions or plain anonymous functions
let button = document.querySelector(".btn");

// #1 - anonymous function used as click handler
button.addEventListener("click", function() {
	console.log("click! 🎉")
});

// #2 - named function used as the callback
var myFunc = function() {
	console.log("click! 🎉")
}
button.addEventListener("click", myFunc);
Examples #1 and #2 do the same thing.

Next steps

  1. Explore More Concepts at the end
  2. Try the Exercises below.
  3. Start working on homework listed in the schedule.
  4. Continue to the next lesson: Data Structures slides | md

Exercises

👉 Try it out

  1. Lottery v.2 - Show results of the game in HTML
  2. Gradebook - Code a gradebook app using conditions, functions, and jquery.
  3. Revisit this lamp demo to explore how it uses functions

References

More Concepts

Continue for more related concepts.

IIFE

(function(){
	// an IIFE runs immediately but
	// the variables declared here
	// do not have global scope
})();

Side Effects

  • Side effects are statements that evaluate an expression and produce some other effect instead of returning a value.
alert(1 + 1); // -> Opens a popup window
console.log(1 < 2); // -> logs to the console

Anonymous Functions (jQuery example)

NOTE: youmightnotneedjquery.com

$("button").click(function() {
	// jquery click() adds listener
    // anonymouse function used as handler
});
$("button").click(myCallback);

var myCallback = function() {
	// this is the same as the pure JS example
}

Presentation comments ...

--- ## Code reuse This is the code from the previous lesson. This code runs just once. ```js let apples = 2; if (apples > 3) { console.log(`We have ${apples} apples! We can make pie!`) } else { console.log(`We have ${apples} apples! We need more apples`) } // -> "We have 2 apples! We need more fruit." ``` --- ## Code reuse <div class="twocolumn"> <div class="col"> Wrapping this code inside a function lets us... 1. Run the code multiple times with different values 1. Change the value that determines the logical flow </div> <div class="col"> ```js function canPie(fruit, count){ let str = `We have ${count} ${fruit}! `; if (count > 3) { str += `We can make pie!`; } else { str += `We need more fruit.`; } return str; } console.log(`${canPie("apples", 2)}`); // -> "We have 2 apples! We need more fruit." console.log(`${canPie("pears", 5)}`); // -> "We have 5 pears! We can make pie!" console.log(`${canPie("berries", 101)}`); // -> "We have 101 berries! We can make pie!" ``` </div> </div>