Chapter 5
Functions

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 is that the logic is encapsulated in the body of the function, and it can be changed without affecting the programs that use it. For example, our function takes in two values, but if we called it like this

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

then the program’s output would be 12, because JavaScript will concatenate strings instead of converting them to numbers. But we can modify the addTwoNumbers function to convert the input to numbers automatically so the function will always work.

Often, we’ll take the result of one function and send it on to another function. Or we’ll evaluate the result of a function to make a decision. Some programming languages are based entirely on functions, like Elixir and Clojure. Those are the aptly named functional programming languages.

When solving the problems in this chapter, organize your code into functions. Try to encapsulate the main algorithm into a function that you invoke from the rest of your program. Or go further and create functions that capture the input and construct the output.

This chapter is intentionally short, because when you finish these exercises, you should revisit your previous programs and see how functions can improve the organization of those programs as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.121