Knowledgebase

Functions, Scope and Closures Print

  • webdevelopment, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Structuring behaviour.

WHAT A FUNCTION IS

A reusable block of code, taking inputs and returning a result.

WHAT SCOPE IS

Where a name is visible.

WHAT THE RULE IS

Names declared inside a block are visible only within it.

WHY THAT MATTERS

It prevents parts of the program interfering with each other.

WHAT A CLOSURE IS

A function retaining access to the scope it was created in, even after that scope has finished.

WHY THAT IS USEFUL

It allows private state, and functions that remember something.

WHY IT SURPRISES PEOPLE

Variables appear to persist beyond where they were defined.

WHAT ARROW FUNCTIONS DIFFER IN

Their shorter form, and how they treat the contextual reference to the current object.

WHY THAT MATTERS

The difference causes a specific and common class of bug.

WHAT MAKES A GOOD FUNCTION

It does one thing Its name says what It does not depend on hidden state

WHAT TO AVOID

Functions modifying things outside themselves Deeply nested functions Very long functions


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot