Function expression over declaration

Hi there,

I am learning about JavaScript functions, and would like to understand why the compiler chooses to return the value for the function expression over the function declaration?

// Function declaration
function myFunction() {
  return 'Hi';
}

// Function expression
var myFunction = function myFunction() {
  return 'Hello';
};

console.log(myFunction()); // returns Hello


Thanks!
userTesterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Steve BinkCommented:
Because you are essentially re-declaring the variable myFunction.  If you were to reverse the order, the function declaration would take precedence, since it would execute later.
0
userTesterAuthor Commented:
Steve

Thanks for responding. I reversed the order, but the function expression still gets precedence - prints Hello.
0
Slick812Commented:
greetings userTester, , In javascript, unlike some other languages, the "Reference Names" of functions ARE VARIABLES, the reference name in yours is "myFunction".  The declaration of a function, is different than the declaration of a  variable as you have -
      var myFunction = function myFunction() {}
which should be -
      var myFunction = function () {}

This will more or less over-write any previous declarations of a function named myFunction, since you all ready have the declaration of the "myFunction" in the
function myFunction() { }
technically you do not need the    var     in this -
       var myFunction = function () {}
could be just -
       myFunction = function () {}

if you just declare a function -
      function myFunction() { }
without the    var myFunction =
then it does not necessarily "over-write" anything that a "Variable" declaration before it has done, I am not really sure about the technical reason, but as far as I have seen, for setting up the page javascript the functions are read and applied before the variables are read, but this is just my opinion.

I did this in firefox -
function myFunction() {
  return 'Hello';
}
console.log("first: "+myFunction());

myFunction = function () {
  return 'Equals';
};
console.log("second: "+myFunction());

function myFunction() {
  return 'Hi';
}
console.log("third: "+myFunction());

Open in new window

and got this console output -
"first: Hi"
"second: Equals"
"third: Equals"

so you see that the second function overwrites the first even BEFORE it is declared, and the variable declaration over-writes both.

= = = = = = = = =
By the way, do NOT have two functions declared with the same name -

function myFunction() {
  return 'Hello';
}

function myFunction() {
  return 'Hi';
}

as this is just bad and confusing code work, I did it here to only demonstrate something.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

userTesterAuthor Commented:
Thanks Slick812,

functions are read and applied before the variables are read

According to javascriptissexy, you are correct, except perhaps for the "applied" part.

So, as you infer, it looks like the function expression variable which has the same name as the function declaration, overwrites the function declaration during hoisting.

This would mean that any variable with the same name as a function, would overwrite any function of the same name, if they're in the same scope of course??
0
Slick812Commented:
Yes, and this can be a good programming tool , to dynamically change the processes of functions according to changes the user makes with check boxes or radios or AJAX return values.

But the variables in javascript can be assigned to an kind of value, so you can turn a function into a string -
function myFunction() {
  return 'Hello';
}


myFunction = "now I'm a String";

Open in new window

and it will no linger work as a function -
  var str = myFunction( ); // will error out of javascript
0
userTesterAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 250 points for Slick812's comment #a40828073
Assisted answer: 0 points for userTester's comment #a40828143
Assisted answer: 250 points for Slick812's comment #a40828244

for the following reason:

Thanks Slick812!
0
userTesterAuthor Commented:
I need to make a correction about my post: ID: 40828143.
0
userTesterAuthor Commented:
A correction to my statement at comment ID: 40828143
So, as you infer, it looks like the function expression variable which has the same name as the function declaration, overwrites the function declaration during hoisting.
I should have said that function declaration overrides variable declaration during hoisting, but variable assignment overrides function declaration​, if they both have the same name of course.

To explain a little further, the function expression variable gets hoisted, but not the entire function expression, so the function declaration takes precedence over the function expression variable during hoisting, but when the compiler assigns the values, the function expression variable overrides the function declaration value.

I did a second read through javascriptissexy, and found that I made a mistake with the timing of the override, sorry about the confusion.

Let me know whether you think that is correct, thanks.
0
Slick812Commented:
????, it is not correct or incorrect, because, javascript is just a scripting language, and in it Nothing gets complied so you say - "when the compiler" does not apply. . An I have never heard of using the word "hoisting" in programming, as if something is being lifted up? In order to have a function work, the script TEXT in the function definition MUST be read and interpreted to a browser sub-processes "ordering" of operations to come close to the text intention of the writer of the code.  So the functions must be setup, BEFORE the code line execution progression, begins at the top and goes line by line down to the bottom.

Do not ever think that the TEXT you write for programming language syntax, has any thing at all to do with, or correspond to any actual machine CPU memory manipulations that produces real light pixel output on your monitor. You program in just TEXT, and it has NO operational value, until it is interpreted and transformed to some computer (not human) electronic operations, which have no relation to any text like -
   for (i=0; i<7;++i)
0
userTesterAuthor Commented:
Thanks Slick812,

I think there is a move toward compiled code, but I am not sure about the technicalities, and whether it is just some form of compilation, and not the real deal. Apparently, Chrome was the first browser with an optimizing engine that compiles JavaScript into native code. Also, many new books on JavaScript, speak in terms of compilation, compile time, and a compiler, so something's brewing.

Hoisting is also a term being used in many newer JavaScript books and articles. I guess it's just a word being used for the same process you've explained.

I did some very basic JavaScript many years ago, and I too never came across these terms, and essentially how JavaScript is being used today.
0
userTesterAuthor Commented:
Thanks Slick812!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.