Example: biology

FUNCTIONS - nostarch.com

2 FUNCTIONSWe have alreadyusedseveral FUNCTIONS in the previouschapter things such asalertandprint to order themachine to perform a specific operation. In this chap-ter, we will startcreatingour own FUNCTIONS , making itpossible to extend the vocabulary that we have avail-able. In a way, this resembles defining our own wordsinside a story we are writing to increase our expressive-ness. Although such a thing is considered rather badstyle in prose, in programming it is Anatomy of a Function DefinitionIn its most basic form, a function definition looks like this:functionsquare(x) {return x*x;}square(12); 144 Eloquent javascript 2011 by Marijn HaverbekeHere,squareisthe name of the the name of its (first andonly) x*x;is the body of the keywordfunctionis always used when creating a new function.

JavaScript, fortunately, is from a generation of languages that solve this problem by going out of their way to preserve the local variable as long as it is in any way reachable.

Tags:

  Javascript

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of FUNCTIONS - nostarch.com

1 2 FUNCTIONSWe have alreadyusedseveral FUNCTIONS in the previouschapter things such asalertandprint to order themachine to perform a specific operation. In this chap-ter, we will startcreatingour own FUNCTIONS , making itpossible to extend the vocabulary that we have avail-able. In a way, this resembles defining our own wordsinside a story we are writing to increase our expressive-ness. Although such a thing is considered rather badstyle in prose, in programming it is Anatomy of a Function DefinitionIn its most basic form, a function definition looks like this:functionsquare(x) {return x*x;}square(12); 144 Eloquent javascript 2011 by Marijn HaverbekeHere,squareisthe name of the the name of its (first andonly) x*x;is the body of the keywordfunctionis always used when creating a new function.

2 Whenit is followed by a variable name, the new function will be stored under thisname. After the name comes a list of argument names and finally the bodyof the function. Unlike those around the body ofwhileloops orifstate-ments, the braces around a function body are keywordreturn, followed by an expression, is used to determine thevalue the function returns. When control comes across areturnstatement, itimmediately jumps out of the current function and gives the returned valueto the code that called the function. Areturnstatement without an expres-sion after it will cause the function to body can, of course, have more than one statement in it.

3 Here is afunction for computing powers (with positive, integer exponents):functionpower(base, exponent) {var result = 1;for (var count = 0; count < exponent; count++)result*= base;return result;}power(2, 10); 1024 Thearguments to a function behave like variables but ones that aregiven a value by thecallerof the function, not the function itself. The func-tion is free to give them a new value though, just like normal OrderEven though function definitions occur as statements between the rest of theprogram, they are not part of the same timeline. In the following example,the first statement can call thefuturefunction, even though its definitioncomes later:print("Thefuture says: ", future());function future() {return "We STILL have no flying cars.}

4 ";}Whatis happening is that the computer looks up all function defini-tions, and stores the associated FUNCTIONS ,beforeit starts executing the rest ofthe program. The nice thing about this is that we do not have to think aboutthe order in which we define and use our FUNCTIONS they are all allowed tocall each other, regardless of which one is defined 2 Eloquent javascript 2011 by Marijn HaverbekeLocalVariablesA very important property of FUNCTIONS is that the variables created insideof them arelocalto the function. This means, for example, that theresultvariable in thepowerexample will be newly created every time the functionis called and will no longer exist after the function returns.

5 In fact, ifpowerwere to call itself, that call would cause anew, distinctresultvariable to becreated and used by the inner call and would leave the variable in the outercall localness of variables applies only to the arguments of the func-tion and those variables that are declared with thevarkeyword inside thefunction. It is possible to accessglobal(nonlocal) variables inside a function,as long as you haven t declared a local variable with the same following code demonstrates this. It defines (and calls) two func-tions that both change the value of the variablex. The first one does not de-clare the variable as local and thus changes the global variable defined at thestart of the example.

6 The second does declare it and ends up changing onlythe local = "A";function setVarToB() {x = "B";}setVarToB();x; "B";function setVarToC() {var x;x = "C";}setVarToC();x; "B";Asan aside, note that these FUNCTIONS contain noreturnstatements, be-cause they are called for their side effects, not to create a value. The actualreturn value of such FUNCTIONS ScopeIn javascript , it is not enough to simply distinguish betweenglobalandlocalvariables. In fact, there can be any number of stacked (or nested) variablescopes. FUNCTIONS defined inside other FUNCTIONS can refer to the local vari-ables in their parent function, FUNCTIONS defined inside those inner func-tions can refer to variables in both their parent and their grandparent func-tions, and so javascript 2011 by Marijn HaverbekeTakea look at this example.

7 It defines a function that takes the absolute(positive) value ofnumberand multiplies that (number, factor) {function multiply(number) {return number*factor;}if (number < 0)return multiply(-number);elsereturn multiply(number);}Theexample is intentionally confusing in order to demonstrate a subtle-ty it contains two separate variables namednumber. When the body of thefunctionmultiplyruns, it uses the samefactorvariable as the outer func-tion but has its ownnumbervariable (created for the argument of that name).Thus, it multiplies its own argument by thefactorpassed this comes down to is that the set of variables visible inside a func-tion is determined by the place of that function in the program text.

8 All var-iables that were defined above a function s definition are visible, whichmeans both those in function bodies that enclose it and those at the top lev-el of the program. This approach to variable visibility is calledlexical who have experience with other programming languages mightexpect that a block of code (between braces) also produces a new local envi-ronment. Not in javascript . FUNCTIONS are the only things that create a newscope. You are allowed to use free-standing blocks:varsomething = 1;{var something = 2;// Do stuff with variable }// Outside of the block the block refers to the same variable as the oneoutside the block.

9 In fact, although blocks like this are allowed, they are onlyuseful to group the body of anifstatement or a loop. (Most people agreethat this is a bit of a design blunder by the designers of javascript , and laterversions of the language will add some way to define variables that stay insideblocks.)32 Chapter 2 Eloquent javascript 2011 by Marijn HaverbekeTheStackTo understand how FUNCTIONS are called and how they return, it is usefulto be aware of a thing called thestack. When a function is called, control isgiven to the body of that function. When that body returns, the code thatcalled the function is resumed. Thus, while the body is running, the com-puter must remember the context from which the function was called sothat it knows where to continue afterward.

10 The place where this context isstored is the reason that it is called a stack has to do with the fact that, as we saw,a function body can again call a function. Every time a function is called, an-other context has to be stored. One can visualize this as a stack of time a function is called, the current context is thrown on top of thestack. When a function returns, the context on top is taken off the stack stack requires space in the computer s memory to be stored. Whenthe stack grows too big, the computer will give up with a message like out ofstack space or too much recursion. The following code illustrates that itasks the computer a really hard question, which causes an infinite back-and-forth between two FUNCTIONS .


Related search queries