Difference between Regular functions and Arrow functions
Last Updated :
11 Sep, 2024
Regular functions and arrow functions are two common ways to define functions in JavaScript, each with distinct behaviors. Regular functions offer traditional syntax and this context handling, while arrow functions provide a concise syntax and lexical this binding, making them ideal for callbacks and simpler expressions.
Regular function
Regular functions in JavaScript are defined using the function keyword and can be named or anonymous. They have their own this context, which varies depending on how they’re called, and they also have access to the arguments object for handling passed parameters.
Syntax
let x = function function_name(parameters){
// body of the function
};
Example: In this example, the regular function greet is defined using the function keyword. It takes a parameter name and logs a greeting message to the console when called.
JavaScript
// Defining a regular function
function greet(name) {
console.log('Hello, ' + name + '!');
}
// Calling the function
greet('Geek');
1. Access arguments with Regular functions
In regular functions, you can access all passed arguments using the arguments object, which is an array-like object containing each argument passed to the function.
Example: Regular functions use the arguments object to access all passed arguments, like an array.
JavaScript
function showArgs() {
console.log(arguments);
}
showArgs(1, 2, 3);
Output[Arguments] { '0': 1, '1': 2, '2': 3 }
2. Duplicate named parameters in Regular functions
In regular functions, duplicate named parameters are allowed but not recommended. The last occurrence of the parameter overwrites previous ones, and only its value is used.
Example: The function allows duplicate parameters in non-strict mode; the last a overwrites the first
JavaScript
function example(a, b, a) {
console.log(a, b);
}
example(1, 2, 3);
3. Hosting in Regular functions
In regular functions, function declarations are hoisted to the top of their scope, allowing them to be called before they’re defined in the code.
Example: The function greet is hoisted, allowing it to be called before its declaration.
JavaScript
greet(); // Output: Hello Geeks!
function greet() {
console.log('Hello Geeks!');
}
4. Using this keyword in Regular function
In regular functions, this refers to the object that calls the function (runtime binding). Its value can vary based on how the function is called (method, event, or global).
Example: In this regular function, this refers to the calling object obj. Output will be the name property.
JavaScript
const obj = {
name: 'Geeks',
greet: function() {
console.log(this.name);
}
};
obj.greet();
5. Using new keyword in Regular function
Regular functions can be used as constructors with the new keyword, allowing the creation of new object instances. The new keyword sets this to the new object inside the function.
Example: The Person function is used as a constructor with new, creating a new object p with name set to Geeks.
JavaScript
function Person(name) {
this.name = name;
}
const p = new Person('Geeks'); // Creates a new Person object
console.log(p.name);
Arrow function
Arrow functions in JavaScript are a concise way to define functions using the => syntax. They do not have their own this context, instead inheriting it from the surrounding scope. Arrow functions also lack their own arguments object and are ideal for shorter functions and callbacks.
Syntax
let x = (parameters) => {
// body of the function
};
Example: In this example, the arrow function greet is defined using the => syntax. It takes a parameter name and logs a greeting message to the console when called.
javascript
// Defining an arrow function
const greet = (name) => {
console.log(`Hello, ${name}!`);
};
// Calling the function
greet('Geeks');
1. Access arguments with Arrow functions
Arrow functions do not have their own arguments object. To access arguments in arrow functions, use rest parameters (…args) to collect all arguments into an array.
Example: The arrow function showArgs uses rest parameters (…args) to capture all arguments into an array.
JavaScript
const showArgs = (...args) => {
console.log(args);
};
showArgs(1, 2, 3);
2. Duplicate named parameters in Arrow functions
Arrow functions do not allow duplicate named parameters, even in non-strict mode, and will throw a syntax error if duplicates are present. Always use unique parameter names in arrow functions.
Example: Arrow functions don’t allow duplicate parameter names, even in non-strict mode. The code will throw a SyntaxError for duplicate parameters.
JavaScript
const example = (a, b, a) => {
console.log(a);
};
// SyntaxError: Duplicate parameter name not allowed in this context
Output:
SyntaxError: Duplicate parameter name not allowed in this context
3. Hoisting in Arrow functions
Arrow functions are not hoisted like regular function declarations. They are treated as variables, so they cannot be called before being defined due to the temporal dead zone.
Example: Arrow functions are not hoisted like regular functions. Calling greet before its declaration results in a ReferenceError due to the temporal dead zone.
JavaScript
greet(); // ReferenceError: Cannot access 'greet' before initialization
const greet = () => {
console.log('Hello!');
};
Output:
ReferenceError: Cannot access 'greet' before initialization
4. Using this keyword with Arrow function
In arrow functions, this is lexically inherited from the surrounding scope, not the function itself. It maintains the this value from where the arrow function is defined.
Example: Arrow functions inherit this from the outer scope, not the object itself, causing this.name to be undefined.
JavaScript
const obj = {
name: 'Geeks',
greet: () => {
console.log(this.name);
}
};
obj.greet(); // Output: undefined (inherited from outer scope)
5. Using new keyword in Arrow function
Arrow functions cannot be used as constructors and do not support the new keyword. Attempting to use new with an arrow function will result in a TypeError.
Example: Arrow functions cannot be used as constructors with new. Attempting to create an instance results in a TypeError.
javascript
const Person = () => {};
const p = new Person(); // TypeError: Person is not a constructor
Output:
TypeError: Person is not a constructor
Difference table of Regular functions and Arrow functions
Feature | Regular Functions | Arrow Functions |
---|
Syntax | Defined using the function keyword. | Uses concise => syntax. |
this Binding | this depends on the calling context. | Inherits this from the surrounding scope. |
Arguments Object | Has its own arguments object. | Does not have its own arguments object. |
Constructor Usage | Can be used as a constructor with new . | Cannot be used as a constructor. |
Hoisting | Function declarations are hoisted. | Not hoisted; behaves like variables. |
Implicit Return | Requires return for returning values. | Supports implicit return for single expressions. |
Methods as Object Properties | Suitable for object methods with proper this . | Not suitable for methods due to lexical this . |
Similar Reads
Difference Between indexOf and findIndex function of array
The task is to differentiate between the indexOf() and findIndex() methods of JavaScript. we're going to discuss both approaches. JavaScript indexOf() Method: This method is used to find the index of the first occurrence of the elements provided for search as the argument to the function. Syntax: ar
2 min read
Behavior of Arrow functions and Regular Functions for this Keyword
In JavaScript, the behavior of the this keyword differs between arrow functions and regular functions. The this keyword in Arrow Functions is lexically bound, meaning it takes the value of this from the surrounding context where the function was defined, not where it's called.In Regular Functions, t
5 min read
Difference Between Function Overloading and Function Overriding in JavaScript
Function overloading and function overriding are two important concepts in object-oriented programming (OOP). Function overloading allows the creation of multiple functions with the same name but different parameters. Function overriding allows the subclass or child class to provide the specific imp
3 min read
Difference between Methods and Functions in JavaScript
Grasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Difference between Anonymous and Named functions in JavaScript
In JavaScript or in any programming language per say, functions, loops, mathematical operators and variables are the most widely used tools. This article will tell you about the difference between anonymous functions and named functions. We will discuss all the required concepts in this article to k
4 min read
Difference between lodash and Underscore
The lodash and UnderScore both are utility libraries from JavaScript which helps make it easier by providing utils which makes, working with arrays, numbers, objects, and strings much easier. They provide a group of tools used for common programming operations having a strong functional programming
3 min read
Difference between âfunction declarationâ and âfunction expression' in JavaScript
Functions in JavaScript allow us to carry out some set of actions, important decisions, or calculations and even make our website more interactive. In this article, we will learn the difference between âfunction declarationâ and âfunction expressionâ. The similarity is both use the keyword function
2 min read
What is the difference between â(â¦);â and â{â¦}â in ReactJS ?
When you write JavaScript, you can use either the "(â¦)" or "{â¦}" pattern to define objects. In ReactJS, (...); and {...} are used in different contexts and have different purposes, and are used to denote different types of code structures. What is "(â¦);" in React JS ?In ReactJS, (...); is used to de
5 min read
Understanding the Difference between Pure and Impure Functions in JavaScript
In this article, we will see the concepts of pure and impure functions in JavaScript, along with understanding their differences, & basic implementation for a better understanding of the concepts. Pure Functions: This function always returns the same output as given the same input parameters. Pu
5 min read
Difference between "var functionName = function() {}" and "function functionName() {}" in JavaScript
In this article, we will be discussing the function functionName() {} and functionName = function() {} with suitable code examples for each condition & then we will see the difference between the function functionName() {} and functionName = function() {}. function functionName() {}: A function
3 min read