Functions, Parameters & Arguments

declaring (creating) a function

function half(x) {
    return x / 2;
}

calling (using) a function

const one = half(2)

Parameters & Arguments

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

Return values

A return statement specifies the function's output value

function square(x) {
    return x * x; 
}

const nine = square(3);

Some functions don't return anything

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

For practice

In the console, declare the following functions:

  • multiply: given 2 numbers, return their product
  • yell: given a lowercase string, log it in all caps to the console
  • longerThan: given 2 arrays, return whether the first is longer than the second

Arrow Functions

The => "fat arrow" lets us create an unnamed function without much code

(x, y) => x + y

In practice

function 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) //6

Another Example

const add = (x, y) => x + y;
function add(x, y) {
    return x + y;
}

is equivalent to 

 

For practice

In the console, declare the following functions using arrow functions

  • divide: given 2 numbers, return the first dividend by the second 
  • whisper: given a uppercase string, log it in all lowercase to the console
  • shorterThan: given 2 arrays, return whether the first is shorter than the second

Functions

By Sachin Sherchan