Call a Function Again After a Variable Update Javascript
Functions — reusable blocks of lawmaking
Another essential concept in coding is functions, which allow you to store a slice of code that does a single task inside a defined cake, and and then phone call that code whenever you demand information technology using a unmarried brusque command — rather than having to type out the same code multiple times. In this article we'll explore cardinal concepts behind functions such as basic syntax, how to invoke and ascertain them, scope, and parameters.
Where do I find functions?
In JavaScript, you'll discover functions everywhere. In fact, we've been using functions all the way through the course so far; we've just non been talking well-nigh them very much. Now is the fourth dimension, however, for u.s.a. to commencement 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 you lot'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 use of a office.
Built-in browser functions
We've made utilize of functions built in to the browser a lot in this course. Every fourth dimension we manipulated a text string, for instance:
const myText = 'I am a string' ; const newString = myText. replace ( 'string' , 'sausage' ) ; console. log (newString) ; // the supplant() string office takes a source string, // and a target string and replaces the source string, // with the target string, and returns the newly formed string
Or every time we manipulated an assortment:
const myArray = [ 'I' , 'love' , 'chocolate' , 'frogs' ] ; const madeAString = myArray. join ( ' ' ) ; console. log (madeAString) ; // the join() function takes an array, joins // all the assortment 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 betwixt // 0 and up to just not including 1, and returns that number
...we were using a function!
Note: Feel gratuitous 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 permit you to do useful things without having to write all that code yourself. In fact, some of the code you are calling when you lot invoke (a fancy word for run, or execute) a built in browser function couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages similar C++, non web languages like JavaScript.
Bear in mind that some built-in browser functions are not part of the core JavaScript linguistic communication — some are defined every bit part of browser APIs, which build on top of the default linguistic communication to provide even more functionality (refer to this early on section of our course for more descriptions). Nosotros'll look at using browser APIs in more detail in a later module.
Functions versus methods
Functions that are role of objects are called methods. You don't need to acquire about the inner workings of structured JavaScript objects still — you lot tin can look until our subsequently module that will teach you all nearly the inner workings of objects, and how to create your own. For now, we just wanted to clear upward any possible confusion of method versus function — you are likely to meet both terms as you look at the available related resource beyond the Web.
The built-in code we've made utilize of so far come in both forms: functions and methods. You lot can check the full list of the congenital-in functions, as well as the built-in objects and their respective methods here.
You've as well seen a lot of custom functions in the course and then far — functions defined in your code, not within the browser. Someday you saw a custom name with parentheses straight after it, y'all were using a custom function. In our random-canvas-circles.html example (meet also the full source lawmaking) from our loops article, nosotros included a custom draw()
function that looked like this:
function draw ( ) { ctx. clearRect ( 0 , 0 , WIDTH , Pinnacle ) ; for ( permit i = 0 ; i < 100 ; i++ ) { ctx. beginPath ( ) ; ctx.fillStyle = 'rgba(255,0,0,0.5)' ; ctx. arc ( random ( WIDTH ) , random ( HEIGHT ) , random ( fifty ) , 0 , ii * Math. PI ) ; ctx. fill ( ) ; } }
This function draws 100 random circles inside a <canvass>
element. Every time nosotros want to do that, we can just invoke the office with this:
rather than having to write all that code out again every time we want to repeat information technology. And functions can incorporate whatever code you like — you can fifty-fifty call other functions from inside functions. The above role for example calls the random()
office three times, which is defined past the post-obit code:
function random ( number ) { render Math. floor (Math. random ( ) *number) ; }
Nosotros needed this part because the browser's built-in Math.random() role only generates a random decimal number between 0 and 1. We wanted a random whole number betwixt 0 and a specified number.
Invoking functions
You are probably articulate on this by now, only but in instance ... to actually use a function after it has been defined, yous've got to run — or invoke — it. This is washed past including the name of the function in the lawmaking somewhere, followed by parentheses.
office myFunction ( ) { alert ( 'how-do-you-do' ) ; } myFunction ( ) ; // calls the office one time
Annotation: This form of creating a function is likewise known as function declaration. It is e'er hoisted, so you can call office in a higher place part definition and it will piece of work fine.
Function parameters
Some functions crave parameters to exist specified when yous are invoking them — these are values that need to be included inside the function parentheses, which it needs to do its job properly.
Notation: Parameters are sometimes chosen arguments, properties, or even attributes.
Equally an instance, the browser's built-in Math.random() function doesn't require any parameters. When called, it e'er returns a random number between 0 and 1:
const myNumber = Math. random ( ) ;
The browser's congenital-in string supplant() part however needs ii parameters — the substring to find in the main string, and the substring to supplant that string with:
const myText = 'I am a string' ; const newString = myText. replace ( 'string' , 'sausage' ) ;
Note: When yous need to specify multiple parameters, they are separated by commas.
Optional parameters
Sometimes parameters are optional — you don't accept to specify them. If you lot don't, the function will generally adopt some kind of default beliefs. As an case, the array join() part's parameter is optional:
const myArray = [ 'I' , 'love' , 'chocolate' , 'frogs' ] ; const madeAString = myArray. bring together ( ' ' ) ; console. log (madeAString) ; // returns 'I beloved chocolate frogs' const madeAnotherString = myArray. bring together ( ) ; console. log (madeAnotherString) ; // returns 'I,love,chocolate,frogs'
If no parameter is included to specify a joining/delimiting graphic symbol, a comma is used by default.
Default parameters
If you lot're writing a part and want to support optional parameters, you tin can specify default values past adding =
after the name of the parameter, followed by the default value:
function how-do-you-do (name= 'Chris' ) { console. log ( ` How-do-you-do ${name} ! ` ) ; } hullo ( 'Ari' ) ; // Hullo Ari! howdy ( ) ; // Hello Chris!
Anonymous functions and arrow functions
So far we have just created a function like so:
function myFunction ( ) { alert ( 'howdy' ) ; }
But y'all tin also create a function that doesn't have a name:
function ( ) { alert ( 'hi' ) ; }
This is called an anonymous function, considering information technology has no name. You'll often encounter bearding functions when a role expects to receive some other function as a parameter. In this example the role parameter is ofttimes passed equally an anonymous part.
Notation: This form of creating a function is also known as function expression. Dissimilar part proclamation, function expressions are not hoisted.
Bearding function example
For example, let's say y'all want to run some code when the user types into a text box. To do this you can call the addEventListener()
part of the text box. This function expects you to pass information technology (at least) two parameters:
- the proper noun of the issue to listen for, which in this case is
"keydown"
- a function to run when the event happens.
When the user presses a primal, the browser volition call the office you provided, and will pass it a parameter containing information about this event, including the item key that the user pressed:
function logKey ( result ) { console. log ( ` You pressed " ${consequence.key} ". ` ) ; } textBox. addEventListener ( 'keydown' , logKey) ;
Instead of defining a split up logKey()
role, y'all can pass an anonymous function into addEventListener()
:
textBox. addEventListener ( 'keydown' , role ( event ) { console. log ( ` You pressed " ${event.key} ". ` ) ; } ) ;
Arrow functions
If y'all pass an bearding function like this, at that place's an alternative form you lot tin use, called an arrow function. Instead of function(event)
, you write (upshot) =>
:
textBox. addEventListener ( 'keydown' , ( event ) => { panel. log ( ` You pressed " ${effect.key} ". ` ) ; } ) ;
If the function just has one line in the curly brackets, you omit the curly brackets:
textBox. addEventListener ( 'keydown' , ( event ) => console. log ( ` You pressed " ${event.central} ". ` ) ) ;
If the office only takes one parameter, you can too omit the brackets effectually the parameter:
textBox. addEventListener ( 'keydown' , effect => panel. log ( ` Yous pressed " ${event.key} ". ` ) ) ;
Finally, if your role needs to return a value, and contains but i line, you tin can also omit the return
statement. In the following example we're using the map()
method of Array
to double every value in the original assortment:
const originals = [ ane , 2 , iii ] ; const doubled = originals. map ( particular => item * 2 ) ; console. log (doubled) ; // [two, 4, half dozen]
The map()
method takes each item in the array in turn, passing it into the given role. It and so takes the value returned past that function and adds it to a new assortment.
And then in the example to a higher place, item => item * 2
is the arrow function equivalent of:
function doubleItem ( particular ) { render particular * two ; }
Nosotros recommend that you use arrow functions, every bit they can make your code shorter and more readable. To learn more, come across the section on arrow functions in the JavaScript guide, and our reference folio on pointer functions.
Note: There are some subtle differences betwixt arrow functions and normal functions. They're outside the telescopic of this introductory guide, and are unlikely to brand a difference in the cases we've discussed here. To larn more, see the arrow function reference documentation.
Pointer function live sample
Here'due south a complete working example of the "keydown" case 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' , event => output.textContent = ` Y'all pressed " ${event.primal} ". ` ) ;
The event - endeavor typing into the text box and encounter the output:
Function scope and conflicts
Permit'due south talk a flake virtually scope — a very important concept when dealing with functions. When you lot create a function, the variables and other things defined inside the role are within their ain split scope, meaning that they are locked away in their ain dissever compartments, unreachable from code exterior the functions.
The top level exterior all your functions is chosen the global telescopic. Values defined in the global scope are accessible from everywhere in the code.
JavaScript is gear up up like this for diverse reasons — but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code — external scripts that you lot phone call in from elsewhere could starting time to mess with your lawmaking and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be washed maliciously, or just by blow.
For example, say yous have an HTML file that is calling in two external JavaScript files, and both of them take a variable and a function divers that use the same name:
<!-- Excerpt from my HTML --> <script src = "first.js" > </script > <script src = "2d.js" > </script > <script > greeting ( ) ; </script >
// first.js const name = 'Chris' ; function greeting ( ) { alert ( ` Hullo ${name} : welcome to our company. ` ) ; }
// 2nd.js const name = 'Zaptec' ; function greeting ( ) { warning ( ` Our company is chosen ${name} . ` ) ; }
Both functions you want to telephone call are called greeting()
, but y'all tin just ever access the first.js
file's greeting()
function (the second one is ignored). In improver, an error results when attempting (in the second.js
file) to assign a new value to the name
variable — considering it was already declared with const
, and then tin't exist reassigned.
Keeping parts of your code locked away in functions avoids such bug, and is considered the best exercise.
Information technology is a bit similar a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and simply have access to the things inside their enclosures — in the same style as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats — a lion 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 scope — they have the keys to access every enclosure, to restock food, tend to sick animals, etc.
Agile learning: Playing with scope
Let's expect at a real example to demonstrate scoping.
- Get-go, make a local re-create of our part-scope.html example. This contains 2 functions chosen
a()
andb()
, and three variables —x
,y
, andz
— two of which are defined inside the functions, and one in the global telescopic. It also contains a third function calledoutput()
, which takes a single parameter and outputs it in a paragraph on the folio. - Open up the instance up in a browser and in your text editor.
- Open the JavaScript console in your browser developer tools. In the JavaScript panel, enter the following command: You should meet the value of variable
10
printed to the browser viewport. - Now try inbound 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 part scope —
y
andz
are locked inside thea()
andb()
functions, thenoutput()
tin't access them when called from the global scope. - However, what virtually when it's chosen from inside another part? Try editing
a()
andb()
and so they wait similar this:function a ( ) { const y = 2 ; output (y) ; } function b ( ) { const z = 3 ; output (z) ; }
a()
andb()
functions from the JavaScript console: Yous should see they
andz
values printed in the browser viewport. This works fine, equally theoutput()
role is beingness called within the other functions — in the same scope as the variables information technology is press are defined in, in each case.output()
itself is bachelor from anywhere, as information technology is defined in the global scope. - Now try updating your code like this:
function a ( ) { const y = 2 ; output (10) ; } function b ( ) { const z = 3 ; output (x) ; }
- Save and reload again, and attempt this again in your JavaScript console: Both the
a()
andb()
call should print the value of x to the browser viewport. These piece of work fine because even though theoutput()
calls are non in the same scope equallyx
is defined in,x
is a global variable then is bachelor within all lawmaking, everywhere. - Finally, try updating your code like this:
office a ( ) { const y = 2 ; output (z) ; } function b ( ) { const z = 3 ; output (y) ; }
- Save and reload once more, and attempt this once again in your JavaScript console: This fourth dimension the
a()
andb()
calls volition throw that annoying ReferenceError: variable name is not divers error into the console — this is considering theoutput()
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 aforementioned scoping rules do not apply to loop (eastward.g. for() { ... }
) and conditional blocks (e.g. if() { ... }
) — they look very similar, merely they are not the aforementioned thing! Accept intendance not to go these dislocated.
Note: The ReferenceError: "x" is not defined error is one of the most mutual you'll run across. If you get this error and you are sure that yous have defined the variable in question, check what telescopic information technology is in.
Test your skills!
You lot've reached the stop of this article, just can you remember the most important information? You tin can notice some further tests to verify that you've retained this information before you motility on — see Test your skills: Functions. These tests crave skills that are covered in the next two articles, and then you might desire to read those offset before trying information technology.
Conclusion
This article has explored the central concepts behind functions, paving the way for the side by side one in which we go applied and take you through the steps to edifice up your ain custom function.
Encounter besides
In this module
- Making decisions in your code — conditionals
- Looping code
- Functions — reusable blocks of code
- Build your own function
- Role render values
- Introduction to events
- Image gallery
Source: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions
0 Response to "Call a Function Again After a Variable Update Javascript"
Postar um comentário