declaring (creating) a function
function half(x) {
return x / 2;
}calling (using) a function
const one = half(2)Some functions need more than one value to work with
function add(x, y) {
return x + y;
}
add(2,3);Some functions don't even need any values
function getRandomNumber() {
return Math.random();
}
getRandomNumber();parameters are the inputs a function expects
function add3(x, y, z) {
console.log("My parameters are named x, y, z");
console.log("I received the arguments", x, y, z);
return x + y + z;
}
const sum = add3(4,5,6);arguments are the actual values the function is called with
Parameters should be named like variables, and behave like variables within the function body
function doesThisWork("literally a value") {
return true;
}function howAboutThis(1weirdVariable!) {
return true;
}What happens if we don't call a function with the intended argument(s)?
add3(1,2)function add3(x, y, z) {
console.log("My parameters are named x, y, z");
console.log("I received the arguments", x, y, z);
return x + y + z;
}
const sum = add3(4,5,6);Try calling the function
A return statement specifies the function's output value
function square(x) {
return x * x;
}
const nine = square(3);function sayHello(name) {
console.log("Oh hi, " + name + "!");
}sayHello("Marc");What value is returned when there's no return?
const hm = sayHello("Marc");What value is returned when there's no return?
const hm = sayHello("Marc");undefined
In the console, declare the following functions:
=> "fat arrow" lets us create an unnamed function without much code(x, y) => x + yfunction multiplyBy2(input) { return input * 2; }
const multiplyBy2 = (input) => { return input*2 }
const multiplyBy2 = (input) => input * 2
const multiplyBy2 = input => input * 2
const output = multiplyBy2(3) //6Another Example
const add = (x, y) => x + y;function add(x, y) {
return x + y;
}is equivalent to
In the console, declare the following functions using arrow functions