O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Functions

Variables are certainly an important part of any programming language; developers could not create efficient and meaningful applications without them. However, a language without any means of organizing code can lead to inefficient applications. In fact, some early programming languages, such as those used for punch cards (and languages based on them like RPG II), lacked organizational constructs, which resulted in many lines of repeated code.

Consider an application that performs the same series of operations on multiple variables. The following shows an example of such an application:

var valueOne = 100;
valueOne = valueOne + 150;
valueOne = valueOne / 2;
valueOne = "The value is: " + valueOne; // results in "The value is: 125"

var valueTwo = 50;
valueTwo = valueTwo + 150;
valueTwo = valueTwo / 2;
valueTwo = "The value is: " + valueTwo; // results in "The value is: 100"

var valueThree = 2;
valueThree = valueThree + 150;
valueThree = valueThree / 2;
valueThree = "The value is: " + valueThree; // results in "The value is: 76"

This is code duplication. The same operations are duplicated three times for three variables. Imagine having to repeat these same operations over and over again for as many variables as your program needs. Also imagine needing to change the addition operation (+ 150) to a subtraction operation (- 150). Not only would you have to make three changes with this code, but you'd also need to make the same change to any other variable that used the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required