Javascript required
Skip to content Skip to sidebar Skip to footer

If I Want to Reuse a Function in Js Do I Have to Type in Function Again

Functions — reusable blocks of code

  • Previous
  • Overview: Building blocks
  • Side by side

Another essential concept in coding is functions, which allow you to store a piece of lawmaking that does a single job inside a defined block, and and so call that lawmaking whenever y'all need it using a single short command — rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts backside functions such as basic syntax, how to invoke and ascertain them, scope, and parameters.

Where practise I discover functions?

In JavaScript, you'll find functions everywhere. In fact, we've been using functions all the fashion through the course then far; we've just non been talking about them very much. Now is the time, however, for u.s.a. to start talking about functions explicitly, and really exploring their syntax.

Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses — () — and y'all're not using a common born linguistic communication construction like a for loop, while or practice...while loop, or if...else argument, yous are making apply of a role.

Built-in browser functions

We've made use of functions built in to the browser a lot in this course. Every time we manipulated a text cord, for example:

                                      const                    myText                    =                    'I am a string'                    ;                    const                    newString                    =                    myText.                    supersede                    (                    'string'                    ,                    'sausage'                    )                    ;                    console.                    log                    (newString)                    ;                    // the replace() string function takes a source string,                    // and a target string and replaces the source string,                    // with the target string, and returns the newly formed cord                                  

Or every time we manipulated an array:

                                      const                    myArray                    =                    [                    'I'                    ,                    'love'                    ,                    'chocolate'                    ,                    'frogs'                    ]                    ;                    const                    madeAString                    =                    myArray.                    bring together                    (                    ' '                    )                    ;                    panel.                    log                    (madeAString)                    ;                    // the join() office takes an array, joins                    // all the array items together into a single                    // string, and returns this new string                                  

Or every time we generated a random number:

                                      const                    myNumber                    =                    Math.                    random                    (                    )                    ;                    // the random() function generates a random number between                    // 0 and upwardly to simply non including one, and returns that number                                  

...we were using a function!

Note: Experience free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality, if needed.

The JavaScript language has many built-in functions to let you to do useful things without having to write all that lawmaking yourself. In fact, some of the code you are calling when you invoke (a fancy give-and-take for run, or execute) a built in browser function couldn't exist written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in depression-level arrangement languages like C++, not web languages similar JavaScript.

Bear in heed that some built-in browser functions are not part of the core JavaScript language — some are defined as function of browser APIs, which build on top of the default language to provide fifty-fifty more than functionality (refer to this early section of our course for more than descriptions). Nosotros'll look at using browser APIs in more item in a subsequently module.

Functions versus methods

Functions that are part of objects are chosen methods. Y'all don't demand to learn almost the inner workings of structured JavaScript objects nevertheless — you can wait until our after module that volition teach you all about the inner workings of objects, and how to create your own. For at present, we simply wanted to clear upwards any possible confusion of method versus role — you are likely to run across both terms as you lot await at the available related resources across the Web.

The congenital-in code we've made utilize of and then far come in both forms: functions and methods. Yous tin can check the full listing of the built-in functions, as well as the born objects and their respective methods here.

Yous've as well seen a lot of custom functions in the form so far — functions defined in your code, non inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom part. In our random-canvas-circles.html instance (run into also the total source lawmaking) from our loops article, we included a custom draw() function that looked like this:

                                      part                    draw                    (                    )                    {                    ctx.                    clearRect                    (                    0                    ,                    0                    ,                    WIDTH                    ,                    HEIGHT                    )                    ;                    for                    (                    let                    i                    =                    0                    ;                    i                    <                    100                    ;                    i++                    )                    {                    ctx.                    beginPath                    (                    )                    ;                    ctx.fillStyle                    =                    'rgba(255,0,0,0.5)'                    ;                    ctx.                    arc                    (                    random                    (                    WIDTH                    )                    ,                    random                    (                    Acme                    )                    ,                    random                    (                    50                    )                    ,                    0                    ,                    two                    *                    Math.                    PI                    )                    ;                    ctx.                    fill                    (                    )                    ;                    }                    }                                  

This function draws 100 random circles inside a <canvas> element. Every time we want to do that, we can just invoke the office with this:

rather than having to write all that lawmaking out once again every time we want to echo information technology. And functions tin comprise whatever code you like — you can fifty-fifty call other functions from inside functions. The above role for example calls the random() function iii times, which is defined past the following lawmaking:

                                      function                    random                    (                    number                    )                    {                    return                    Math.                    floor                    (Math.                    random                    (                    )                    *number)                    ;                    }                                  

