Skip to content Skip to sidebar Skip to footer

How to Use Times to Run a Function Again and Again Pythonh

Functions — reusable blocks of code

  • Previous
  • Overview: Building blocks
  • Next

Another essential concept in coding is functions, which allow you to store a piece of code that does a unmarried task inside a defined block, and and so call that code whenever yous demand it using a single curt command — rather than having to blazon out the same code multiple times. In this article nosotros'll explore fundamental concepts behind functions such every bit basic syntax, how to invoke and ascertain them, scope, and parameters.

Where do I find functions?

In JavaScript, you'll find functions everywhere. In fact, we've been using functions all the mode through the grade so far; we've just not been talking most them very much. Now is the time, nevertheless, for us to starting time talking virtually functions explicitly, and really exploring their syntax.

Pretty much someday you brand use of a JavaScript structure that features a pair of parentheses — () — and you're not using a common built-in language construction like a for loop, while or do...while loop, or if...else statement, you are making apply of a function.

Built-in browser functions

We've made utilize of functions congenital in to the browser a lot in this course. Every time nosotros manipulated a text string, for instance:

                                      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.                    join                    (                    ' '                    )                    ;                    console.                    log                    (madeAString)                    ;                    // the join() function takes an array, joins                    // all the array items together into a single                    // string, and returns this new cord                                  

Or every fourth dimension we generated a random number:

                                      const                    myNumber                    =                    Math.                    random                    (                    )                    ;                    // the random() office generates a random number between                    // 0 and up to but non including 1, and returns that number                                  

...we were using a role!

Notation: Feel 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 born functions to permit you to practice 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 part couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in depression-level system languages like C++, not web languages like JavaScript.

Bear in listen that some built-in browser functions are not role of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to this early department of our course for more descriptions). We'll look at using browser APIs in more item in a later module.

Functions versus methods

Functions that are role of objects are called methods. You don't need to learn about the inner workings of structured JavaScript objects all the same — you tin can wait until our later on module that volition teach you all about the inner workings of objects, and how to create your own. For at present, we just wanted to clear up whatever possible confusion of method versus part — you are probable to meet both terms as you lot look at the available related resources beyond the Spider web.

The born code nosotros've made use of and then far come in both forms: functions and methods. You can check the full list of the congenital-in functions, also as the built-in objects and their corresponding methods here.

You've likewise seen a lot of custom functions in the form and then far — functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our random-canvass-circles.html example (see also the full source code) from our loops article, we included a custom describe() role that looked similar this:

                                      function                    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                    (                    Summit                    )                    ,                    random                    (                    50                    )                    ,                    0                    ,                    2                    *                    Math.                    PI                    )                    ;                    ctx.                    fill                    (                    )                    ;                    }                    }                                  

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

rather than having to write all that code out again every time we want to repeat information technology. And functions tin contain whatever code you lot similar — you lot can fifty-fifty call other functions from inside functions. The above role for instance calls the random() function three times, which is divers by the post-obit lawmaking:

                                      role                    random                    (                    number                    )                    {                    return                    Math.                    flooring                    (Math.                    random                    (                    )                    *number)                    ;                    }                                  

Nosotros needed this function because the browser'southward built-in Math.random() part just generates a random decimal number between 0 and 1. Nosotros wanted a random whole number between 0 and a specified number.

Invoking functions

Yous are probably clear on this past now, only only in instance ... to actually use a function after information technology has been defined, you've got to run — or invoke — information technology. This is washed by including the proper noun of the function in the lawmaking somewhere, followed by parentheses.

                                      function                    myFunction                    (                    )                    {                    alert                    (                    'hello'                    )                    ;                    }                    myFunction                    (                    )                    ;                    // calls the office one time                                  

Note: This form of creating a function is likewise known equally function declaration. Information technology is always hoisted, so you lot can call function higher up function definition and it will work fine.

Part parameters

Some functions crave parameters to be specified when you lot are invoking them — these are values that need to exist included inside the function parentheses, which information technology needs to do its job properly.

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

As an case, the browser's built-in Math.random() part doesn't require any parameters. When called, information technology always returns a random number betwixt 0 and ane:

                                      const                    myNumber                    =                    Math.                    random                    (                    )                    ;                                  

The browser'southward congenital-in cord replace() part all the same needs ii parameters — the substring to observe in the main string, and the substring to replace that cord with:

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

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

Optional parameters

