1/21/2014

Functions: declarations and expressions | JavaScript Tutorial
Log in

JavaScript Tutorial
Home » Tutorial » JavaScript: from the Ground to Closures
‹ Loops and switch String › Tutorial

JavaScript: from the Ground to Closures
JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Functions: declarations and expressions
Ilya Kantor

1. The syntax 1. Returning a value 2. Local variables 2. Function Declaration 3. Function Expression 1. Use declarations, please 4. Function is a value 1. Passing a function around 5. Running at place 6. Named function expressions 7. Function naming 8. Summary A function, like a variable, can be defined anywhere in the code. JavaScript provides several ways of defining them: Function Declaration Function Expression Function as a result of a n e wF u n c t i o ncall

Like

2

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

The syntax
The basic syntax to create a function is a Function Declaration. The syntax is: f u n c t i o nf ( a r g 1 ,a r g 2 ,. . . ){ . . .c o d e. . . } Looks like this:
Run!

Donate Donate to this project

1 f u n c t i o ns a y H i ( n a m e ){ 2 a l e r t ( " H i ," + n a m e ) 3 } 4 5 s a y H i ( ' J o h n ' )

The example above declares a function named s a y H iwith a single argument n a m eand calls it.

Returning a value
To return a value, use r e t u r nstatement:
Run!

1 2 3 4 5 6

f u n c t i o ns u m ( a ,b ){ }

r e t u r na + b

v a rr e s u l t=s u m ( 2 , 5 ) a l e r t ( r e s u l t )

If a function does not return anything, it’s result is considered to be a special value, u n d e f i n e d . You can check it out on the following example.
Run!

1 2 3 4 5 6 7

f u n c t i o ng e t N o t h i n g ( ){ / /n or e t u r n } v a rr e s u l t=g e t N o t h i n g ( ) a l e r t ( r e s u l t )

An empty return gives same result:

http://javascript.info/tutorial/functions-declarations-and-expressions

1/6

