Arrow Functions in JavaScript: A Simpler Way to Write Functions
Welcome to the JavaScript Blog Series
Arrow functions in JavaScript
As the title of the blog suggests, it is a short and easier way to write a function.
It is more related to function expression than function declaration, as covered in our previous blog.
Note: These arrow functions are called as other types are called functionName()
Arrow function syntax
There are multiple ways to write an arrow function, each have their own pros and cons.
Method 1: Explicit return and single parameter.
//If you have single parameter
const sq = (a) => {
console.log("Arrow Function with explicit return")
return a*a
}
//If you have no parameter
const hello = () => {
return "Hello"
}
//One more way to write if you have single parameter
const sqr = a => {
return a*a
}
Use this method only when you want to explicitly(manually) return something.
Method 2: Implicit Return and multiple parameters
Here is a function named add with parameters a & b
//Multiple parameter
const add = (a,b) => a + b //It will automatically return a + b
//Single parameter 'a'
const sqr = a => a*a
It will return whatever you write after an arrow. It returns implicitly (automatically, without the return keyword)
There is a case when your return is a multi-line return.
const person = (name, age) => ({
name, age})
What is this code doing?
It is returning an object with properties name and age.
Intro to Object
Objects are a key-value pair kind of data type in JavaScript. It is defined using {}
For eg:
const Ram = {
key1: value1,
key2: value2
}Just an intro to Object, we have a different blog on this.
Difference between Arrow function and normal functions
| Aspect | Arrow Functions | Normal Functions |
|---|---|---|
| Syntax | Concise (=>); implicit return for single expressions. |
More verbose; requires function keyword and explicit return. |
this Binding |
Lexically scoped; inherits this from the surrounding (parent) scope. |
Dynamically scoped; this depends on how the function is called. |
arguments Object |
Does not have its own arguments object (use rest parameters ...args instead). |
Has its own array-like arguments object. |
| Constructors | Cannot be used as constructors with the new keyword. |
Can be used as constructors to create new objects. |
| Hoisting | Not hoisted; behave like variables defined with const or let, so it cannot be accessed before the declaration. |
Function declarations are hoisted to the top of their scope, allowing them to be called before they are defined. |
| Methods | Not ideal for object methods that this should refer to the object itself. |
Suitable for object methods. |

