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() > Return a Function Before It Is Done (Cancel Function Execution)

Return a Function Before It Is Done (Cancel Function Execution)

Functions can be cancelled at any time during invocation by using the return keyword with or without a value. Below, we are canceling the add function if the parameters are undefined or not a number.

Live Code

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

var add = function(x, y) {
   // If the parameters are not numbers, return error.
   if (typeof x !== 'number' || typeof y !== 'number') {return 'pass in numbers';}
   return x + y;
}
console.log(add(3,3)); // logs 6
console.log(add('2','2')); // logs 'pass in numbers'

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

The takeaway here is that you can cancel a function’s execution by using the return keyword at any point in the execution of the function.


  

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