We needed this function because the browser'due south built-in Math.random() function simply generates a random decimal number betwixt 0 and ane. Nosotros wanted a random whole number between 0 and a specified number.

Invoking functions

Yous are probably clear on this past now, but merely in case ... to actually use a function after it has been defined, y'all've got to run — or invoke — it. This is washed by including the name of the office in the code somewhere, followed by parentheses.

                                      role                    myFunction                    (                    )                    {                    warning                    (                    'hello'                    )                    ;                    }                    myFunction                    (                    )                    ;                    // calls the office once                                  

Notation: This grade of creating a part is also known as function announcement. Information technology is always hoisted, so you can phone call office above office definition and information technology volition piece of work fine.

Office parameters

Some functions require parameters to exist specified when you lot are invoking them — these are values that demand to be included inside the function parentheses, which it needs to practise its job properly.

Note: Parameters are sometimes chosen arguments, properties, or even attributes.

Every bit an instance, the browser'south born Math.random() function doesn't require whatsoever parameters. When called, it always returns a random number between 0 and 1:

                                      const                    myNumber                    =                    Math.                    random                    (                    )                    ;                                  

The browser'due south built-in string supervene upon() part however needs two parameters — the substring to observe in the main string, and the substring to replace that string with:

                                      const                    myText                    =                    'I am a string'                    ;                    const                    newString                    =                    myText.                    replace                    (                    'string'                    ,                    'sausage'                    )                    ;                                  

Annotation: When you need to specify multiple parameters, they are separated by commas.

Optional parameters

Sometimes parameters are optional — you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. Equally an instance, the array join() function's parameter is optional:

                                      const                    myArray                    =                    [                    'I'                    ,                    'love'                    ,                    'chocolate'                    ,                    'frogs'                    ]                    ;                    const                    madeAString                    =                    myArray.                    join                    (                    ' '                    )                    ;                    console.                    log                    (madeAString)                    ;                    // returns 'I honey chocolate frogs'                    const                    madeAnotherString                    =                    myArray.                    bring together                    (                    )                    ;                    panel.                    log                    (madeAnotherString)                    ;                    // returns 'I,beloved,chocolate,frogs'                                  

If no parameter is included to specify a joining/delimiting character, a comma is used by default.

Default parameters

If y'all're writing a office and want to back up optional parameters, yous tin can specify default values by adding = subsequently the name of the parameter, followed by the default value:

                                      function                    hello                    (proper noun=                    'Chris'                    )                    {                    panel.                    log                    (                                          `                      Hello                                                                    ${name}                                            !                      `                                        )                    ;                    }                    hello                    (                    'Ari'                    )                    ;                    // Hello Ari!                    hello                    (                    )                    ;                    // Hello Chris!                                  

Bearding functions and arrow functions

So far nosotros accept just created a office like then:

                                      office                    myFunction                    (                    )                    {                    alert                    (                    'hello'                    )                    ;                    }                                  

But you tin as well create a function that doesn't have a proper name:

                                      function                    (                    )                    {                    alarm                    (                    'hello'                    )                    ;                    }                                  

This is called an bearding function, considering it has no proper noun. You'll often come across anonymous functions when a office expects to receive another function as a parameter. In this instance the function parameter is often passed as an anonymous function.

Note: This form of creating a part is besides known as function expression. Different function proclamation, role expressions are non hoisted.

Anonymous function example

For case, let'south say you desire to run some lawmaking when the user types into a text box. To practice this you tin phone call the addEventListener() function of the text box. This function expects you to pass it (at least) two parameters:

  • the proper name of the result to listen for, which in this case is keydown
  • a function to run when the event happens.

When the user presses a central, the browser will telephone call the function you provided, and will pass it a parameter containing information about this effect, including the particular key that the user pressed:

                                      function                    logKey                    (                    event                    )                    {                    console.                    log                    (                                          `                      You pressed "                                              ${event.central}                                            ".                      `                                        )                    ;                    }                    textBox.                    addEventListener                    (                    'keydown'                    ,                    logKey)                    ;                                  

Instead of defining a split up logKey() role, you lot can pass an anonymous office into addEventListener():

                  textBox.                    addEventListener                    (                    'keydown'                    ,                    role                    (                    outcome                    )                    {                    console.                    log                    (                                          `                      You pressed "                                              ${consequence.key}                                            ".                      `                                        )                    ;                    }                    )                    ;                                  

