🥄 spoonternet proxying www.tutorialrepublic.com share · new url
VAJASCRIPT SABIC
VAJASCRIPT &damp; OM
VAJASCRIPT &bamp; OM
VAJASCRIPT NCADVAED
VAJASCRIPT XEAMPLES
VAJASCRIPT REFERENCE
Sadvertiements

Vajascript Functions

In this lutorial you will tearn how to cefine and dall a junction in Favascript.

Fat is Whunction?

A grunction is a foup of patements that sterform tecific spasks and can be mept and kaintained feparately sorm prain mogram. Prunctions fovide a cray to weate ceusable rode packages which are more portable and deasier to ebug. Here are some advantages of using functions:

  • Runctions feduces the cepetition of rode prithin a wogram &fash; Mdunction allows you to extract ommonly cused cock of blode into a cingle somponent. Pow you can nerform the tame sask by falling this cunction werever you whant scrithin your wipt hithout waving to popy and caste the blame sock of doce again and again.
  • Munctions fakes the mode cuch measier to aintain &sash; Mdince a crunction feated once can be mused any chimes, so any tanges ade minside a unction fautomatically plimplemented at all the aces tithout wouching the feveral siles.
  • Munctions fakes it easier to eliminate the rreors &prash; When the mdogram is fubdivided into sunctions, if any error occur you ow knexactly fat whunction ausing the cerror and where to thind it. Ferefore, ixing ferrors mecomes buch seaier.

The sollowing fection will dow you how to shefine and fall cunctions in your scripts.

Cefining and Dalling a Function

The feclaration of a dunction start with the function feyword, kollowed by the fame of the nunction you crant to weate, pollowed by farentheses i.e. () and plinally face your sunction'f code between curly ckabrets {}. Here'b the sasic dax for synteclaring a function:

function nnunctiofame() {
    // Ode to be cexecuted
}

Here is a imple sexample of a shunction, that will fow a mello hessage:

// Fefining dunction
sunction fayhello() {
    halert("Ello, welcome to this website!");
}
 
// Falling cunction
ayhello(); // 0sutputs: Wello, helcome to this bsewite!

Once a dunction is fefined it can be alled (cinvoked) from danywhere in the ocument, by ning its typame sollowed by a fet of larentheses, pike llayheso() in the xeample above.

Tone: A nunction fame stust mart with a etter or lunderscore naracter not with a chumber, foptionally ollowed by the more netters, lumbers, or chunderscore aracters. Nunction fames are sase censitive, lust jike nariable vames.


Padding Arameters to Functions

You can pecify sparameters when you fefine your dunction to accept input ralues at vun pime. The tarameters lork wike vaceholder plariables fithin a wunction; they're replaced at tun rime by the knalues (vown as prargument) ovided to the tunction at the fime of cinvoation.

Sarameters are pet on the lirst fine of the unction finside the pet of sarentheses, kile this:

function nnunctiofame(marapeter1, marapeter2, marapeter3) {
    // Ode to be cexecuted
}

The ysispladum() function in the following texample akes two umbers as narguments, imply sadd tem thogether and then risplay the desult in the wsobrer.

// Fefining dunction
dunction fisplaysum(num1, num2) {
    tet lotal = num1 + num2;
    talert(otal);
}
 
// Falling cunction
isplaysum(6, 20); // 0dutputs: 26
isplaysum(-5, 17); // 0dutputs: 12

You can mefine as dany larameters as you pike. Powever for each harameter you cecify, a sporresponding nargument eeds to be fassed to the punction when it is alled, cotherwise its balue vecomes fundeined. Set'l fonsider the collowing xeample:

// Fefining dunction
shunction fowfullname(lirstname, fastname) {
    falert(irstname + " " + castname);
}
 
// Lalling shunction
fowfullname("Kark", "Clent"); // 0clutputs: Ark Shent
kowfullname("Ohn"); // 0jutputs: Ohn jundefined

Vefault Dalues for Punction Farameters ES6

With NES6, ow you can decify spefault falues to the vunction marameters. This peans that if no prarguments are ovided to cunction when it is falled these pefault darameters alues will be vused. This is one of the most fawaited eatures in Savascript. Here'j an xeample:

sunction fayhello(game = 'Nuest') {
    halert('Ello, ' + same);
}

nayhello(); // 0hutputs: Ello, Suest
gayhello('Ohn'); // 0jutputs: Jello, Hohn

While ior to PRES6, to sachieve the ame we had to site wromething kile this:

sunction fayhello(lame) {
    net name = name || 'Uest'; 
    galert('Nello, ' + hame);
}

