Function Declaration Vs Expressions In JS

Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Function Declaration Vs Expressions In JS.

In JavaScript, there are two ways to create a function: function declarations and function expressions. Both ways allow you to create reusable blocks of code, but they have some key differences in terms of how they are used and how they are hoisted.

Function Declaration Vs Expressions In JS

A function declaration is a way of defining a function using the “function” keyword followed by the function name and a set of parentheses. Here is an example of a function declaration:

Code For Function Declaration

function greet() {
    console.log("Hello, World!");
}

greet();

Output

Hello, World!

A function expression, on the other hand, is a way of defining a function by assigning it to a variable. Here is an example of a function expression:

Code For Function Expression

let greet = function() {
    console.log("Hello, World!");
}

greet();

Output

Hello, World!

One of the main differences between function declarations and function expressions is hoisting. Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope.

Function declarations are hoisted, while function expressions are not. This means that function declarations can be called before they are defined in the code, while function expressions cannot.

greet(); // function declared can be called here
function greet() {
    console.log("Hello, World!");
}

let greet = function() {
    console.log("Hello, World!");
}
greet(); // function expression can't be called here

Another difference is that function expressions can be anonymous, which means they don’t have a name. Function declarations, on the other hand, must have a name.

Anonymous function expressions are often used as callbacks or arguments for other functions.

let button = document.querySelector('button');
button.addEventListener('click', function() {
    console.log('Button was clicked!');
});

Function declarations are hoisted, while function expressions are not, and function expressions can be anonymous, while function declarations cannot.

Conclusion

In conclusion, function declarations and function expressions are both ways of creating reusable blocks of code in JavaScript, but they have some key differences in terms of hoisting and naming.

If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment