One of the most magnificent structures in the computer science world is the function.
Functions (sometimes called procedures) are mini-programs that you can use over and over inside of your bigger program.
Functions are pieces of code that you can call over and over again.
Functions are at the heart of JavaScript. They let you write code that you can quickly use again and again.
Remember! Our song exercise at the beginning of class? The chorus acts like a function that you can call over and over when you want the singer to sing those lyrics. What are some real life functions?
The following is how you declare a function:
function functionName() {
//code you want to repeat
}
Name a function like you name a variable. Best practices:
Function names cannot start with a number.
Everything within the curly braces is the code block.
The code in the code block only runs when the function is activated. How do we run the code block in myGreeting?
function myGreeting() {
alert("Good morning!");
}
To activate our code block, we need to call the function housing the code block. You call the function like so:
myGreeting();
The parentheses ()
are what actually call the myGreeting function. Parentheses ()
are very important!
In summary, functions are re-usable collections of statements.
First, declare the function:
function sayMyName() {
console.log('Hi Jessica!');
}
Then call it (as many times as you want):
sayMyName();
//Create your function first
function alertRandom() {
//create a new random number each time the function is run
let randomNumber = Math.floor(Math.random()*6)+1;
alert(randomNumber);
}
//calling the function
alertRandom();
function alertRandom() {
let randomNumber = Math.floor(Math.random()*6)+1;
alert(randomNumber);
}
alertRandom();
alertRandom();
alertRandom();
alertRandom();
var alertRandom = function() {
let randomNumber = Math.floor(Math.random()*6)+1;
alert(randomNumber);
};
Which of the following describes a function?
Which of the following code snippets correctly shows how to create a function named sayHello
which opens an alert dialog with the string "Hello" in it?
function sayHello {
alert("Hello");
}
function sayHello (
alert("Hello");
)
function sayHello() {
alert("Hello");
}
var function=sayHello() {
alert("Hello");
}
Bad:
function addNumbers() {return num1 + num2;}
Good:
function addNumbers() {
return num1 + num2;
}
Up until this point, our programs have been running from top to bottom in HTML and CSS.
Functions allow the browser interpreter to store information to be sure that proper code is being called depending on the contents of the function.
Many developers write their functions at the beginning of their code, so all of them are grouped together.
Functions don't just run JavaScript statements. They can also return values that you can use elsewhere in a program.
Functions can also give something back when they finish. This is called returning a value.
function goToCoffeeShop() {
return "Espresso is on the way";
}
The value that is returned by the function can then be used in your program.
‘return’ing something in JavaScript is very useful
You can use its values for many other parts of your program. Examples: display items on your website, do calculations, etc.
Return statements should be the last thing in the code block of a function, because they immediately exit the function.
The return
keyword returns a value to whoever calls the function (and exits the function):
function addNumbers() {
var num1 = prompt("What is your favorite number?");
var num2 = prompt("What is your second favorite number?");
let result = Number(num1) + Number(num2);
return result; // Anything after this line won't be executed
}
var sum = addNumbers();
After the code below runs, what value is stored in the variable dayOfWeek
?
function getDay() {
return "Monday";
alert("Calculating day");
return "Friday";
}
var dayOfWeek = getDay();
What is the return
value of running a load of laundry?
How is this different from using console.log()
?
1. Create a function named getYear
.
2. Inside the function's code block add this line of code:
var year = new Date().getFullYear();
This creates a new variable and stores the current year in it.
3. Add a statement that returns the variable.
4. Call the getYear
function & store the returned value in a new variable named yearToday
.
You can give information to a function to change how it works.
Coffee shop example
JavaScript functions can also accept information called an argument, which you send to the function.
The argument is stored in a variable called a parameter that you can use inside the function.
function myFunction(parameter) {
//code block
}
Parameters are variables.
Passing an argument to a function
function goToTheCoffeeShop(drink) {
alert(drink + " is on the way!");
}
goToTheCoffeeShop("Espresso");
You can pass different values and get different results!
You can also have multiple arguments in a function. More on that very soon!
In our example, let’s say I also want something to eat.
function goToTheCoffeeShop(drink, pastry) {
alert(drink + "and " + pastry + " are on the way!");
}
goToTheCoffeeShop("Espresso", "scone");
You can pass different values and get different results!
You can also have multiple arguments in a function.
You want to add no more than 4 or 5 arguments to a function. This can get tedious.
In JS Bin, let’s create a function to calculate the area of a rectangle.
Functions can accept any number of named arguments:
function sayMyName(name) {
console.log('Hi, ' + name);
}
sayMyName('Claire');
sayMyName('Testy McTesterFace');
function addNumbers(num1, num2) {
let result = num1 + num2;
console.log(result);
}
addNumbers(7, 21);
addNumbers(3, 10);
You can also pass variables:
var number = 10;
addNumbers(number, 2);
addNumbers(number, 4);
var nameImprover = function(name, adj) {
return 'Col ' + name + ' Mc' + adj + ' pants';
};
var nameImprover = function(name, adj) {
return 'Col ' + name + ' Mc' + adj + ' pants';
};
var nameLogger = function(name, adj) {
let newName = 'Col ' + name + ' Mc' + adj + ' pants';
console.log(newName);
};
Read here for more on the return keyword
Read here for more on the console.log() method
var addTwo = function(a, b) {
console.log(a,b); // logs 3,10
return a + b;
};
addTwo(3, 10); // 13
Why would a developer use the console.log()
method in the addTwo
function in the development phase?
Why would a developer remove the console.log()
method in the addTwo
function for the production phase?
JavaScript can handle multiple functions.
Each function acts like its own individual universe.
The variables created in one universe do not interact with the variables created in another universe or another function.
This means that functions are a wonderful tool to use when coding with security in mind.
function greeting() {
let person= "Lilah";
alert(person);
}
var person = "George";
greeting();
alert(person);
function greeting() {
let person = "Lilah";
alert(person);
}
var person = "George"
greeting();
alert(person);
LOCAL: A variable declared in a function only lives inside that function and cannot be accessed or changed outside of that function and has therefore local scope.
GLOBAL: Any variables you create in a script that are not contained in a function are in this bigger universe called the global scope.
**All functions can access the global scope.
The word “scope” refers to where a variable is declared.
As you create more complex programs, you'll end up adding multiple functions to your scripts.
It's possible, even likely, that a function defines and uses the same name as a variable used elsewhere in your script.
You might write some JavaScript with a variable named “width”, but also have a function named computeArea
that also has a width
variable inside it. More on this later.
var width = 6;
var computeArea = function(width) {
return width * width;
};
1. You can use the var
keyword to declare variables outside of functions. These global variables can be used by other functions and variables.
2. You can use the let
keyword to declare variables inside of functions. These local variables are block scoped.
3. You can use the const
keyword to declare variables whose values cannot be reassigned. These will often be global variables.
A variable with "local" scope:
function addNumbers(num1, num2) {
let localResult = num1 + num2;
console.log("The local result is: " + localResult);
}
addNumbers(5, 7);
console.log(localResult);
A variable with "global" scope:
var globalResult;
function addNumbers(num1, num2) {
globalResult = num1 + num2;
console.log("The global result is: " + globalResult);
}
addNumbers(5, 7);
console.log(globalResult);
Why pay a fortune teller when you can just program one yourself?
tellFortune
that:Calculate Your Age!
calculateAge
that:
var divideByThree = function(number) {
let val = number / 3;
console.log(val);
};
How would you call this function so that 3 is logged to the console?
var greeting = function(name) {
console.log("Great to see you," + " " + name + "!");
};
How would you call this function so that “Great to see you, Grace Hopper!” is logged to the console?
var foodDemand = function(food) {
console.log("I want to eat" + " " + food + ".");
};
How would you call this function so that “I want to eat Chinese food.” is logged to the console?
var coffeeCost = function(cost) {
let total = cost * 5;
console.log(total);
}
Jessica drinks five cups of coffee a day. How would you call this function if the cost of her coffee is $3?
Given the code below, what appears in the alert dialogue when this program runs?
var name = "Wonder Woman";
function setName() {
let name = "Diana Prince";
}
setName();
alert(name);
Please read Chapter 3
(no need to worry about pages 106-117)
Thank you for your attention!