Functions

Built-in Functions

What are some functions that we know?

prompt("number please...");
console.log("hi");
parseInt("5");

We can write our own functions!

Creating Functions

  1. start with the keyword, function
  2. followed by the name of your function
  3. followed by parentheses
  4. the parentheses can be empty, OR can include an optional list of comma separated parameters (input)
  5. followed by a block of code between curly braces

Syntax:

function functionName(param1, param2) {
  Some statement(s) here;
}

Why Create Functions?

Basic Functions

Here’s a bare bones function….

function foo() {
  console.log("FOO!");
}

What does this function do and how would you execute (call) it?→

A Function With Parameters

To create a function that has an input, and executes some code…

function foo(s) {
	console.log(s + "!");
}

How does this improve on the previous example?→

How would you call this function, using it to print "Hello world!" to the console?→

A Function With Parameters That Returns a Value

To create a function that has an inputs, and returns a value….

function foo(s) {
	return s + "!";
}
console.log(foo("hi"));

How does this differ from the previous example?→

Calling Functions

You can use a function as you would use a variable…

// as part of an expression
var sum = someNum + calcSomething(x);

// in a function call
console.log(calcGrade(num));

// inside another function
function calcGrade(x) {
  return someNum + calcNum(y);
}

How does this differ from the previous example?→