Difference between var functionName = function() {} and function functionName() {} in JavaScript
Hello everyone! I just started learning JavaScript and encountered a situation that is unclear to me. In different code examples, I see two ways of declaring functions that look similar but behave differently.
First way:
```javascript
var myFunc = function() {
console.log("Hello!");
};
```
Second way:
```javascript
function myFunc() {
console.log("Hello!");
}
```
At first glance, they do the same thing — create a function named `myFunc`. But I noticed that if you call the function before its declaration, the first way throws an error, while the second one works. For example:
```javascript
// Works
test1(); // Outputs "Works!"
function test1() {
console.log("Works!");
}
// Error
test2(); // TypeError: test2 is not a function
var test2 = function() {
No answers yet.
Log in to leave an answer