Javascript Arrow function

OVERVIEW

The arrow function acts somewhat like the lamdba expression in Java. It allows you to define functions in a shorthand syntax. The sample code below shows how it can be used with and without parameters.

The this keyword within an arrow function always points to the calling object, which is the window by default. If an arrow function is defined within a function then this points to the function.

SAMPLE CODE

<html>
	<head><title>Arrow Function</title>
	
	<script>
		function standard() {
		   return "standard";
		}

		let func = () => {return "arrow";}

		document.write(standard() + "<br>");
		document.write(func() + "<br>");

		let funcWithParams = (a,b) => {
			let c = a+b;
			return c;
		}
		document.write(funcWithParams(12,67) + "<br>");

		let funcThis = () => {
			alert(this);
		}


	</script>
	</head>

	<body>
	    <button onclick="funcThis();" id="btn" type="button">Click Me</button>

	</body>
</html>

The output is shown below

standard
 arrow
 79

Be the first to comment

Leave a Reply

Your email address will not be published.


*