Home > Software design >  How it's possible to have same variable and function name in JavaScript
How it's possible to have same variable and function name in JavaScript

Time:11-16

We usually use React.memo as follow

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});

We have a MyComponent function and a MyComponent variable in the same scope, Why the syntax is correct and we have no runtime error like Uncaught SyntaxError: Identifier 'MyComponent' has already been declared?

CodePudding user response:

Given a function declaration (you don't have one, this is for the sake of comparison):

function example() {
    ...
}

The identifier example does two distinct things.

  1. It sets the function name to example
  2. It creates a variable named example and assigns the function to it

It is important to distinguish between the name of a function and any variables that reference it.

You could go on to do:

const foo = example;

So now you have a function named example and two variables (foo and example) which can be used to access it.


The syntax you have in the question is a function expression not a function declaration.

One of the differences between function expressions and declarations is that the identifier only names the function. It does not create a variable of the same name. (Another difference is that the identifier for expressions is optional, you have a named function expression).

Since it doesn't create a variable, there is no conflict with const MyComponent.

  • Related