4.java script functions


#1

does any one know whats wrong with my sntax?

var foodDemand = function("chocolate");
{
console.log("I want to eat" + " "+ food);
}


#2

try this

var foodDemand = function("chocolate") //took away the semicolon(;)
{
    console.log("I want to eat" + " "+ food);
}; // added the semicolon here

#3

var foodDemand=function("suishi")
{
console.log("I want to eat" + " " + food)
};

//* mine is still wrong. What did i do wrong?


#4
var foodDemand=function("suishi")

you used "suishi" as parameters but parameters are expected to be variable names like e.g. food in your case. The way it gets it's value is by calling your function e.g.

foodDemand("suishi");

#5

var foodDemand = function(food ){
console.log("I want to eat"+" "+ "food");
}
foodDemand("apples");

This is what I got. I had function("food") instead of function(food).


#6

Well good that you changed it then :smile: But you're still not making use of the parameter. The idea is that the parameter (the variable name after function) is a local variable of your function that get's it's value assigned by the function call. So by using foodDemand("apples");, your parameter food gets the value "apples" so inside of your function you can always use food as if it would mean "apples" just like a regular variable. This also enables you to run the same function and get different results. Test it! Just remove the "" from food and run the function a few times with different inputs to see the results.


#7

Hi there,

I am very new to coding. So I've got some questions to ask which I hope you don't mind. This is my code below:

var foodDemand = function(food)
{
console.log("I want to eat"+" " +"Chicken")
};

foodDemand ("cake")

So my question is, my foodDemand says "cake".
But the console prints out "chicken" because that is what I told it to do. But it clearly shows that you can put anything in the foodDemand and it will still say what you have told the console to print out... does this make sense??

I'm just inquisitive regarding this code structure... :smile:


#8

What you say after foodDemand in the () for example "cake" is then stored in the food variable that you declared after function in the (). There it stays ready for you to use it, but of your you could use a hard coded "Chicken" instead :smile:
But as you've already got it maybe it is a good idea to use console.log("I want to eat "+food) and see what you get :wink: