Chapter 5Functions

Our programs are getting complex. Even if we try to separate our input, processing, and output, as programs get more complex, it gets harder and harder to find things.

But we can use functions to organize our code, and we can even create reusable components.

Functions act like smaller programs inside our main program. Here’s some JavaScript code that defines a function that adds two numbers:

 
function​ addTwoNumbers(firstNumber, secondNumber) {
 
return​(
 
firstNumber + secondNumber
 
);
 
}

The addTwoNumbers function takes in two numbers as its input, does the calculation, and returns the result to the rest of the program. Here’s how to use it:

 
var​ sum = addTwoNumbers(1,2);
 
console.log(sum);

Another benefit of functions ...

Get Exercises for Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.