FUNCTIONS
Objectives!
- describe the concept of a function in one sentence
- explain the syntax of a function
- create a function
- invoke a function
- use the keyword return
- add behavior with parameters and arguments
- use the keyword arguments
What is a function?
A reusable sequence of instructions that achieve a specific task
Function Syntax
var myfunction = function () {
BODY
}Expression declaration
function as a part of a larger expression syntax (typically a variable assignment )
Function Syntax
function name () {
BODY
}statement declaration
Function Syntax
var func = x => x * x;
var func = (x, y) => { return x + y; };Arrow, "fat arrow" syntax
Function Syntax
var func = new Function();Not recommended.

Let's make some functions!
Write a function named "greet" that will print out "Hello World!"
function greet() {
console.log("Hello World!");
}Let's make some functions!
What will the console.log return?
var whisper = "Kittens are magic";
function yell() {
whisper = whisper.toUpperCase();
console.log(whisper);
}
console.log(whisper);Why?
Invoking your function
What's different here?
var whisper = "Kittens are magic";
function yell() {
whisper = whisper.toUpperCase();
console.log(whisper);
}
yell()
Invoking your function
Write and invoke a function to print "Wizard cat"
var myPets = {
Ginger: "dachshund/corgi",
Ferdinand: "French bulldog",
Zoey: "Australian cattle dog",
Ben: "Wizard cat"
}Invoking your function
Write and invoke a function to print "Wizard cat"
var myPets = [
["Ferdinand", "French bulldog", "cream"],
["Ginger", "dachshund/corgi", "red"],
["Zoey", "Australian cattle dog", "blue"],
["Ben", "Wizard cat", "white"]
];Stretch: write a function that uses a loop to print each pet's name
Arguments and Parameters
Why use them?
Makes your code dynamic and reusable
Arguments and Parameters
function myFunc (param1, param2) {
console.log(param1);
console.log(param2);
};
myFunc("argument1", "argument2")Arguments and Parameters
function greet2 (name) {
console.log("Hello, " + name);
};
greet2("Danny")Define a function named "greet2" that will take a name as a parameter and print "Hello, <name>"
Then invoke it with a name as an argument.
return keyword
function greet2 (name) {
return "Hi!";
console.log("Hello, " + name);
};
greet2("Danny")return keyword
returning something is the purpose of a function.
FUNCTIONS
By Valerie Kraucunas
FUNCTIONS
- 566