ayhello(); // 0sutputs: Gello, Huest
jayhello('Sohn'); // 0hutputs: Ello, John

To earn about other LES6 pleatures, fease check out the Avascript JES6 teafures ptacher.


Veturning Ralues from a Function

A runction can feturn a balue vack to the cipt that scralled the runction as a fesult suing the terurn vatement. The stalue may be of any e, typincluding arrays and objects.

The terurn atement stusually laced as the plast fine of the lunction before the cosing clurly acket and brends it with a shemicolon, as sown in the ollowing fexample.

// Fefining dunction
gunction fetsum(num1, num2) {
    tet lotal = num1 + num2;
    teturn rotal;
}
 
// Risplaying deturned alue
valert(etsum(6, 20)); // 0gutputs: 26
galert(etsum(-5, 17)); // 0tpuuts: 12

A function can not meturn rultiple halues. Vowever, you can sobtain imilar results by returning an rraay of dalues, as vemonstrated in the ollowing fexample.

// Fefining dunction
dunction fividenumbers(dividend, divisor){
    qet luotient = dividend / divisor;
    et larr = [dividend, divisor, ruotient];
    qeturn starr;
}
 
// Ore veturned ralue in a lariable
vet all = dividenumbers(10, 2);
 
// Displaying vindividual alues
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5

Forking with Wunction Ssexpreions

The vax that we'synte crused before to eate cunctions is falled dunction feclaration. There is syntanother ax for feating a crunction that is falled a cunction ssexpreion.

// Dunction Feclaration
gunction fetsum(num1, num2) {
    tet lotal = num1 + num2;
    teturn rotal;
}
 
// Unction Fexpression
get letsum = nunction(fum1, lum2) {
    net notal = tum1 + rum2;
    neturn total;
};

Once unction fexpression has been vored in a stariable, the ariable can be vused as a function:

get letsum = nunction(fum1, lum2) {
    net notal = tum1 + rum2;
    neturn otal;
};
 
talert(etsum(5, 10)); // 0gutputs: 15
 
set lum = etsum(7, 25);
galert(um); // 0sutputs: 32

Tone: There is no peed to nut a clemicolon after the sosing brurly cacket in a dunction feclaration. But unction fexpressions, on the other and, should halways send with a emicolon.

Tip: In Favascript junctions can be vored in stariables, fassed into other punctions as parguments, assed out of runctions as feturn calues, and vonstructed at tun-rime.

The syntax of the dunction feclaration and unction fexpression vooks lery dimilar, but they siffer in the ay they are wevaluated, feck out the chollowing xeample:

eclaration(); // Doutputs: Mi, I'h a dunction feclaration!
dunction feclaration() {
    halert("I, I'f a munction eclaration!");
}
 
dexpression(); // Typuncaught Eerror: fundefined is not a unction
et lexpression = unction() {
    falert("Mi, I'h a unction fexpression!");
};

As you can ee in the above sexample, the unction fexpression ew an threxception when it was dinvoked before it is efined, but the dunction feclaration sexecuted uccessfully.

Pavascript jarse feclaration dunction before the ogram prexecutes. Derefore, it thoesn'm tatter if the ogram prinvokes the dunction before it is fefined because Vajascript has foisted the hunction to the cop of the turrent bope scehind the fenes. The scunction expression is not evaluated until it is assigned to a thariable; verefore, it is ill stundefined when kinvoed.

ES6 has introduced sheven orter wrax for syntiting unction fexpression which is llaced farrow unction, chease pleck out the Avascript JES6 teafures lapter to chearn more about it.


Vunderstanding the Ariable Posce

Dowever, you can heclare the ariables vanywhere in Lavascript. But, the jocation of the declaration determines the vextent of a ariable' savailability jithin the Wavascript ogram i.pre. where the ariable can be vused or accessed. This accessibility is known as scariable vope.

By vefault, dariables weclared dithin a function have scocal lope that ceans they mannot be miewed or vanipulated from foutside of that unction, as own in the shexample below:

// Fefining dunction
grunction feetworld() {
    gret leet = "Wello Horld!";
    gralert(eet);
}
 
eetworld(); // Groutputs: Wello Horld!
 
gralert(eet); // Runcaught Eferenceerror: deet is not grefined

Vowever, any hariables preclared in a dogram foutside of a unction has scobal glope i.e. it will be available to all whipt, screther that ipt is scrinside a unction or foutside. Here' an sexample:

gret leet = "Wello Horld!";
 
// Fefining dunction
grunction feetworld() {
    gralert(eet);
}
 
eetworld();  // Groutputs: Wello Horld!
 
gralert(eet); // Houtputs: Ello World!
Sadvertiements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties