Syntax error Explain shorthand functions in JavaScript?

Explain shorthand functions in JavaScript?



The arrow functions also known as shorthand functions were introduced in ES2015 and allows us to write function in a shorter way. They don’t have their own binding to this and get the this from the surrounding context.

Following is the code showing shorthand functions in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Shorthand function in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to invoke arrow and normal function</h3>
<script>
   let resEle = document.querySelector(".result");
   let objYear, obj1Year;
   let obj = {
      name: "rohan",
      age: 20,
      birthday() {
         function birthYear() {
            objYear = new Date().getFullYear() - this.age;
         }
         birthYear();
      },
   };
   let obj1 = {
      name: "Shawn",
      age: 22,
      birthday() {
         let birthYear = () => {
            obj1Year = new Date().getFullYear() - this.age;
         };
         birthYear();
      },
   };
   document.querySelector(".Btn").addEventListener("click", () => {
      obj.birthday();
      obj1.birthday();
      resEle.innerHTML += " Without arrow function : Birth Year = " + objYear + " ";
      resEle.innerHTML += " With arrow function : Birth Year = " + obj1Year + " ";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 2020-07-17T08:16:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements