Thursday, December 21, 2023

Day 16 || Arrow function in JavaScript

 JavaScript Topics

Day 16:

  • Arrow Function

ArrowFunction:

// 1. Syntax

function traditionalFunction(x, y) {
  return x + y;
}
// console.log(traditionalFunction(2, 3));

let arrowFunction = (x, y) => {
  return x + y;
};

// console.log(arrowFunction(2,3))

// 2. this binding

let user = {
  name: "Hema",
  sayNamaste: function () {
    console.log("Namaste " + this.name);
  },

  sayHello: () => {
    console.log("Hello " + this.name);
  },
};

// user.sayNamaste()
// user.sayHello()

// 3. Arguments Object
function printArguments() {
  for (i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}
// printArguments(1, 2, 3, 4, 5);

let printArgumentsA = (...arguments) => {
  for (i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
};

// printArgumentsA(1, 2, 3, 4, 5);

// 4. Return

function multiply(x,y){
    return x*y;
}
console.log(multiply(2,3))

let multiplyA =(x,y)=> x * y;
console.log(multiplyA(4,5))


Task:

Task 1: Arrow Function with Parameters

Write an arrow function called calculateArea that takes the radius of a circle as a parameter and returns the area of the circle. Use the formula: Area=×radius2. Assume that π (pi) is approximately 3.14.

Task 2: Arrow Function with a Default Parameter

Write an arrow function called power that takes two parameters: a base (x) and an exponent (y). If no exponent is provided, default it to 2. The function should return the result of raising the base to the exponent.

Interview Questions:

1. How do arrow functions differ from regular functions in terms of syntax and behavior?

2. Explain the concept of lexical scoping and how it applies to arrow functions.

3. What is the main advantage of using arrow functions over traditional functions?


No comments:

Post a Comment

Top 10 | JavaScript Coding Interview Question | Beginner Level

               JavaScript Coding Interview  Q. No. 01/10:  console . log ( "1" + "4" + "1" ) // 141 console . ...