Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

shaikh_md
shaikh_md

Posted on • Edited on

     

The Heart Of JavaScript #functions💙

Functions

So far we have seen many builtin JavaScript functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets understand what function is and why we need function?

A function is a reusable block of code or programming statements designed to perform a certain task.
A function is declared by a function key word followed by a name, followed by parentheses (). A parentheses can take a parameter. If a function take a parameter it will be called with argument. A function can also take a default parameter. To store a data to a function, a function has to return certain data types. To get the value we call or invoke a function.
Function makes code:

  • clean and easy to read
  • reusable
  • easy to test

A function can be declared or created in couple of ways:

  • Declaration function
  • Expression function
  • Anonymous function
  • Arrow function

Function Declaration

Let us see how to declare a function and how to call a function.

//declaring a function without a parameterfunctionfunctionName(){// code goes here}functionName();// calling function by its name and with parentheses
Enter fullscreen modeExit fullscreen mode

Function without a parameter and return

Function can be declared without a parameter.

Example:

// function without parameter,  a function which make a number squarefunctionsquare(){letnum=2;letsq=num*num;console.log(sq);}square();// 4// function without parameterfunctionaddTwoNumbers(){letnumOne=10;letnumTwo=20;letsum=numOne+numTwo;console.log(sum);}addTwoNumbers();// a function has to be called by its name to be executed
Enter fullscreen modeExit fullscreen mode
functionprintFullName(){letfirstName="md";letlastName="shaikh";letspace="";letfullName=firstName+space+lastName;console.log(fullName);}printFullName();// calling a function
Enter fullscreen modeExit fullscreen mode

Function returning value

Function can also return values, if a function does not return values the value of the function is undefined. Let us write the above functions with return. From now on, we return value to a function instead of printing it.

functionprintFullName(){letfirstName="md";letlastName="shaikh";letspace="";letfullName=firstName+space+lastName;returnfullName;}console.log(printFullName());
Enter fullscreen modeExit fullscreen mode
functionaddTwoNumbers(){letnumOne=2;letnumTwo=3;lettotal=numOne+numTwo;returntotal;}console.log(addTwoNumbers());
Enter fullscreen modeExit fullscreen mode

Function with a parameter

In a function we can pass different data types(number, string, boolean, object, function) as a parameter.

// function with one parameterfunctionfunctionName(parm1){//code goes her}functionName(parm1);// during calling or invoking one argument neededfunctionareaOfCircle(r){letarea=Math.PI*r*r;returnarea;}console.log(areaOfCircle(10));// should be called with one argumentfunctionsquare(number){returnnumber*number;}console.log(square(10));
Enter fullscreen modeExit fullscreen mode

Function with two parameters

// function with two parametersfunctionfunctionName(parm1,parm2){//code goes her}functionName(parm1,parm2);// during calling or invoking two arguments needed// Function without parameter doesn't take input, so lets make a function with parametersfunctionsumTwoNumbers(numOne,numTwo){letsum=numOne+numTwo;console.log(sum);}sumTwoNumbers(10,20);// calling functions// If a function doesn't return it doesn't store data, so it should returnfunctionsumTwoNumbers(numOne,numTwo){letsum=numOne+numTwo;returnsum;}console.log(sumTwoNumbers(10,20));functionprintFullName(firstName,lastName){return`${firstName}${lastName}`;}console.log(printFullName("md","$haikh"));
Enter fullscreen modeExit fullscreen mode

Function with many parameters

// function with multiple parametersfunctionfunctionName(parm1,parm2,parm3,...){//code goes here}functionName(parm1,parm2,parm3,...)// during calling or invoking three arguments needed// this function takes array as a parameter and sum up the numbers in the arrayfunctionsumArrayValues(arr){letsum=0;for(leti=0;i<arr.length;i++){sum=sum+arr[i];}returnsum;}constnumbers=[1,2,3,4,5];//calling a functionconsole.log(sumArrayValues(numbers));constareaOfCircle=(radius)=>{letarea=Math.PI*radius*radius;returnarea;}console.log(areaOfCircle(10))
Enter fullscreen modeExit fullscreen mode

Function with unlimited number of parameters