Sometimes parameters are optional — you lot don't have to specify them. If you don't, the function will generally adopt some kind of default beliefs. Every bit an instance, the array join() part'southward parameter is optional:

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

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

Default parameters

If you're writing a function and desire to support optional parameters, you tin can specify default values by adding = after the name of the parameter, followed by the default value:

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

Anonymous functions and pointer functions

So far we have just created a part similar so:

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

But you tin likewise create a function that doesn't accept a name:

                                      role                    (                    )                    {                    alert                    (                    'how-do-you-do'                    )                    ;                    }                                  

This is chosen an anonymous function, because it has no proper noun. You'll oftentimes come across anonymous functions when a function expects to receive some other part as a parameter. In this case the office parameter is often passed as an anonymous function.

Note: This course of creating a office is likewise known as function expression. Different function annunciation, function expressions are not hoisted.

Bearding function example

For example, let's say you want to run some lawmaking when the user types into a text box. To exercise this yous can call the addEventListener() function of the text box. This function expects you to pass it (at to the lowest degree) ii parameters:

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

When the user presses a key, the browser will phone call the office you provided, and will pass it a parameter containing data about this event, including the detail fundamental that the user pressed:

                                      office                    logKey                    (                    event                    )                    {                    panel.                    log                    (                                          `                      You lot pressed "                                              ${result.key}                                            ".                      `                                        )                    ;                    }                    textBox.                    addEventListener                    (                    'keydown'                    ,                    logKey)                    ;                                  

Instead of defining a carve up logKey() function, you can pass an anonymous part into addEventListener():

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

Arrow functions

If you laissez passer an anonymous function like this, there'south an culling course you can utilize, chosen an arrow function. Instead of role(effect), y'all write (outcome) =>:

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

If the function simply has ane line in the curly brackets, y'all omit the curly brackets:

                  textBox.                    addEventListener                    (                    'keydown'                    ,                    (                    event                    )                    =>                    panel.                    log                    (                                          `                      Y'all pressed "                                              ${issue.key}                                            ".                      `                                        )                    )                    ;                                  

If the office only takes one parameter, you lot can besides omit the brackets around the parameter:

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

Finally, if your function needs to return a value, and contains just i line, you can besides omit the return statement. In the post-obit instance we're using the map() method of Array to double every value in the original assortment:

                                      const                    originals                    =                    [                    ane                    ,                    2                    ,                    3                    ]                    ;                    const                    doubled                    =                    originals.                    map                    (                    particular                    =>                    item                    *                    2                    )                    ;                    console.                    log                    (doubled)                    ;                    // [2, iv, 6]                                  

The map() method takes each detail in the array in turn, passing it into the given function. It then takes the value returned past that role and adds it to a new array.

So in the case above, detail => item * 2 is the arrow office equivalent of:

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

We recommend that you utilize pointer functions, as they can make your lawmaking shorter and more than readable. To learn more than, see the section on arrow functions in the JavaScript guide, and our reference page on arrow functions.

Note: At that place are some subtle differences between arrow functions and normal functions. They're outside the scope of this introductory guide, and are unlikely to make a difference in the cases we've discussed hither. To larn more, see the arrow function reference documentation.

Arrow role alive sample

Here'due south a consummate working case of the "keydown" example nosotros 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'                    ,                    upshot                    =>                    output.textContent                    =                                          `                      You pressed "                                              ${event.central}                                            ".                      `                                        )                    ;                                  

The upshot - endeavour typing into the text box and see the output:

Function scope and conflicts

Let's talk a chip well-nigh scope — a very important concept when dealing with functions. When you create a office, the variables and other things defined inside the office are inside their own separate scope, meaning that they are locked away in their own split compartments, unreachable from code exterior the functions.

The peak 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 fix like this for various reasons — but mainly because of security and organisation. Sometimes you don't want variables to exist accessible from everywhere in the code — external scripts that you telephone call in from elsewhere could start to mess with your lawmaking and cause problems considering they happen to be using the same variable names every bit other parts of the code, causing conflicts. This might be washed maliciously, or just past blow.