Arrow functions

If you pass an bearding function like this, there's an alternative form you can apply, chosen an arrow role. Instead of function(event), you write (event) =>:

                  textBox.                    addEventListener                    (                    'keydown'                    ,                    (                    outcome                    )                    =>                    {                    console.                    log                    (                                          `                      You pressed "                                              ${issue.key}                                            ".                      `                                        )                    ;                    }                    )                    ;                                  

If the function merely has 1 line in the curly brackets, yous omit the curly brackets:

                  textBox.                    addEventListener                    (                    'keydown'                    ,                    (                    consequence                    )                    =>                    console.                    log                    (                                          `                      You pressed "                                              ${event.key}                                            ".                      `                                        )                    )                    ;                                  

If the function only takes one parameter, you lot can likewise omit the brackets effectually the parameter:

                  textBox.                    addEventListener                    (                    'keydown'                    ,                    upshot                    =>                    console.                    log                    (                                          `                      You pressed "                                              ${outcome.key}                                            ".                      `                                        )                    )                    ;                                  

Finally, if your function needs to return a value, and contains merely one line, y'all tin can also omit the return statement. In the post-obit case nosotros're using the map() method of Array to double every value in the original array:

                                      const                    originals                    =                    [                    1                    ,                    two                    ,                    3                    ]                    ;                    const                    doubled                    =                    originals.                    map                    (                    item                    =>                    particular                    *                    two                    )                    ;                    console.                    log                    (doubled)                    ;                    // [two, 4, six]                                  

The map() method takes each item in the assortment in plow, passing it into the given function. It then takes the value returned by that function and adds it to a new assortment.

So in the example above, item => item * two is the arrow office equivalent of:

                                      part                    doubleItem                    (                    particular                    )                    {                    render                    item                    *                    2                    ;                    }                                  

We recommend that you apply arrow functions, every bit they can make your lawmaking shorter and more readable. To acquire more, run into the section on pointer functions in the JavaScript guide, and our reference page on arrow functions.

Note: In that location are some subtle differences betwixt arrow functions and normal functions. They're outside the scope of this introductory guide, and are unlikely to make a difference in the cases nosotros've discussed here. To learn more, encounter the arrow function reference documentation.

Arrow role live sample

Here'southward a complete working example of the "keydown" instance we discussed above:

The HTML:

                                                                                    <input                      id                                              =                        "textBox"                                            type                                              =                        "text"                                            >                                                                                      </input                      >                                                                                      <div                      id                                              =                        "output"                                            >                                                                                      </div                      >                                                      

The JavaScript:

                                      const                    textBox                    =                    document.                    querySelector                    (                    "#textBox"                    )                    ;                    const                    output                    =                    document.                    querySelector                    (                    "#output"                    )                    ;                    textBox.                    addEventListener                    (                    'keydown'                    ,                    outcome                    =>                    output.textContent                    =                                          `                      You pressed "                                              ${effect.fundamental}                                            ".                      `                                        )                    ;                                  

The upshot - try typing into the text box and run into the output:

Function telescopic and conflicts

Let'south talk a chip about telescopic — a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the part are inside their own separate scope, significant that they are locked away in their ain dissever compartments, unreachable from code outside the functions.

The tiptop level outside all your functions is called the global scope. Values defined in the global telescopic are accessible from everywhere in the lawmaking.

JavaScript is set upward similar this for various reasons — only mainly because of security and organization. Sometimes you lot don't want variables to be accessible from everywhere in the code — external scripts that you telephone call in from elsewhere could outset to mess with your code and cause bug because they happen to be using the aforementioned variable names as other parts of the code, causing conflicts. This might be washed maliciously, or merely past accident.

For example, say you take an HTML file that is calling in two external JavaScript files, and both of them have a variable and a part defined that use the aforementioned name:

                                      <!-- Excerpt from my HTML -->                                                                  <script                      src                                              =                        "starting time.js"                                            >                                                                                                          </script                      >                                                                                      <script                      src                                              =                        "2d.js"                                            >                                                                                                          </script                      >                                                                                      <script                      >                                                                                      greeting                        (                        )                        ;                                                                                                            </script                      >                                                      
                                      // first.js                    const                    proper noun                    =                    'Chris'                    ;                    function                    greeting                    (                    )                    {                    alert                    (                                          `                      Howdy                                                                    ${name}                                            : welcome to our company.                      `                                        )                    ;                    }                                  
                                      // 2d.js                    const                    proper name                    =                    'Zaptec'                    ;                    role                    greeting                    (                    )                    {                    alert                    (                                          `                      Our company is called                                                                    ${name}                                            .                      `                                        )                    ;                    }                                  

