var myfunction = function () {
BODY
}Expression declaration
function as a part of a larger expression syntax (typically a variable assignment )
function name () {
BODY
}statement declaration
var func = x => x * x;
var func = (x, y) => { return x + y; };Arrow, "fat arrow" syntax
var func = new Function();Not recommended.
Write a function named "greet" that will print out "Hello World!"
function greet() {
console.log("Hello World!");
}What will the console.log return?
var whisper = "Kittens are magic";
function yell() {
whisper = whisper.toUpperCase();
console.log(whisper);
}
console.log(whisper);Why?
What's different here?
var whisper = "Kittens are magic";
function yell() {
whisper = whisper.toUpperCase();
console.log(whisper);
}
yell()
Write and invoke a function to print "Wizard cat"
var myPets = {
Ginger: "dachshund/corgi",
Ferdinand: "French bulldog",
Zoey: "Australian cattle dog",
Ben: "Wizard cat"
}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
Why use them?
Makes your code dynamic and reusable
function myFunc (param1, param2) {
console.log(param1);
console.log(param2);
};
myFunc("argument1", "argument2")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.
function greet2 (name) {
return "Hi!";
console.log("Hello, " + name);
};
greet2("Danny")returning something is the purpose of a function.