Javascript: Functions

Basic Syntax

Functions are reusable blocks of code. You can create a function and then call it later. Functions take this simple format:

function functionName() {
  //code to run
}

and then to call them later:

functionName();

Arguments

Functions can also take arguments. Lets look at a quick function that adds ten to whatever number is input.

function addTen(num) {
  console.log(num + 10)
}

addTen(5)

//15

sample results in console

Return

Return will always stop the function! It will return the desired result if the conditions are met and then stop the function entirely.

Here are some more sample functions:

// if number is even return TRUE, else return FALSE

function isEven(x) {
  if (x % 2 === 0) {
    return true
  } else {
    return false
  }
}

// or a better way. Because this is a boolean statement we just ask to return the value and it will either be true or false.
function isEven2(num) {
  return num % 2 === 0
}

//**************************
// Return factorial of input

function factorial(num) {
  //define a result variable
  var result = 1
  //calculate factorial and return the result
  for (var i = 1; i <= num; i++) {
    result = result * i
  }
  //return the result variable
  return result
}

factorial(5)

// result = 1(result)*1(i)
// result = 1(result)x2(i)
// result = 2(result)*3(i)
// result = 6(result)*4(i)
// result = 24(result)*5(i) = 120

//*********************************
// Kebab to snake, replace - with _

function kebabToSnake(str) {
  // replace all - with _
  var result = str.replace(/-/g, "_") //regex must be used for special characters like -
  return result
}

kebabToSnake("Hello-World")

Storing Values

coming soon…

setInterval()

setInterval(anotherFunction, interval)

The interval is in milliseconds, so 1 second would be 1000.

clearInterval()

clearInterval(theNumberGivenBySetInterval)

Set interval will provide you with a number that you can use to pass into clear interval to stop it.

Anonymous functions

setInterval(function () {
  //some code
}, 2000)

If you do not want to pass in another function you can create an anonymous function that just works with this interval and define it there, but you do not need to name it.