Sometimes we do not know how many arguments the user going to pass. Therefore, we should know how to write a function which can take unlimited number of arguments. The way we do it has a significant difference between a function declaration(regular function) and arrow function. Let us see examples both in function declaration and arrow function.

Unlimited number of parameters in regular function

A function declaration provides a function scoped arguments array like object. Any thing we passed as argument in the function can be accessed from arguments object inside the functions. Let us see an example

// Let us access the arguments objectfunctionsumAllNums(){console.log(arguments)}sumAllNums(1,2,3,4)// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
Enter fullscreen modeExit fullscreen mode
// function declarationfunctionsumAllNums(){letsum=0for(leti=0;i<arguments.length;i++){sum+=arguments[i]}returnsum}console.log(sumAllNums(1,2,3,4))// 10console.log(sumAllNums(10,20,13,40,10))// 93console.log(sumAllNums(15,20,30,25,10,33,40))// 173
Enter fullscreen modeExit fullscreen mode

Unlimited number of parameters in arrow function

Arrow function does not have the function scoped arguments object. To implement a function which takes unlimited number of arguments in an arrow function we use spread operator followed by any parameter name. Any thing we passed as argument in the function can be accessed as array in the arrow function. Let us see an example

// Let us access the arguments objectconstsumAllNums=(...args)=>{// console.log(arguments), arguments object not found in arrow function// instead we use a parameter followed by spread operator (...)console.log(args)}sumAllNums(1,2,3,4)// [1, 2, 3, 4]
Enter fullscreen modeExit fullscreen mode
// function declarationconstsumAllNums=(...args)=>{letsum=0for(constelementofargs){sum+=element}returnsum}console.log(sumAllNums(1,2,3,4))// 10console.log(sumAllNums(10,20,13,40,10))// 93console.log(sumAllNums(15,20,30,25,10,33,40))// 173
Enter fullscreen modeExit fullscreen mode

Anonymous Function

An anonymous function is a function without a name - here
Anonymous function or without name

