,

JavaScript Tutorial – Arrow Function in JavaScript

Learn how to write shorter codes in JavaScript with the help of the arrow function.

Today, I’ll show you how to write shorter code using JavaScript Arrow functions. Arrow functions are a concise way to define functions in JavaScript, making your code more streamlined.

Let’s start with a simple example. I’ll create an HTML page that prints “Hello World.” First, in the HTML body, I’ll use a

tag with an ID of “demo.” Then, in the script section, I’ll define a function named “hello” that returns the string “Hello World.”

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrow Function Demo</title>
</head>
<body>
<p id="demo"></p>

<script>
let hello = () => "Hello World";
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>

In this example, I’ve used an Arrow function (=>) to define the “hello” function in a single line. It returns the string “Hello World.” The code is concise and achieves the same output.

Now, let’s take it a step further. Suppose you want to multiply two numbers. I’ll define a function called “multiply” using Arrow function syntax.

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrow Function Demo</title>
</head>
<body>
<p id="demo"></p>

<script>
let multiply = (a, b) => a * b;
document.getElementById("demo").innerHTML = multiply(4, 5);
</script>
</body>
</html>

Here, the “multiply” function takes two parameters (a and b) and uses the Arrow function to return their product. The result is then displayed in the HTML.

Additionally, I’ve demonstrated using an Arrow function with parameters to dynamically create a greeting. The “hello” function now takes a parameter “val,” allowing you to customize the greeting.

Feel free to explore Arrow functions for various scenarios where concise and expressive code is beneficial. Keep in mind that Arrow functions are best suited for simpler, one-liner functions.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>