Engineering note · Node.js

Arrow Functions

Arrow functions in Node.js are a concise way to write functions. They are great for short, single-expression functions and have unique behaviors like lexical this binding. However, they lack their own this, arguments object, and can't be used as constructors with new.

By Published

Node.js

1. Basic Syntax

CODE SAMPLE Code snippet
const add = (a, b) => a + b;

2. Single Parameter

CODE SAMPLE Code snippet
const greet = name => `Hello, ${name}`;

No need for parentheses if there’s only one parameter.

3. No Parameters

CODE SAMPLE Code snippet
const sayHello = () => 'Hello!';

Use empty parentheses when there are no parameters.

4. Implicit Return

CODE SAMPLE Code snippet
const double = x => x * 2;

No need for return or curly braces for single expression functions.

5. Block Body

CODE SAMPLE Code snippet
const sum = (a, b) => {
    const result = a + b;
    return result;
};

Use curly braces when you need multiple statements.

6. Lexical this

CODE SAMPLE Code snippet
const obj = {
    name: 'Node.js',
    getName: () => this.name
};
console.log(obj.getName()); // Outputs: undefined (depends on surrounding scope)

Arrow functions don’t have their own this; they inherit this from the surrounding context.

7. No arguments Object

CODE SAMPLE Code snippet
const add = () => {
    console.log(arguments); // `arguments` is not defined
};

Arrow functions don’t have their own arguments object.

8. No new Keyword

CODE SAMPLE Code snippet
const Person = (name) => {
    this.name = name;
};
const john = new Person('John'); // Error: Person is not a constructor

Arrow functions can’t be used as constructors.

9. No Prototype

CODE SAMPLE Code snippet
const ArrowFunc = () => {};
console.log(ArrowFunc.prototype); // Outputs: undefined

Arrow functions don’t have a prototype property, so they can’t be used to define methods on a prototype.

10. Arrow Functions in Callbacks

CODE SAMPLE Code snippet
setTimeout(() => console.log('Executed after 1 second'), 1000);

Often used in callbacks for their concise syntax and lexical this binding, especially in asynchronous operations.

11. Empty Arrow Function

CODE SAMPLE Code snippet
// An empty arrow function returns undefined
const empty = () => {};

(() => "foobar")();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)

12. Promise

CODE SAMPLE Code snippet
promise
  .then((a) => {
    // …
  })
  .then((b) => {
    // …
  });

More engineering notes

Toggle Classes Based on Conditions

Use classList.toggle to add or remove classes based on a condition. ``` const button = document.get...

Scope

Scope in Node.js defines where variables and functions can be accessed in your code. It includes glo...