For example, say you lot have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a office defined that use the same proper noun:

                                      <!-- Excerpt from my HTML -->                                                                  <script                      src                                              =                        "showtime.js"                                            >                                                                                                          </script                      >                                                                                      <script                      src                                              =                        "second.js"                                            >                                                                                                          </script                      >                                                                                      <script                      >                                                                                      greeting                        (                        )                        ;                                                                                                            </script                      >                                                      
                                      // starting time.js                    const                    proper noun                    =                    'Chris'                    ;                    function                    greeting                    (                    )                    {                    alert                    (                                          `                      How-do-you-do                                                                    ${name}                                            : welcome to our company.                      `                                        )                    ;                    }                                  
                                      // 2nd.js                    const                    name                    =                    'Zaptec'                    ;                    office                    greeting                    (                    )                    {                    alert                    (                                          `                      Our company is called                                                                    ${name}                                            .                      `                                        )                    ;                    }                                  

Both functions y'all desire to call are called greeting(), but you can only ever access the first.js file's greeting() function (the 2nd one is ignored). In addition, an fault 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 and then tin can't be reassigned.

Keeping parts of your code locked abroad in functions avoids such issues, and is considered the best exercise.

It is a bit similar a zoo. The lions, zebras, tigers, and penguins are kept in their ain enclosures, and simply have access to the things inside their enclosures — in the same manner every bit the function scopes. If they were able to become into other enclosures, problems would occur. At best, unlike animals would feel really 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 similar the global telescopic — they have the keys to access every enclosure, to restock food, tend to sick animals, etc.

Active learning: Playing with scope

Permit's wait at a existent example to demonstrate scoping.

  1. Kickoff, brand a local copy of our function-scope.html instance. This contains 2 functions chosen a() and b(), and 3 variables — x, y, and z — two of which are divers within the functions, and ane in the global scope. It also contains a third function chosen output(), which takes a single parameter and outputs it in a paragraph on the page.
  2. Open the example upward in a browser and in your text editor.
  3. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command: You lot should see the value of variable ten printed to the browser viewport.
  4. Now try entering the following in your console Both of these should throw an error into the console along the lines of "ReferenceError: y is not defined". Why is that? Because of part telescopic — y and z are locked inside the a() and b() functions, and so output() can't admission them when called from the global telescopic.
  5. However, what nearly when it'south chosen from inside another function? Try editing a() and b() and then they look like this:
                                                  office                        a                        (                        )                        {                        const                        y                        =                        2                        ;                        output                        (y)                        ;                        }                        role                        b                        (                        )                        {                        const                        z                        =                        3                        ;                        output                        (z)                        ;                        }                                          
    Save the code and reload it in your browser, then attempt calling the a() and b() functions from the JavaScript console: You should see the y and z values printed in the browser viewport. This works fine, every bit the output() function is being chosen inside the other functions — in the same scope as the variables it is printing are defined in, in each case. output() itself is available from anywhere, as it is defined in the global telescopic.
  6. Now try updating your code like this:
                                                  function                        a                        (                        )                        {                        const                        y                        =                        2                        ;                        output                        (10)                        ;                        }                        part                        b                        (                        )                        {                        const                        z                        =                        three                        ;                        output                        (x)                        ;                        }                                          
  7. Save and reload again, and effort this once again in your JavaScript console: Both the a() and b() call should print the value of x to the browser viewport. These piece of work fine because fifty-fifty though the output() calls are not in the same scope equally 10 is defined in, 10 is a global variable then is available within all code, everywhere.
  8. Finally, try updating your lawmaking like this:
                                                  function                        a                        (                        )                        {                        const                        y                        =                        2                        ;                        output                        (z)                        ;                        }                        role                        b                        (                        )                        {                        const                        z                        =                        3                        ;                        output                        (y)                        ;                        }                                          
  9. Save and reload again, and try this again in your JavaScript panel: This time the a() and b() calls will throw that annoying ReferenceError: variable name is not defined error into the console — this is considering 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 function calls.

Note: The same scoping rules do non apply to loop (e.k. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very like, only they are non the same affair! Have care not to get these confused.

Note: The ReferenceError: "10" is not defined error is one of the most mutual you'll encounter. If you lot get this error and you are sure that y'all accept defined the variable in question, check what scope it is in.

Test your skills!

You've reached the end of this article, just can y'all recollect the nearly important data? You tin discover some farther tests to verify that you've retained this data earlier you lot move on — meet Exam your skills: Functions. These tests crave skills that are covered in the side by side two manufactures, so you might desire to read those outset before trying information technology.

Conclusion

This article has explored the primal concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to edifice upwardly your own custom function.

See as well

In this module

perezdesch2000.blogspot.com

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

Enregistrer un commentaire for "How to Use Times to Run a Function Again and Again Pythonh"