Both functions y'all desire to call are called greeting(), but you can only always access the first.js file'due south greeting() function (the 2d 1 is ignored). In addition, an mistake results when attempting (in the second.js file) to assign a new value to the name variable — because information technology was already declared with const, and then can't be reassigned.

Keeping parts of your code locked away in functions avoids such bug, and is considered the best do.

Information technology is a chip like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures — in the same mode as the role scopes. If they were able to get into other enclosures, problems would occur. At best, unlike animals would feel actually uncomfortable inside unfamiliar habitats — a king of beasts or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to consume the penguins!

The zoo keeper is like the global scope — they have the keys to access every enclosure, to restock nutrient, tend to sick animals, etc.

Active learning: Playing with telescopic

Let'southward look at a existent instance to demonstrate scoping.

  1. First, make a local copy of our part-scope.html case. This contains two functions called a() and b(), and 3 variables — ten, y, and z — two of which are defined inside the functions, and one in the global telescopic. It likewise contains a third function chosen output(), which takes a unmarried parameter and outputs it in a paragraph on the page.
  2. Open the example up in a browser and in your text editor.
  3. Open the JavaScript panel in your browser developer tools. In the JavaScript console, enter the following command: You should see the value of variable x printed to the browser viewport.
  4. Now try entering the following in your console Both of these should throw an fault into the console along the lines of "ReferenceError: y is not defined". Why is that? Because of function telescopic — y and z are locked within the a() and b() functions, so output() can't access them when called from the global scope.
  5. However, what most when it's chosen from within another function? Endeavor editing a() and b() and then they await like this:
                                                  function                        a                        (                        )                        {                        const                        y                        =                        2                        ;                        output                        (y)                        ;                        }                        function                        b                        (                        )                        {                        const                        z                        =                        3                        ;                        output                        (z)                        ;                        }                                          
    Save the code and reload information technology in your browser, then try calling the a() and b() functions from the JavaScript console: You should encounter the y and z values printed in the browser viewport. This works fine, equally the output() function is being called within the other functions — in the same telescopic as the variables it is printing are defined in, in each case. output() itself is bachelor from anywhere, as it is defined in the global telescopic.
  6. Now try updating your lawmaking like this:
                                                  function                        a                        (                        )                        {                        const                        y                        =                        ii                        ;                        output                        (10)                        ;                        }                        function                        b                        (                        )                        {                        const                        z                        =                        3                        ;                        output                        (10)                        ;                        }                                          
  7. Relieve and reload once more, and try this once more in your JavaScript panel: Both the a() and b() call should print the value of x to the browser viewport. These work fine because even though the output() calls are not in the same scope as 10 is defined in, x is a global variable so is available inside all lawmaking, everywhere.
  8. Finally, endeavor updating your code like this:
                                                  function                        a                        (                        )                        {                        const                        y                        =                        2                        ;                        output                        (z)                        ;                        }                        office                        b                        (                        )                        {                        const                        z                        =                        3                        ;                        output                        (y)                        ;                        }                                          
  9. Save and reload again, and try this again in your JavaScript console: This time the a() and b() calls volition throw that annoying ReferenceError: variable name is non defined mistake into the console — this is because the output() calls and the variables they are trying to print are not in the same function scopes — the variables are effectively invisible to those role calls.

Note: The same scoping rules do not utilise to loop (e.m. for() { ... }) and conditional blocks (east.g. if() { ... }) — they wait very similar, but they are not the same affair! Take intendance not to get these confused.

Notation: The ReferenceError: "ten" is not defined mistake is i of the most common yous'll meet. If you get this error and yous are sure that you have divers the variable in question, check what scope it is in.

Test your skills!

You've reached the end of this article, merely can you think the most of import information? You can find some further tests to verify that yous've retained this data before you motility on — run across Test your skills: Functions. These tests require skills that are covered in the adjacent two manufactures, so you might want to read those outset earlier trying it.

Decision

This commodity has explored the primal concepts behind functions, paving the fashion for the next one in which we go applied and take you through the steps to edifice upwardly your own custom office.

See besides

In this module

mokarejudings.blogspot.com

Source: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions