Chapter 3. Functions

Mastering functions is an important skill when you learn any programming language, and even more so when it comes to JavaScript. This is because JavaScript has many uses for functions, and much of the language's flexibility and expressiveness comes from them. Where most programming languages have a special syntax for some object-oriented features, JavaScript just uses functions. This chapter will cover the following topics:

  • How to define and use a function
  • Passing arguments to a function
  • Predefined functions that are available to you for free
  • The scope of variables in JavaScript
  • The concept that functions are just data, albeit a special type of data

Understanding these topics will provide a solid base that will allow you to dive into the second part of the chapter, which shows some interesting applications of functions, as follows:

  • Using anonymous functions
  • Callbacks
  • Immediate (self-invoking) functions
  • Inner functions (functions defined inside other functions)
  • Functions that return functions
  • Functions that redefine themselves
  • Closures

What is a function?

Functions allow you to group together a code, give it a name, and reuse it later, addressing it by the name you gave it. Let's consider the following code as an example:

    function sum(a, b) { 
      var c = a + b; 
      return c; 
    } 

The parts that make up a function are shown as follows:

  • The function keyword.
  • The name of the function; in this case, sum.
  • The function parameters; in this case, a and b. A function can take any number of parameters, or no parameters, separated by commas.
  • A code block, also called the body of the function.
  • The return statement. A function always returns a value. If it doesn't return a value explicitly, it implicitly returns the value undefined.

Note that a function can only return a single value. If you need to return more values, you can simply return an array that contains all of the values you need as elements of this array.

The preceding syntax is called a function declaration. It's just one of the ways to create a function in JavaScript, and more ways are coming up.

Calling a function

In order to make use of a function, you will need to call it. You can call a function simply using its name, optionally, followed by any number of values in parentheses. To invoke a function is another way of saying to call.

Let's call the sum()function, passing two arguments and assigning the value that the function returns to the variable result:

    > var result = sum(1, 2); 
    > result; 
    3 

Parameters

When defining a function, you can specify what parameters the function expects to receive when it's called. A function may not require any parameters, but if it does, and you forget to pass them, JavaScript will assign the undefined value to the ones you skipped. In the next example, the function call returns NaN because it tries to sum 1 and undefined:

    > sum(1); 
    NaN 

Technically speaking, there is a difference between parameters and arguments, although the two are often used interchangeably. Parameters are defined together with the function, while arguments are passed to the function when it's called. Consider the following example:

    > function sum(a, b) { 
        return a + b; 
      } 
    > sum(1, 2); 

Here, a and b are parameters, while 1 and 2 are arguments.

JavaScript is not picky at all when it comes to accepting arguments. If you pass more than the function expects, the extra ones will be silently ignored, as shown in the following example:

    > sum(1, 2, 3, 4, 5); 
    3 

What's more, you can create functions that are flexible about the number of parameters they accept. This is possible thanks to the special value arguments that are created automatically inside each function. Here's a function that simply returns whatever arguments are passed to it:

    > function args() { 
        return arguments; 
      } 
    > args(); 
    [] 
    > args( 1, 2, 3, 4, true, 'ninja'), 
    [1, 2, 3, 4, true, "ninja"] 

Using arguments, you can improve the sum() function to accept any number of arguments and add them all up, as shown in the following example:

    function sumOnSteroids() { 
      var i, 
          res = 0, 
          number_of_params = arguments.length; 
      for (i = 0; i < number_of_params; i++) { 
        res += arguments[i]; 
      } 
      return res; 
    } 

If you test this function by calling it with a different number of arguments, or even none at all, you can verify that it works as expected, as you can see in the following example:

    > sumOnSteroids(1, 1, 1); 
    3 
    > sumOnSteroids(1, 2, 3, 4); 
    10 
    > sumOnSteroids(1, 2, 3, 4, 4, 3, 2, 1); 
    20 
    > sumOnSteroids(5); 
    5 
    > sumOnSteroids(); 
    0 

The arguments.length expression returns the number of arguments passed when the function was called. Don't worry if the syntax is unfamiliar, we'll examine it in detail in the next chapter. You'll also see that arguments is not an array (although it sure looks like one), but an array-like object.

ES6 introduces several important improvements around function parameters. ES6 function parameters can now have default values, rest parameters, and allows destructuring. The next section discusses each of these concepts in detail.

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

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