1 0 0 )=1 * 1 * . http://javascript. The demo: tutorial/intro/pow. Or. xis multiplied by itself ntimes.1 )= =1 Open solution Write a function p o w ( x . . . n )which returns xin the n t hpower.html Open solution Function Declaration Nested functions come later Here in this section. b )which takes two numbers and returns the lesser one. then outputs the result of p o w ( x ." + n a m e ) 5 } A function can be declared anywhere in the code . Everything in due time. 1 f u n c t i o ns u m ( a . p o w ( 3 . right now we need to get the most important stuff right." + n a m e ) 3 } 4 5 s a y H i ( " J o h n " ) … But changed order also works: Run! 1 s a y H i ( " J o h n " ) 2 3 f u n c t i o ns a y H i ( n a m e ){ 4 a l e r t ( " H i .info/tutorial/functions-declarations-and-expressions 2/6 . This works: Run! 1 f u n c t i o ns a y H i ( n a m e ){ 2 a l e r t ( " H i . Such variables are called local and are only visible inside the function. m i n ( 2 . when the browser prepares to execute the code. Function Declarations are parsed at pre-execution stage.5 ) = =2 m i n ( 3 . in other words. They are covered later in Initialization of functions and variables and the next articles.1/21/2014 Run! Functions: declarations and expressions | JavaScript Tutorial 1 f u n c t i o ng e t N o t h i n g ( ){ 2 r e t u r n 3 } 4 a l e r t (g e t N o t h i n g ( )= = =u n d e f i n e d)/ /t r u e Local variables A function may contain variables. defined by v a r .b ){ 2 v a rs u m=a+b 3 4 r e t u r ns u m 5 } Create a function m i n ( a . * 1=1 Create a page with prompts for xand n . n ) . we are not talking about advanced topics like nested functions.3 )=3 * 3 * 3=2 7 p o w ( 1 . That’s why the function declared this way can be called both after and before the definition.2 )=3 * 3=9 p o w ( 3 .

} . .g for conditional function definition. declared “at place” with a function expression syntax: f u n c t i o n ( a r g u m e n t s ){. So the i fstatement doesn’t affect anything. v a rf=f u n c t i o n ( ){. . the result is the same in all browsers. . For example. Anywhere where you could put a value. f u n c t i o nf ( ){. Function Expression A function in JavaScript is a first-class value. Function Expressions can be used only after they are executed . . you can do: v a rf=5 But you can also assign it to a function expression: Run! 1 v a rf=f u n c t i o n ( n a m e ){ 2 a l e r t ( " H i . E. . Use them instead. http://javascript. When a f u n c t i o ncomes as a part of a statement. just like a number or string. . .5). it assumes Function Declaration. functions declared this way can be called before it’s definition. . . . you can also put a function . . . functions are often declared by expressions: . . depending on the condition: Run! 1 2 3 4 5 6 7 s a y H i ( ) i f( 1 ){ f u n c t i o ns a y H i ( ){ a l e r t ( 1 ) } }e l s e{ f u n c t i o ns a y H i ( ){ a l e r t ( 2 ) }/ /< } Try running the example above in different browsers. other browsers output 2. Function Declarations are much more readable and shorter. When it comes to execution. the declarations are ignored. At the time of writing. That’s because the declarations are parsed before the execution. . . When the JavaScript parser sees a f u n c t i o nin the main code flow.10. Besides. 3 } When `function` means Expression and when it's a Declaration? The rule is simple.c o d e. Use declarations. .t h e r ei sn os a y H iy e t 0 4 0 5 i f( 1 ){ 0 6 s a y H i=f u n c t i o n ( ){ a l e r t ( 1 ) } 0 7 }e l s e{ 0 8 s a y H i=f u n c t i o n ( ){ a l e r t ( 2 ) } 0 9 } 1 0 1 1 s a y H i ( ) In the example above. . please In the code of unexperienced developers.} . . According to the specification (p. it is a Function Expression.} . Function Expressions are created when the execution flow reaches them. Use expressions only if you mean it."+n a m e+" ! " ) . the latter function with same name overwrites the existing one. we may want to declare a function differently.c o d e. As a consequence. Run! 0 1 v a rs a y H i 0 2 0 3 / /s a y H i ( )< -c a n ' tc a l lh e r e .1/21/2014 Functions: declarations and expressions | JavaScript Tutorial For example.info/tutorial/functions-declarations-and-expressions 3/6 . . Firefox gives error.

2 / /. When I assign it to h i . We don’t want our local variables to become global. That is. We could even output it: Run! 1 f u n c t i o nf ( ){a l e r t ( 1 )} 2 3 a l e r t ( f ) The example above outputs the function. Why f u n c t i o nis in brackets? That’s because JavaScript only allows Function Expressions to be called in-place. for example: Run! 1 2 3 4 5 6 7 f u n c t i o ns a y H i ( n a m e ){ a l e r t ( " H i ." + n a m e ) } v a rh i=s a y H i/ /a s s i g naf u n c t i o nt oa n o t h e rv a r i a b l e h i ( " d u d e " ) / /c a l lt h ef u n c t i o n The function is assigned by reference. . . One function can accept another function as an argument. Usually as the source code. . .1/21/2014 Functions: declarations and expressions | JavaScript Tutorial Function is a value A function in JavaScript is a regular value. we create a function without a name. Running at place It is possible to create and run a function created with Function Expression at once. That’s a good practice. like this: Run! 1 ( f u n c t i o n ( ){ 2 3 v a ra . 3 } ( ) http://javascript. Run! 1 2 3 4 5 6 7 f u n c t i o nr u n W i t h O n e ( f ){ / /r u n sg i v e nf u n c t i o nw i t ha r g u m e n t1 f ( 1 ) } r u n W i t h O n e ( f u n c t i o n ( a ) {a l e r t ( a )} ) Logically. the global namespace is still clean. .b / /l o c a lv a r i a b l e s 4 5 / /. Such functions are called anonymous functions. In the example above. a function is an action. a function is kept somewhere in memory and s a y H iis a reference (or you could say pointer) to it. a function can be assigned. both variables start to reference the same function. JavaScript would see the f u n c t i o nkeyword and try to parse Function Delaration: Run! 1 f u n c t i o n ( ){/ /e r r o r . Passing a function around Just like any value. and don’t assign it to any variable. 3 } ( ) / /s y n t a xe r r o r Even if we remove the name.info/tutorial/functions-declarations-and-expressions 4/6 . And it doesn’t matter how it was defined. Function Declarations can’t be called like that: Run! 1 f u n c t i o nw o r k ( ){ 2 / /. So. . Only the creation time is different. passed as a parameter for another function and so on. This feature is widely used in JavaScript. so wrap the code into a function.f u n c t i o nd e c l a r a t i o nw i t h o u tn a m e . After the execution. passing a function around is transferring an action which can be initiated from another part of the program. Both declarations and expression declare a variable and put the function into it. / /a n dt h ec o d e 6 7 } ) ( ) Running in place is mostly used when we want to do the job involving local variables.

1/21/2014 hence a Function Expression. 2 ) .S. That’s just like v a rr e s u l t=s u m ( 2 . Then the interpreter consider it as a part of a statement. then there’s no need in wrapping it. almost never. In those browsers which support it. See the following f a c t o r i a lfunction wrapped into s e t T i m e o u tcall: s e t T i m e o u t ( f u n c t i o nf a c t o r i a l ( n ){ r e t u r nn= =1?n:n * f a c t o r i a l ( n 1 ) } . the function is created and called instantly. It takes arguments list and body as strings and creates a function from them: Run! 1 v a rs a y H i=n e wF u n c t i o n ( ' n a m e ' .'a l e r t ( " H i . It is used very very rarely. where s u mis replaced by a function expression. Named function expressions A function expression may have a name: v a rf=f u n c t i o ns a y H i ( n a m e ){ a l e r t ( " H i . b ){r e t u r na + b} ( 2 . for instance: Run! 1 v a rr e s u l t=f u n c t i o n ( a . What will be the result of code execution? Why? 1 v a ra=5 2 3 ( f u n c t i o n ( ){ 4 a l e r t ( a ) 5 } ) ( ) P. If the function is obviously an expression." + n a m e ) } The syntax is called named function expression (or NFE) and works as it should in all browsers except IE<9. the only way is to wrap the function in brackets.e r r o r( gi su n d e f i n e d )i no t h e rb r o w s e r s 4 a l e r t ( f = = =g ) NFEs exist to allow recursive calls from anonymous functions. Functions: declarations and expressions | JavaScript Tutorial So. Think well! Pitfall ahead! Ok. 2 ) 2 a l e r t ( r e s u l t )/ /4 In the code above." + n a m e )' ) . the name is visible inside the function only: 1 v a rf=f u n c t i o ns a y H i ( n a m e ){ 2 a l e r t ( s a y H i )/ /o u t p u t sf u n c t i o n 3 } 4 5 a l e r t ( s a y H i )/ /e r r o r :u n d e f i n e dv a r i a b l e' s a y H i ' IE will actually create two function objects in such case: s a y H iand f : Run! 1 v a rf=f u n c t i o ng ( ){ } 2 3 / /f a l s ei nI E .1 0 0 ) What is the result of the code? Why? (f u n c t i o ng ( ){r e t u r n1}) a l e r t ( g ) Open solution http://javascript. 2 3 s a y H i ( " B e n e d i c t " ) . you’ve been warned Open solution There is one more way which uses a direct call to F u n c t i o nconstructor.info/tutorial/functions-declarations-and-expressions 5/6 .

1/21/2014 Functions: declarations and expressions | JavaScript Tutorial Function naming A function is an action. Summary Functions in JavaScript are regular values. the name of a function should be a verb or multiple words starting with a verb. A function is used everywhere in the code. Short function names can be allowed if: A function is temporary and used only in nearest code. Can be called only after creation. 2011. © Ilya Kantor. Function Expression f u n c t i o nis created as a part of an expression. JavaScript libraries use these names to make frequent calls shorter.r e a d . like g e t . ‘$A’. ‘$F’ etc. Function Declaration f u n c t i o nis used in the main code flow Created at pre-execution stage. http://javascript. or it is extremely widely used. Can be called in-place Generally. So it’s name should be a verb. you have less writing.info/tutorial/functions-declarations-and-expressions 6/6 . Same logic as with variables. Can be called both before and after the definition. and from the other hand. etc. there is no danger to forget what it does. In other cases. ‹ Loops and switch String › The content of this site is available under the terms of CC BY-NC-SA. They can be assigned. A function which returns nothing actually returns special value: u n d e f i n e d . ‘$$’.c a l c u l a t e S u m . Created when the execution reaches it. The real-world examples are ‘$’. So from the one hand. "JavaScript™ is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp. Use verbs to name functions. Short names are allowable in two edge cases: a name is used in the nearest code only. it is recommended to use D e c l a r a t i o nunless there is a reason for E x p r e s s i o n . passed around and called when needed.