← Learn Javascript

Functions & Events

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, followed by two parentheses. The open and closing curly braces contain the code that is executed when the function is called.

function hello(){
	console.log("hello back!");
}

👉 Paste the above into the console, press return, and then run it with...

hello()

Use Parameters and a Return Value

Declare a new function with 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.style.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)]

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 r(){
	return hex[Math.floor(Math.random() * hex.length)]
}
document.body.style.backgroundColor = "#" +r() +r() +r() +r() +r() +r();
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 event listeners.
  • Callbacks can be stored as function expressions or plain anonymous functions
let button = document.querySelector(".btn");

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

// #2 - named function as 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 ...