Returning Values from Functions

  • Many times you will write a function and expect a value to be returned - this is called a return value

  • To have your function return a value you must use the return keyword in the last line of the body of your function

  • We use the return keyword when we want our function to “give us back” a value

  • You can store the returned value in a variable and use it later in your program


Example

// declare a function called bark
// that *returns* a string respreseting 'woof woof'
function bark() {
  return 'woof woof!'
}

// call the bark function and store result in a variable
const sound = bark()

// print out result to the console
console.log(`a dog makes the following sound ${sound}`)

JS Bin on jsbin.com

  • If you don’t use the return keyword, then no value will be returned

// declare a function called meow
// that generates a string representing 'meow' but
// does not use the return keyword

function meow() {
  'meow'
}  

// call the meow function and store result in a variable
const sound = meow()

// print out result to the console
console.log(`a cat makes the following sound ${sound}`)
JS Bin on jsbin.com


Exercise

  • Create a function called sayMoo that returns the string mooooooo!. Next, call the function and store the result into a variable named cowSound

JS Bin on jsbin.com