xxxxxxxxxx
//* main difference is arrow functions do not have their own this
let user = {
name: "HEllo world",
functTest() {
console.log("----functTest---", this.name) // HEllo world
},
arrowTest: () => {
console.log("----arrowTest----", this.name) // undefined
}
}
user.functTest()
user.arrowTest()
xxxxxxxxxx
There are a few differences between regular functions and arrow functions in JavaScript:
1. Syntax: Arrow functions have a shorter syntax compared to regular functions. Arrow functions do not have the function keyword, and the return keyword is optional if the function body is a single expression.
// Regular function
function sum(a, b) {
return a + b;
}
// Arrow function
const sum = (a, b) => a + b;
2. this keyword: The value of the this keyword inside a regular function is determined by how the function is called. In an arrow function, the value of this is inherited from the surrounding context.
const obj = {
name: 'John',
regularGreet: function() {
console.log(`Hello, my name is ${this.name}`);
},
arrowGreet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
obj.regularGreet(); // "Hello, my name is John"
obj.arrowGreet(); // "Hello, my name is undefined"
3. arguments object: The arguments object is an array-like object that is available inside functions. It can be used to access the arguments passed to the function. Arrow functions do not have their own arguments object. Instead, they can use the rest parameter syntax ( ) to access the arguments passed to the function.
function sum() {
console.log(arguments);
}
const sum = () => {
console.log(arguments); // Uncaught ReferenceError: arguments is not defined
}
const sum = (args) => {
console.log(args);
}
4.new operator: Regular functions can be called with the new operator to create an instance of an object. Arrow functions cannot be used as constructors and cannot be called with the new operator.
function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(person.name); // "John"
const Person = (name) => {
this.name = name;
}
const person = new Person('John'); // Uncaught TypeError: Person is not a constructor
In this example, we have an object with a greet method that uses an arrow function inside a setTimeout call. The arrow function has access to the enclosing scope’s this value, which is the object itself. If we had used a regular function instead of an arrow function, this would have referred to the enclosing scope instead of the object.
xxxxxxxxxx
const obj = {
name: 'John',
age: 30,
greet() {
setTimeout(() => {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}, 1000);
}
};
obj.greet(); // Hello, my name is John and I'm 30 years old.
xxxxxxxxxx
var name = "Suprabha"
let newObject = {
name : "supi",
arrowFunc: () => {
console.log(this.name);
},
regularFunc() {
console.log(this.name);
}
}
newObject.arrowFunc(); // undefined
newObject.regularFunc(); // supi