Function expressions or functions declarations?

Hello there!

I have some PHP knowledge, and now I’m trying to learn JavaScript. Because of that, I never saw something like defining a function using a function expression before.

Right now, I’m doing Learn JavaScript Syntax: Functions, and I’m having a great doubt about function expressions utility.

What are the differences between defining a function by function declarations and by function expressions?

function plantNeedsWater(day) {
// Some clean code
}
const plantNeedsWater = function(day) {
// Some clean code
}

Conventional function declarations seem cleaner to me, and it’s what I see in other languages. So, why use function expressions to define a function?

and it’s what I see in other languages

Great question! But also it depends on which languages you’re often seeing :slight_smile: If you’re seeing haskell, coq, scala (etc.) then the first example is the odd one out…

It’s a matter of imperative vs declarative (Declarative vs Imperative. Transition into React from Javascript | by Myung Kim | Medium). (Two styles which suggest, but do not define object oriented programming and functional programming).

It seems React is moving towards a more declarative style rather quickly. (But there is and will still be a lot of imperative React code out there).

1 Like

Thanks for your help!

But after reading the article I was confused, I think maybe is too complex for my actual level. I did some research and I found this freeCodeCamp article: When to use a function declaration vs. a function expression.

1 Like

Hi,

Well the core of it is that they come from 2 very different styles of programming. The reason why one is one way and the other is another is a matter of getting to know the intricacies of each style… which is not an easy to digest in a small article.

If you want to understand function expressions better I’d recommend looking into ideas of functional programming: light version → What is functional programming | Easy way - YouTube slightly heavier version (still light) → Functional Programming & Haskell - Computerphile - YouTube

1 Like