Janice Zhong
Janice Zhong

Reputation: 878

Question about comparing two functions by stringifying them

I came across this excerpt while reading Chapter 2 of "You Don't Know JS Yet".

But beware, it's more complicated than you'll assume. For example, how might you determine if two function references are "structurally equivalent"? Even stringifying to compare their source code text wouldn't take into account things like closure.

I just want to make sure if I understand correctly on what the author meant by "closure". I'm thinking of this example:

function x() {
  console.log('Hello');
}

const foo = x;

function y() {
  const bar = x;
  if(foo.toString() === bar.toString()) { // returns true but the closure of foo and bar is different 
    // do something
  }
}

Also, under what circumstances we need to compare two functions? Thanks.

Upvotes: 0

Views: 59

Answers (3)

Md Anik Hossen
Md Anik Hossen

Reputation: 26

The author means that closure is the data that a function carries with it, including the variables from its surrounding scope that are used in its body. In the example you gave, even though the two functions foo and bar have the same source code (as indicated by the toString() comparison), they are not structurally equivalent because they have different closure values.

As for when to compare two functions, you might need to compare two functions in certain scenarios, such as when you want to determine if two functions have the same behavior, if they have the same closure, or if they are bound to the same execution context.

Upvotes: 1

Carsten Massmann
Carsten Massmann

Reputation: 28196

Here is an example of two functions that look the same yet will behave differently because of their closure:

const what="great",
      fun1=()=>console.log(`This is ${what}!`);

{ // this block will have its own closure
 const what="stupid",
       fun2=()=>console.log(`This is ${what}!`);

 console.log(fun1.toString()==fun2.toString());
 fun1();
 fun2();
}

Upvotes: 2

Harry Z. Huang
Harry Z. Huang

Reputation: 79

As far as I can tell, the author is saying "closure" as a reference to scope. I think you are correct.

As for the comparison of two functions, the most obvious case that comes to mind is comparing the time and space complexity performance of two functions that perform the same overall task. However, in regards to the authors 'structurally equivalent' notion, I don't know.

Upvotes: 0

Related Questions