Return the Sum of Two Numbers

Photo by Paul Esch-Laurent on Unsplash

Task: Return the Sum of Two Numbers

Instructions: Create a function that takes two numbers as arguments and return their sum.

What are functions?

Functions are one of the fundamental building blocks in JavaScript. A function is composed of a sequence of statements called the function body, but for a function to qualify as one, it should take an input (as function parameters) and return an output where there is a relationship between the two.

Anatomy of a function

A Function definition (also known as function declaration or function statement) consists of the function keyword, followed by:

  • The name of the function (addition);
  • One or a list of parameters to the function, enclosed in parentheses and (in case there is more than one) separated by commas (a, b); and
  • The JavaScript statements that defines the function, enclosed in curly braces, {...}.

Arrow functions

Arrow function expressions have a shorter syntax (with limited functionality) compared to function expressions and are always anonymous.

What does the return statement do for my function?

The return statement ends function execution and specifies a value to be returned to the function caller. Its syntax return [expression]; includes an expression whose value is to be returned. If omitted, undefined is returned instead.

Data validation: typeof

What would happen if we would use any other type of parameter in our addition function? In order to make sure the function serves its purpose correctly, we can make use of the JavaScript typeof operator.

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by the question mark (?), then an expression to execute if the condition is truthy, followed by a colon (:), and finally the expression if the condition is falsy. This operator is frequently used as a shortcut for the if statement. Finally, refactoring our typeof data validation and utilising the conditional (ternary) operator our function would look as follows:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store