Difference between var functionName = function() {} and function functionName() {} in JavaScript
Hello, colleagues! I'm a beginner frontend developer and I've run into some confusion. In different projects and tutorials, I see two ways of declaring functions:
```javascript
// Method 1: Function Expression
var myFunc = function() {
console.log("Hello from expression!");
};
// Method 2: Function Declaration
function myFunc() {
console.log("Hello from declaration!");
}
```
At first glance, they do the same thing. But when I started writing more complex code, I noticed strange behavior. For example, if I call a function before its declaration, one method works while the other throws an error:
```javascript
// This works
sayHello(); // Outputs "Hello!"
function sayHello() {
console.log("Hello!");
}
// But this throws an error
s
No answers yet.
Log in to leave an answer