DONATE  
MENU
JAVASCRIPT
AJAX
HTML
JSON
CSS
MYSQL
PHP

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Functions » Arrow Functions
Share Tweet WhatsApp

Arrow Functions

Arrow functions are short alternative methods or ways of defining JavaScript traditional functions. They were introduced in ECMAScript6 (ES6) to make defining functions easier and shorter. Nevertheless, this means they are not supported in browsers running anything less than ES6. Syntax The basic syntax for arrow functions is outlined below,
  1. The first step involves specifying the name of the function and an assignment operator (=). You will do this if the function is not suppose to be an anonymous function.
    var myFunc = 
  2. Then, followed by the function parameters in parentheses (()). Parentheses are not necessarily needed if the function has only one parameter.
    var myFunc = () /*No Parameter Needs Parentheses*/
    var myFunc = x /*One Parameter - Parentheses Is Optional*/
    var myFunc = (x, y) /*Need Parentheses*/
  3. Then, an arrow ( => ).
     var myFunc = () =>
  4. Finally, the function body which may be a concise body (one without curly braces ({}) and contains just one statement) or a block body (one with curly braces and contain one or more statements.
    var myFunc = () => alert("Hello World");; //Concise body(No curly braces and contains one statement)
    var myFunc = () => {
    var x = 2 + 4;
    alert(x);
    }; //Block body(Curly braces with one or more statements)
This syntax is demonstrated in the following examples,
//A function with no parameters and a statement in arrow method will go thus,
var functionName = () => statement; //Syntax

var myFunc = () => 2 + 5;; //Example

//A function with one parameter and one statement in arrow method will go thus,
var functionName = parameter => statement; //Syntax

var myFunc1 = a => a + 5;; //Example

//A function with more than one parameters and one statement in arrow method will go thus,
var functionName = (parameter 1, parameter 2, parameter N) => statement; //Syntax

var myFunc2 = (a, b, c) => a + b - c;; //Example

//A function with more than one parameters and statements in arrow method will go thus,
var functionName = (parameter 1, parameter N) => {statements}; //Syntax

var myFunc = (x, y) => {
var sum = x + y;
alert(sum);
};
These syntaxes would further be broken down below. A Traditional Function Below is the traditional method of creating functions you have learnt previously,
<script>
function addSurName(name){
return name+" Ajayi";
} //Function definition

var names = addSurName("Peter"); //Invokes the function
document.write(names); //Outputting a value
</script>

Copy PRACTICE IT

Arrow Function Equivalent If we are to define the above traditional function as an arrow function, the syntax will go thus,
<script>
var addSurName = (name) => {return name+" Ajayi"; };//Function definition
//"addSurName" is the "name" of the function
//"(name)" is a "parentheses containing a parameter" for the function
//"=>" is an "arrow" - Arrow Function
//"{return name+" Ajayi"; }" is the function code block or body
//"return name+" Ajayi";" is a "statement" in the body of the function

var names = addSurName("Peter"); //Invokes the function
document.write(names); //Outputting a value
</script>
But you should remove the return keyword and can also remove the curly braces ({}) if the body of the function contains just one statement just as in the above. This is demonstrated below,
<script>
var addSurName = (name) => name+" Ajayi";

var names = addSurName("Peter");
document.write(names);
</script>

Copy PRACTICE IT

You can also remove the parentheses(()) if the function has just one parameter.
<script>
var eligibility = age => age+": "+(age >= 18?"Eligible":"Not Eligible");
document.write(eligibility(16)+"<br/>");
document.write(eligibility(19)+"<br/>");
</script>

Copy PRACTICE IT

You would need to bring back parentheses (()) if the parameters are two or more. Also, if the function has no parameters.
<script>
var addTwo = (a, b) => alert(a+b);;

addTwo(2,4);
</script>

Copy PRACTICE IT

<script>
var myFunc = () => alert("Hello World");; //No parameters

myFunc();
</script>

Copy PRACTICE IT

You would also need to use curly braces if the function statements are more than one.
<script>
var addTwo = (a, b) => {
var sum = a + b; //1st statement
alert(sum); //2nd statement
};

addTwo(50, 45);
</script>

Copy PRACTICE IT

Lastly, you would need to use the return keyword if the statements are more than one and you desire to return a value. Remember the return keyword is used when a function should return a value.
<script>
var percentOf = (val, percent) => {
var percentValue = (percent/100) * val; //1st statement
return percentValue; //2nd statement
};

alert("25 percent(%) of 10000 is "+percentOf(10000, 25));
</script>

Copy PRACTICE IT

Default Parameters' Values Below is how to specify default values for parameters in arrow functions. Remember, default parameters' values are values a function expecting a parameter(s) can use when no argument(s) is assigned to the parameter during invocation.
<script>
var func = (x = 1, y = 2) => x + y;; //default value for x is 1 and y is 2
alert(func());
alert(func(10, 15));
</script>

Copy PRACTICE IT

Returning An Object Literal In Arrow Functions To return object literals or literal objects in an arrow function with only one statement requires you enclose such an object in parentheses (()). This is to prevent the object curly braces from being interpreted as the code block of the function.
<script>
var myFunc = (a, b) => ({"a": a, "b": b, "sum": a + b});;
//The literal object is {"a": a, "b": b, "sum": a + b}
alert(myFunc(23, 24));
</script>

Copy PRACTICE IT

Implicit And Explicit Return Statements Most of the time, your arrow functions will be defined to return values. Values can either be returned implicitly or explicitly. Implicit Return When an arrow function contains one statement and that statement is a standalone value e.g 5 or that statement is an expression that will result to a value e.g 3 + 5, by implication, the value will be returned and that is an implicit return or implied return.
<script>
var myFunc = () => 3 + 5;; //8 will be return from the function by implication because the function contains one statement and that statement is a value (8) that will result from an expression 3 + 5
alert(myFunc()); //8
</script>

Copy PRACTICE IT

But the below example won't return any value implicitly because the statement does not result to a value rather a value from an expression is basically being assigned to a variable.
<script>
var myFunc = () => var x = 3 + 5;;
alert(myFunc()); //undefined
</script>

Copy PRACTICE IT

Explicit Return When an arrow function contains more than one statement and there is a need to return a value, you need to explicitly return that value by using the return keyword as the function won't be able to guess what value to return. That is explicit return or express return.
<script>
var percentOf = (val, percent) => {
var percentValue = (percent/100) * val; //1st statement
return percentValue; //2nd statement
};

alert("25 percent(%) of 10000 is "+percentOf(10000, 25));
</script>

Copy PRACTICE IT

Problems Of Arrow Functions
  • Unlike traditional functions, arrow functions do not have arguments object.
  • It is difficult and confusing to use arrow functions in defining object methods.
  • Arrow functions cannot be used in defining prototypes and as such can not serve as constructor functions.
  • Since arrow functions cannot be used in defining constructors, using the new keyword with them will result in an error.
  • The this keyword of arrow functions behaves differently from those of traditional functions. For traditional function, the this keyword will return an object of the element invoking the function which may be the window, document, a button, a paragraph, input field and etcetera while that of arrow functions will be the object that defined the function usually the window object. Analyze the example below,
    <h1>TRADITIONAL FUNCTIONS THIS</h1>
    <p><button id='btn'>Click Me</button></p>
    <p><input type='text' id='text'/></p>
    <script>
    function myFunc(){
    alert(this);
    }
    
    var btn = document.getElementById("btn");
    var text = document.getElementById("text");
    btn.addEventListener("click", myFunc);
    text.addEventListener("keyup", myFunc);
    </script>
    <h1>ARROW FUNCTIONS THIS</h1>
    <p><button id='btn1'>Click Me</button></p>
    <p><input type='text' id='text1'/></p>
    <script>
    var myFunc1 = () => alert(this);;
    
    var btn1 = document.getElementById("btn1");
    var text1 = document.getElementById("text1");
    btn1.addEventListener("click", myFunc1);
    text1.addEventListener("keyup", myFunc1);
    </script>

    Copy PRACTICE IT

SUMMARY
  • Arrow functions are short alternative methods or ways of defining JavaScript traditional functions.
  • They were introduced in ECMAScript6 (ES6). This means some browsers running on older versions of JavaScript may not support them.
  • The syntax for creating an arrow function involves specifying the name of the function and an assignment operator (=). You will do this if the function is not suppose to be an anonymous function.
    var myFunc = 
  • Then, followed by the function parameters in parentheses (()). Parentheses are not necessarily needed if the function has only one parameter.
    var myFunc = () /*No Parameter Needs Parentheses*/
    var myFunc = x /*One Parameter - Parentheses Is Optional*/
    var myFunc = (x, y) /*Need Parentheses*/
  • Then, an arrow ( => ).
     var myFunc = () =>
  • Finally, the function body which may be a concise body (one without curly braces ({}) and contains just one statement) or a block body (one with curly braces and contain one or more statements.
    var myFunc = () => alert("Hello World");; //Concise body(No curly braces and contains one statement)
    var myFunc = () => {
    var x = 2 + 4;
    alert(x);
    }; //Block body(Curly braces with one or more statements)
  • If we want our arrow function(s) to return a value, this can be done either implicitly or explicitly.
  • A value is returned implicitly when an arrow function contains just one statement and that statement is a value or an expression which will give birth to a value.
    var myFunc = () => 10;; //10 will be return impliedly
    var myFunc1 = () => 10 > 8;; //10 > 8 is an expression that will result to true. true will be returned implicitly
  • A value is returned explicitly when an arrow function contains two or more statements and a value is returned using the return keyword.
    var myFunc = () => {
    var x = 2 + 4;
    return x;
    };//6 will be returned explicitly
Take a short quiz on Arrow Functions.
Ask a question or tell us if Arrow Functions is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode