56740

Function declaration in variable object

Question:

test(); //working function test(){//do something}

Is this related to (global)variable object? Does the function push to variable object before execution process start?

UPDATE: Ok my real question is how "hoist" work. To understand you need to take a look at <a href="http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/" rel="nofollow">execution context of javascript</a>,and yes it related to variable object(which is part of execution context).

Answer1:

See the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet" rel="nofollow">Scope Cheatsheet on MDN</a>

function foo() { } <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet#Hoisting" rel="nofollow">hoists</a> foo to the top of scope automatically

<blockquote>

Is this related to (global)variable object? Does the function push to variable object before execution process start?

</blockquote>

Nope, it's just hoisting.

<hr />

Consider this example:

foo(); // ReferenceError: foo is not defined (function(){ foo(); function foo (){ console.log("A"); }; })(); // A (function(){ foo(); function foo (){ console.log("B"); }; })(); // B foo(); // ReferenceError: foo is not defined

Hoisting just "lifts" the variable name to the top of the scope.

<hr />

<strong>My opinion:</strong>

I <strong>never</strong> write functions as:

function foo() { ... }

I prefer being explicit because magic behavior sucks; I <strong>always</strong> write functions as

var foo = function() { ... }

If I feel like the function needs a name, I will give it a name, but still define with var

var foo = function foo() { ... } <hr />

<a href="https://stackoverflow.com/users/825789/bfavaretto" rel="nofollow">@bfavaretto</a> raises a valid concern:

<blockquote>

About your opinion... var foo = function() { ... } also hoists foo to the top, but with an undefined value. So there's implicit stuff going on there too

</blockquote>

True, it does hoist foo with an undefined value, but things will all work as desired.

foo(); // TypeError: undefined is not a function // This is good. We don't want the above function to run like that. // This is a fatal error; the script won't even continue to run as-is. // Comment out the above line to get it to run. var foo = function foo() { console.log("foo"); }; var foo2 = function foo() { console.log("foo2"); }; // Even with the same function name, these two functions will // output the correct values. foo(); // foo foo2(); // foo2

All of that said, it would be silly to have two functions with the same name identifier in the same scope. But, even if you <em>do</em> make a mistake and write bad code like that, if you're using function expressions as described above, the code would still work anyway. If you just used named functions like in the original question, it certainly will not.

Answer2:

I think you are talking about <strong>Hoisting</strong> here. I always prefer labeled function instead of function expression.

<strong><em>this is a function expression:</em></strong>

//Declaration 1 var foo = function(){ // code goes here } <ul><li>The func expression in this case is anonymous but assigned to a var foo. for reference</li> </ul>

<strong><em>This is a labeled function :</em></strong>

//Declaration 2 function foo(){ // same code here } <ul><li>

There's not really any great reason to do expression to var. You should always try to use labeled statements for constructors,so you can identify an object's 'type' via its constructor.

</li> <li>

people mostly use this where <strong>hoisting</strong> is needed.<strong>Hoisting simply means calling something before it is defined</strong>.

<strong><em>Very very simple example</em></strong>:

foo(); // alerts 'hello' function foo() {alert('hello');} V/s foo(); // throws an error since foo is undefined var foo = function() {alert('hello');} </li> </ul>

REFER:<a href="https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname" rel="nofollow">var functionName = function() {} vs function functionName() {}</a>

Recommend

  • how to accomplish this?
  • UIButton highlight area extends way outside button
  • Why is object not defined?
  • froogaloop: $ is not defined
  • JS FormData object not defined for PhoneGap in Android
  • UISlider evaluate the result once they have stopped changing the value
  • IBM Worklight 6.0.0.1 - JavaScript not executing in a jQuery Mobile multipage app
  • Typescript ///: why doesn't it work for me?
  • Console Error with Ajax: ReferenceError: $ is not defined
  • how to define BusinessNetworkConnection in hyperledger-composer transaction processor?
  • Access to internal function from externally loaded HTML in React component
  • Loading javascript functions to webview in Android Kitkat
  • __awaiter is not defined when using async/await in Typescript
  • ReferenceError: localStorage is not defined in ReactJS Build
  • How can I pass mochas done callback function to another helper function
  • Firebase + Chrome content security policy settings?
  • How to use function declaration with jsfiddle
  • How to load external js library in Jmeter?
  • cannot convert from 'const char [3]' to 'char *' x100000 (Qt Creator C++ Windows
  • ASP.NET - Efficiently delay code execution for single request?
  • ViewData, ViewBag and TempData violates MVC? [closed]
  • Variant from android-autofittextview library : scaling makes strange behaviour
  • Where I store the custom exceptions in cakephp 3?
  • Android: how to determine cold start
  • Using multiple input pipelines in TensorFlow
  • CoreData basics – to-many relationship array data
  • in batch how do i use taskkill properly
  • Local Development, Apache vs Developer - file permissions
  • MySQL performance when updating row with FK
  • How to explicitly/implicitly implemented interface members in C++/CLI?
  • uniform generation of points on 3D box
  • Email format validation in mvc3 view
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • How to add date and time under each post in guestbook in google app engine
  • output of program is not same as passed argument
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Why winpcap requires both .lib and .dll to run?
  • python regex in pyparsing
  • coudnt use logback because of log4j