Function declarations and function representations

Asked 1 years ago, Updated 1 years ago, 131 views

I recently started maintaining someone else's JavaScript code. You want to fix bugs and add features to fix code more consistently.

Previous developers defined code as a function in two ways. I was wondering if there was any special reason for doing this, so I couldn't proceed with the work anymore.

Both ways are

var functionOne = function() {
    // // Some code
};

function functionTwo() {
    // // Some code
}

It's like this. I wonder what the reason for each method is and what are the pros and cons of each method. Is there anything that works in those two ways, but not in other ways?

function javascript syntax

2022-09-22 22:08

1 Answers

The difference is that functionOne is defined at runtime, while functionTwo is defined when the script block is interpreted. For example,

<script>
  // Error Occurred 
  functionOne();

  var functionOne = function() {
  };
</script>

<script>
  //Normal execution
  functionTwo();

  function functionTwo() {
  }
</script>

In this way, if a function is called above the defined one, the error functionOne() is not a function occurs. On the other hand, the second method is called well.


2022-09-22 22:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.