FAQ: Functions - Function Expressions


#22

I’m a little confused as to the application for Function Expressions, at least in the way it’s being shown in the exercise and my current understanding.

At a glance it appears redundant to declare a variable to hold a function when a function can just be declared on it’s own. Is it maybe related to memory usage throughout a larger program?

I think an example of a practical use case would set me straight.

Insight would be appreciated.
Thanks!


#23

This is an article from 2015, before arrow functions were adopted into regular use, but it can apply to them, as well, for the most part.

Quick Tip: Function Expressions vs Function Declarations

Conslusion
As we’ve seen, function expressions don’t offer much that can’t be achieved with function declarations, but using them can often result in cleaner and more readable code. Their widespread use makes them an essential part of every developer’s toolbox.


#24

I tried to turn this (working) code:

const plantNeedsWater = function(day) {
if (day === ‘Wednesday’) {
return true;
} else {
return false;
}
};
console.log(plantNeedsWater(‘Wednesday’));

Into this in order to reduce what is needed

const plantNeedsWater = function(day) {
day === ‘Wednesday’ ? true: false;
}
console.log(plantNeedsWater(‘Wednesday’));

However, when using the second code I get ‘undefined’ printed rather than ‘true’. What is this happening and is there a way to get the second code to behave like the first one?

Edit: Found solution in a example a few exercises later (after being too stubborn to move on at first)

return day === ‘Wednesday’ ? true: false;

fixes the problem


#25

A comparison results in Boolean value, so you could even do:

return day === 'Wednesday'

#26

Hey everyone! I’m a bit confused, why do I need to call a function right before logging the result to the console:

const plantNeedsWater = function(day) {
  if(day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
}
plantNeedsWater('Wednesday'); // here
console.log(plantNeedsWater('Wednesday'))

If I omit that step I will get the same result in the console as well. It seems that only the last value of the argument, which we have passed in here “console.log(plantNeedsWater(‘Wednesday’))”, matters. For example, if I assinged any other value there in the console.log step - I would get ‘false’, no matter what value we have assinged to the argument before. Thank you in advance.


#27

who says you need to do this?


#28

I was just doing everything according to task, one of the steps was to call the function and assign an argument. So as far as I understood there is no practical need to do this?


#29

calling plantNeedsWater function and logging the result is certainly useful, not sure why you call the first without logging the result. Its not needed


#30

Thank you. I might have misunderstood something.