How to keep JavaScript function expressions in memory?

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Inferred_function_names:

Variables and methods can infer the name of an anonymous function from its syntactic position (new in ECMAScript 2015).

Chrome and Firefox both give "sayBye" when printing bye.name.


From personal experiments, Chrome console shows bye.toString() when asking for bye, while Firefox shows a custom output of theirs, where they display the inferred name of the function (which makes sense indeed, as knowing the name usually helps debugging).


Functions are object so assignment x = y is not copied . I tried this Nodejs I got

Bye
[Function: sayBye]

If you don't name a Function JS will automatically add name to it. In ES6 you can check name of function by using myFunction.name ,i.e. 'name' is property of an function object .Important thing is that this is read only property. Good practice is to use const instead of let while using function expression .Also ,if possible, try to name function debugging is easy on call stack


You are confused by the function's name.

The memory things happen exactly the same way as you thought.

However, the function didn't have an explicit name, so the browser gave an implicit name to the function, that is the name of the variable or object property it was first assigned to, in this case, sayBye.

Then, it gets assigned to a different variable, but the name doesn't change.

You can see this if you give an explicit name to it:

//  Explicit name ----vvvv
let sayBye = function myFn() {
    console.log(`Bye`);
}

let bye = sayBye;   
sayBye = null;    // X

bye();            // Y

console.log(bye);

Tags:

Javascript