FAQ: Functions - Function Expressions


#1

This community-built FAQ covers the “Function Expressions” exercise from the lesson “Functions”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Function Expressions

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

I’m confused why I’m able to reassign the value of the constant variable plantNeedsWater in the following code:

const plantNeedsWater = function(day) {
  if (day === 'Wednesday')
    {return true}
  else {
    return false;
  }
}

console.log(plantNeedsWater('Tuesday'));

console.log(plantNeedsWater('Wednesday'))

//outputs false, true

I was imagining that by calling the function, initially plantNeedsWater evaluates to a constant ‘falsey’ boolean, but then by calling the function a second time, you can change it to a truthy. Does this effectively destroy the original plantNeedsWater value by overwriting it?


#3

The only thing constant is the name and the assigned function. Parameters are not in the same scope. That’s why we can run the function over and over with different inputs.


#4

Thanks for your reply. So to be clear, in the above code:

const plantNeedsWater = function(day){
}

is a function only, and not a variable declaration, right? Effectively the same as if I had typed:

function plantNeedsWater(day){
}

Can the function’s contents be changed later if I declared a function like:

let plantNeedsWater = function(day){
}

Through experimentation, I determined “yes” is the answer to the above questions. Thanks for your help!


#5

No. The above is hoisted as a declared function; the preceding is hoisted as a variable, which expression will be caught on the next pass.

When we assign using = in our code, the right hand side does not get hoisted. That is why we call them function expressions; they appear on the right hand side of an equals sign. On that side they are values.

They can also appear in arguments to other functions, in which case we refer to them as a callback. Essentially when the return value of one function given the inputs becomes the argument value of another function, per chance with additional arguments (that may include the initial inputs in some way).

Hoisting and binding are two different things to keep aware of in JS.


 > (function () {
     return foo();
     function foo(day="Wednesday"){
       return day==="Wednesday" ? "Water me!" : "Don't water me!";
     }
   })()
<- "Water me!"
 >

 > (function () {
     return foo(arguments[0]);
     function foo(day="Wednesday"){
       return day==="Wednesday" ? "Water me!" : "Don't water me!";
     }
   })('Thursday')
<- "Don't water me!"
 > 

The binding is to the return (response) value of the expression. That’s the key. Only foo was ever hoisted. Least not to mention is the arguments object which may or may not be populated. The first value may be of some interest…


This tells us that hoisting occurs within functions, not just at the global level. Whatever isn’t hoisted is treated as a value on the second pass. Recall that expressions are values, and utilize that going forward.


#6

Hey everyone,

I guess this just flew over my head - but I’m a little confused over the solution suggested by Codecademy:

const plantNeedsWater = 
      function(day, plantNeedsWater){
         if(day === 'Wednesday'){
           return true;
         }
         else {
           return false;
         }
       };
  1. Why would I have to make it a variable? I tried just making it a function and it seems to work fine.

  2. Why is plantNeedsWater a parameter in the solution above? ‘day’ changes and is affected in the if and else statements. Why is plantNeedsWater listed as a parameter above? I don’t quite get it.

The const and parameter just seems like code I don’t necessarily need, or am I missing something?

The code below (works):

function plantNeedsWater(day){
        if(day === 'Wednesday'){
          return true;
        }
        else {
          return false;
        }
      };

Thanks,
Malte


#7

The code works, yes, but the exercise deals with function expressions, not function declarations. If an expression is expected, your code will not and should not be accepted.


#8

So does someone have an example of why I’d ever want to use a function expression over a function declaration?


#9

Hi there,
I don’t understand why I need to “call” the function before logging it into the console. Why do we call it and pass an argument to it, and then have to type all of it again when logging it into the console?


#10

You probably wouldn’t want to print the function itself, you’d want its result instead.
You wouldn’t want to print addition but you might want to print the result of doing addition on 1 and 2


#11

Logging is a one way operation. We send content to the method, and it outputs (logs) it to the console (the terminal window at right in the learning environment).

If we wish to output the result of our function running on the various arguments, we need that result before we can log it.

const hello = subject => `Hello ${subject}!`;    

var result = hello('World');

console.log(result);    // Hello World!

Alternatively, we can log the return value directly…

console.log(hello("Earth"))    // Hello Earth!

#12

Thanks for your responses, sorry but I’m really having a mental block on this.

In some cases, the exercises make me print the result by just calling the function (e.g. playGame() in the ‘Rock, Paper, Scissors’ exercise). But in some other cases, I need to log it into the console to get the result (e.g. “console.log(eightBall);” in the Magic Eight Ball exercise).

I’m not sure I understand when I can do what.


#13

Usually a function shouldn’t print anything and instead return a value. Whoever calls the function can then choose what to do with that value (like displaying it)


#14

Ok, let me take an example: in the “Paper, rock, scissors” exercise, I had to do the following:

const playGame = () => {
const userChoice =
getUserChoice('scissors');
const computerChoice =
getComputerChoice();
console.log('You threw: ' + userChoice);
console.log('The computer threw: ' + computerChoice);
console.log(determineWinner(userChoice, computerChoice));
};

playGame();

In the Magic Eight Ball exercise, my code is the following:

const randomNumber = Math.floor(Math.random() * 8);

let eightBall = '';

switch(randomNumber) {
  case 0 :
    eightBall = 'It is certain';
    break;
  case 1 :
    eightBall = 'It is decidedly so';
    break;
  case 2 :
    eightBall = 'Reply hazy try again';
    break;
  case 3 :
    eightBall = 'Cannot predict now';
    break;
  case 4 :
    eightBall = 'Do not count on it';
    break;
  case 5 :
    eightBall = 'My sources say no';
    break;
  case 6 :
    eightBall = 'Outlook not so good';
    break;
  case 7 :
    eightBall = 'Signs point to yes';
    break;
  default :
    eightBall = 'Invalid';
    break;
}

console.log(eightBall);

Why don’t I need to do console.log(playGame) in the first example?
Why can’t I just call eightBall() in the second example?


#15

If you have a piece of text then you can display it.
Are those both text?


#16

Hi my question is simple, why Return true; instead of Return = true; ? This last one displays an error.

Just want the theory, tyvm.


#17

return is not assignable. We simply follow the keyword with the return value or object.


#18

Why messing with Ifs and elses, when you can just return the condition:

const plantNeedsWater = function(day) { return (day==='Wednesday') }


#19

Because before we can run, we need to learn how to walk. Learning program logic is not as simple a task as one might think. First we master the naive, then we explore the abstract.


#21

Why don’t I need to do console.log(playGame) in the first example?

You don’t need to use the console.log command yourself because the playGame() function is calling three different console.log commands on it’s own.

Why can’t I just call eightBall() in the second example?

There is no function “eightBall()” created in that exercise, so calling it should do nothing.
In the exercise, you’re using a random number to change what string the eightBall variable is set to, and then calling the eightBall variable to the console to check that it’s actually changing.