DEV Community

Discussion on: Learn these awesome Javascript concepts.

Collapse
 
mooha1999 profile image
mooha1999 • Edited

In the Closure example
The parameter "childName", where will it get its value from?
I'm new to js and this issue is confusing me

Collapse
 
peerreynders profile image
peerreynders • Edited

This is one of the weird cases where it is actually easier to show with TypeScript:

// A type of function that takes a 
// `string` argument and returns `undefined`
type ChildFn = (name: string) => void;

// A type of function that takes a
// `string` argument and returns a `ChildFn`
type ParentFn = (name: string) => ChildFn;

// `create` is a function of type `ParentFn`
// i.e. it takes a string argument and returns
// a `ChildFn` function. 
const create: ParentFn = (parentName) => 
  (childName) => print(`${parentName} ${childName}`);

// i.e. `create` returns the function 
// `(childName) => print(`${parentName} ${childName}`)`
// note that `parentName` comes from the closure that 
// created the function.

// The function returned from `create` 
// is bound to `child` and has access 
// to `parentName = 'Bitcoin' 
// through its closure which created it
const child: ChildFn = create('Bitcoin');

// Here we finally supply `childName` 
// so that the full string is logged.
child('Dogecoin');

// ---
function print(...args: any[]): void {
  console.log(...args);
}
Enter fullscreen mode Exit fullscreen mode

So it's at child('Dogecoin'); that we supply childName.

A version that uses function declarations only:

// A type of function that takes a
// `string` argument and returns `undefined`
type ChildFn = (name: string) => void;

// The function value returned from `create`
// is bound to `child` and has access
// to `parentName = 'Bitcoin'
// via the closure that created it
const child: ChildFn = create('Bitcoin');

// Here we finally supply `childName`
// so that the full string is logged.
child('Dogecoin');

// [LOG]: "Bitcoin Dogecoin"

// ---

// `create` is a function that takes
// a `string` argument and returns
// a function of the `ChildFn` type.

function create(parentName: string): ChildFn {
  return childFn;

  // ---
  function childFn(childName: string): void {
    print(`${parentName} ${childName}`);
  }
}

// i.e. `create` returns the `childFn` function
// value which has access to `parentName`
// value via the closure that created it.

function print(...args: any[]): void {
  console.log(...args);
}
Enter fullscreen mode Exit fullscreen mode

I believe it's a bit more difficult to understand.