DEV Community

Cover image for Deep Dive into JavaScript Functions

Deep Dive into JavaScript Functions

Francisco Inoque on September 24, 2023

Deep Dive into JavaScript Functions Functions are a fundamental concept in JavaScript, allowing you to define reusable blocks of code th...
Collapse
 
synthetic_rain profile image
Joshua Newell Diehl

So fun! I love me some functional js.
Check out this neat constructor syntax!

const Counter = (count) => ({
    current: () => count,
    increment: () => count++,
    decrement: () => count--,
    adjust: (amount) => count += amount
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peerreynders profile image
peerreynders

Typically that's called a factory function as it isn't used with the new operator.

When a function is used as a constructor (i.e. is invoked with the new operator) it needs to work with a dynamically bound this which represents the object under construction.

Given that arrow function expressions have their this statically bound to the environment that created them only regular function declarations (and regular function expressions) can used as constructors.

Collapse
 
synthetic_rain profile image
Joshua Newell Diehl

Check out this neat factory function syntax

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Closures are inner functions that have access to the variables of their outer functions even after the outer function has completed its execution. This is useful for creating encapsulation.

Closures are NOT functions. They are the combination of a function bundled together with references to its surrounding state. ALL functions have an associated closure, not just ones created inside others.