Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > Functions Always Return a Value

Functions Always Return a Value

While it’s possible to create a function simply to execute code statements, it’s also very common for a function to return a value. Below, we are returning a string from the sayHi function.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var sayHi = function() {
   return 'Hi';
};

console.log(sayHi()); // logs "Hi"

</script></body></html>

If a function does not specify a return value, then undefined is returned. Below, we call the yelp function, which logs the string 'yelp' to the console without explicitly returning a value.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var yelp = function() {
   console.log('I am yelping!');
   // functions return undefined even if we don't
}

/* logs true because a value is always returned, 
even if we don't specifically return one */
console.log(yelp() === undefined);

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint