×

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be easier to read and more organised using arrow functions.

They are unidentified functions, arrow functions (the functions without a name and not bound with an identifier). They can declare without the function keyword because they don't return any value. It is not possible to utilise arrow functions as constructors. The context is either lexically or statically specified within the arrow functions. They go by the name Lambda Functions in many linguistic contexts.

Arrow functions are not compatible with the new keyword since they lack a prototype attribute.

The syntax for defining the arrow function

const functionName = (arg1, arg2, ?..) => {  
    //The main body of the function  
}

An Arrow Function or Lambda Function is composed of three parts:

Parameters: The arguments may be an optional part of any function.

Fat arrow notation/lambda notation: It is used to represent the arrow (=>).

Statements: The function's instruction set is represented by it.

Let's use an illustration to try to understand it.

We are defining three functions in the example below that display Function Expression, Anonymous Function, and Arrow Function.

Program

// expression of a function  
var myop1 = function show() {  
 console.log("expression of a function");     
}    
// Anonymous operation 
var myop2 = function () {  
    console.log("It is an Anonymous operation");     
   }     
//Arrow operator 
var myop3 = () => {  
    console.log("It is an Arrow operator");     
   };  
myop1();  
myop2();  
myop3();  

Output

Arrow operator in Java

Syntactic Variations

The following are some syntactic modifications for the arrow functions:

Optional parentheses for the single parameter

Program

var num = a => {  
    console.log(a);  
}  
num(115);  

Output

Arrow operator in Java

Braces are optional for single statements, and they are left empty if no parameters are needed.

Program

var show = () => console.log("Java Program");  
show();  

Output:

Arrow operator in Java

Arrow Function with Parameters

When utilising an arrow function, you must supply parameters inside parentheses if you need to pass more than one.

Program

var show = (u,v,w) => {  
    console.log(u + " " + v + " " + w );  
}  
show(124,256,524);  

Output:

Arrow operator in Java

Arrow operator with default arguments

In ES6, if no value is supplied to the function or the value is undefined, the arguments may be initialised with default values. The following code provides an illustration for the same:

Program

var show = (u, v=456) => {
    console.log(u + " " + v);
}
show(126);

The value of v in the preceding function is set to 456 by default. If no value for v is explicitly supplied, 456 will always be assumed by the function.

Output

Arrow operator in Java

If the function passes the parameter's value manually, the default value of "v" will be replaced. It is demonstrated in the following example:

Program

var show = (u, v=456) => {  
    console.log(u + " " + v);  
}  
show(126,549);  

Output

Arrow operator in Java

Arrow function with Rest parameters

The number of values you can provide into a function is not limited by rest parameters, but they all need to be of the same type. Another way to put it is that rest parameters function as hold for numerous arguments of the same type.

The spread operator with three periods should be preceded with the parameter name when expressing the remainder parameter (not more than three or not less than three).

The illustration for the same may be seen in the example below:

Program

var show = (u, ...args) => {  
    console.log(u + " " + args);  
}  
show(111,222,333,444,555,666,777,888);  

Output:

Arrow operator in Java

Arrow Function without Parentheses

Parentheses are not required if you just have one parameter to pass.

Program

var show = u => {  
    console.log(u);  
}  
show("Java Program");   

Output:

Arrow operator in Java

Advantages of Arrow Functions

The following are some benefits of utilising arrow functions:

1.It reduces the code size: The size of the code is decreased when the arrow function syntax is used. Using the arrow function allows us to write less code.

2.Return statement and Functional braces are optional for single line functions: In ES5, the return statement in the functions must be defined, however in ES6, the return statement is not necessary for single-line functions. For the single-line functions, functional brackets are likewise not required.

Syntax in ES5

function show(num){  
return num/2;  
}  

Syntax in ES6

var show = num => num/2;  
console.log(show(112));  

Program without Return Keyword

var show = num => {  
    num/2;  
}  
console.log(show(48));  

Output:

Arrow operator in Java

Program with Return Keyword

var show = value => {  
   return value/2;  
}  
console.log(show(48));  

Output:

Arrow operator in Java

3.Lexically bind the context: The arrow function lexically or statically binds the context. In contrast to conventional functions, arrow functions handle this differently. There is no binding for this in the arrow function. This term is used to identify the objects that called a regular function, which may be anything from a window to a button to a document.

In contrast, this term always refers to the object that specifies the arrow function in the case of arrow functions.

Let's use the following bit of code to try and understand it:

Program

If the array of numbers in a class contains a value lower than 30, we shall put the value into the child queue.

The following may be accomplished in ES5:

this.num.forEach(function(num) {   
    if (num < 30)   
        this.child.push(num);   
}.bind(this));  

Use the arrow function in ES6 to do this.

this.num.forEach((num) => {   
    if (num < 30)   
        this.child.push(num);   
});  

Therefore, utilising the arrow function eliminates the need for implicit binding because it executes automatically.

As we've seen, the arrow function decreases the amount of lines while also simplifying the drafting of functions.


Related Topics

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.