Function example

Here's a not very useful function:

function add(x, y) {
  return x + y;

Call Me, Maybe

You call a function by its name, plus parentheses:

function add(x, y) {
  return x + y;

add(2, 3)   // returns 5
add(12, 30) // returns 42

Lab: isDivisible

One number is divisible by another if you divide them and the remainder is 0.

Write a function called isDivisibleBy that takes two numbers, and returns true if the first number is divisible by the second number, and false otherwise.

isDivisibleBy(100, 10)    // true
isDivisibleBy(100, 7)     // false
isDivisibleBy(3333, 11)   // true
isDivisibleBy(99, 12)     // false


function rant(opinion) {
  return opinion.toUpperCase().replace(/ /g, "") + "!!!"

console.log(rant("i like pizza"));

/ /g is a regular expression; for now just think of it like a weird string. It defines the substring to replace, and the g at the end stands for "global" and means "replace them all, not just the first one".


function capitalize(s) {
  return s[0].toUpperCase() + s.slice(1).toLowerCase()


<!-- TODO: move this to either arrays or closures lesson, or a separate map-reduce lesson


function capitalize(s) {
  return s[0].toUpperCase() + s.slice(1).toLowerCase()

function titlecase(s) {
  return s.split(' ').map((word) => capitalize(word)).join(' ');

console.log(titlecase("the rain in spain falls MAINLY on the PLAIN"));


Function names can be variable names

The following two are roughly equivalent:

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

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

Modern Debugging   Null



Functions Slides - Code Like This