Function Object and Named Function Expressions (NFE) in JavaScript

Function Object and Named Function Expressions (NFE) in JavaScript

Function Object and Named Function Expressions (NFE) in JavaScript

In JavaScript, functions are objects. This means they can have properties and methods just like objects. Also, functions can be anonymous or named, which is where Named Function Expressions (NFE) come in.

Function as an Object

Since functions are objects, they can have properties and methods.

Example: Assigning Properties to a Function

function greet() { console.log("Hello!"); } greet.info = "This is a greeting function"; console.log(greet.info); // Output: "This is a greeting function"

Functions can store properties like any other object.

Example: Function Object’s name and length Properties

function sum(a, b) { return a + b; } console.log(sum.name); // Output: "sum" (function name) console.log(sum.length); // Output: 2 (number of parameters)

.name gives the function name.
.length returns the number of parameters.

Named Function Expressions (NFE)

A Named Function Expression (NFE) is a function expression with a name.

Example: NFE Usage

let greet = function hello() { console.log("Hello, world!"); }; greet(); // Output: "Hello, world!" // hello(); // ❌ Error: hello is not defined (not accessible outside)

hello is only accessible inside the function.
✔ Useful for recursion and debugging.

Why Use NFE?

  1. Helps in Debugging

    • Named functions show up in stack traces, making debugging easier.
  2. Allows Recursion in Function Expressions

let countdown = function repeat(n) { if (n > 0) { console.log(n); repeat(n - 1); // Using function's own name } }; countdown(3); // Output: 3, 2, 1

repeat is only available inside the function, preventing unintended access.

  1. Prevents Overwriting by Reassignment
let factorial = function fact(n) { return n === 0 ? 1 : n * fact(n - 1); }; console.log(factorial(5)); // Output: 120 // Reassigning factorial let oldFactorial = factorial; factorial = null; console.log(oldFactorial(5)); // ✅ Still works because it uses `fact`

✔ Even if factorial is reassigned, fact inside still works.

šŸŽÆ Summary

✔ Functions in JavaScript are objects and can have properties.
✔ Function objects have useful properties like .name and .length.
Named Function Expressions (NFE) help with recursion, debugging, and prevent accidental function overrides.

šŸš€ NFE makes functions more powerful and safer! Let me know if you need more examples! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close