(function(){//... statement block});function(){console.log("I am an anonymous function");};
Enter fullscreen modeExit fullscreen mode

An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable.

For example, the following shows an anonymous function that displays a message:

letshow=function(){console.log('Anonymous function');};show();
Enter fullscreen modeExit fullscreen mode

Code language: JavaScript (javascript anonymous function assignment to a Variable)
In this example, the anonymous function has no name between the function keyword and parentheses ().

Because we need to call the anonymous function later, we assign the anonymous function to the show variable.

Since the whole assignment of the anonymous function to the show variable makes a valid expression, you don’t need to wrap the anonymous function inside the parentheses ().

Expression Function

Expression functions are anonymous functions. After we create a function without a name and we assign it to a variable. To return a value from the function we should call the variable. Look at the example below.

// Function expressionconstsquare=function(n){returnn*n;};console.log(square(2));// -> 4
Enter fullscreen modeExit fullscreen mode

Self Invoking Functions

Self invoking functions are anonymous functions which do not need to be called to return a value.

(function(n){console.log(n*n);})(2);// 4, but instead of just printing if we want to return and store the data, we do as shown belowletsquaredNum=(function(n){returnn*n;})(10);console.log(squaredNum);
Enter fullscreen modeExit fullscreen mode

Arrow Function

Arrow function is an alternative to write a function, however function declaration and arrow function have some minor differences.

Arrow function uses arrow instead of the keywordfunction to declare a function. Let us see both function declaration and arrow function.

// This is how we write normal or declaration function// Let us change this declaration function to an arrow functionfunctionsquare(n){returnn*n;}console.log(square(2));// 4constsquare=(n)=>{returnn*n;};console.log(square(2));// -> 4// if we have only one line in the code block, it can be written as follows, explicit returnconstsquare=(n)=>n*n;// -> 4
Enter fullscreen modeExit fullscreen mode
constchangeToUpperCase=(arr)=>{constnewArr=[];for(constelementofarr){newArr.push(element.toUpperCase());}returnnewArr;};constcountries=["Finland","Sweden","Norway","Denmark","Iceland"];console.log(changeToUpperCase(countries));// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
Enter fullscreen modeExit fullscreen mode
constprintFullName=(firstName,lastName)=>{return`${firstName}${lastName}`;};console.log(printFullName("shaikhmd","Yetayeh"));
Enter fullscreen modeExit fullscreen mode

The above function has only the return statement, therefore, we can explicitly return it as follows.

constprintFullName=(firstName,lastName)=>`${firstName}${lastName}`;console.log(printFullName("shaikhmd","Yetayeh"));
Enter fullscreen modeExit fullscreen mode

Function with default parameters

Sometimes we pass default values to parameters, when we invoke the function if we do not pass an argument the default value will be used. Both function declaration and arrow function can have a default value or values.

// syntax// Declaring a functionfunctionfunctionName(param=value){//codes}// Calling functionfunctionName();functionName(arg);
Enter fullscreen modeExit fullscreen mode

Example:

functiongreetings(name="shaikh"){letmessage=`${name}, Love JavaScript!`;returnmessage;}console.log(greetings());console.log(greetings("shaikhmd"));
Enter fullscreen modeExit fullscreen mode
functiongenerateFullName(firstName="shaikhmd",lastName="Yetayeh"){letspace="";letfullName=firstName+space+lastName;returnfullName;}console.log(generateFullName());console.log(generateFullName("David","Smith"));
Enter fullscreen modeExit fullscreen mode
functioncalculateAge(birthYear,currentYear=2019){letage=currentYear-birthYear;returnage;}console.log("Age:",calculateAge(1819));
Enter fullscreen modeExit fullscreen mode
functionweightOfObject(mass,gravity=9.81){letweight=mass*gravity+" N";// the value has to be changed to string firstreturnweight;}console.log("Weight of an object in Newton:",weightOfObject(100));// 9.81 gravity at the surface of Earthconsole.log("Weight of an object in Newton:",weightOfObject(100,1.62));// gravity at surface of Moon
Enter fullscreen modeExit fullscreen mode

Let us see how we write the above functions with arrow functions

// syntax// Declaring a functionconstfunctionName=(param=value)=>{//codes};// Calling functionfunctionName();functionName(arg);
Enter fullscreen modeExit fullscreen mode

Example:

constgreetings=(name="shaikh")=>{letmessage=name+" Love JavaScript!";returnmessage;};console.log(greetings());console.log(greetings("shaikhmd"));
Enter fullscreen modeExit fullscreen mode
constgenerateFullName=(firstName="md",lastName="shaikh")=>{letspace="";letfullName=firstName+space+lastName;returnfullName;};console.log(generateFullName());console.log(generateFullName("David","Smith"));
Enter fullscreen modeExit fullscreen mode
constcalculateAge=(birthYear,currentYear=2019)=>currentYear-birthYear;console.log("Age:",calculateAge(1819));
Enter fullscreen modeExit fullscreen mode
constweightOfObject=(mass,gravity=9.81)=>mass*gravity+" N";console.log("Weight of an object in Newton:",weightOfObject(100));// 9.81 gravity at the surface of Earthconsole.log("Weight of an object in Newton:",weightOfObject(100,1.62));// gravity at surface of Moon
Enter fullscreen modeExit fullscreen mode

🌕Now you knew function . Now, you are super charged with the power of functions.

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jonrandy profile image
Jon Randy 🎖️
🤖 Artisanal developer - coding with varying degrees of success since 1983
  • Location
    Bangkok 🇹🇭
  • Joined
• Edited on• Edited

Your functionanonymousFun is not anonymous. It has a name. You can check this withanonymousFun.name. The act of assigning an anonymous function to a variable (in most cases) gives it a name, making it cease to be anonymous.

Similarly, yoursquare function also has a name - 'square'.

Also, I'm not sure what you mean by 'expression function'. Presumably you are talking about function expressions? All these are are expressions whose value is a function. This function may or may not have a name - that is irrelevant.

CollapseExpand
 
shaikhmd007 profile image
shaikh_md
Upgrading...
  • Location
    Mumbai - MH- India
  • Joined

Sure, will check 👍🏻

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Upgrading...
  • Location
    Mumbai - MH- India
  • Joined

More fromshaikh_md

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp