4 Introduction to Functions- How does a function work?


#1

Here is the code I have written:

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

The error I'm receiving is SyntaxError: Unexpected string

Could someone please help me fix the code and explain what I've done incorrectly?


#2

var foodDemand =function(food)


#3

@jaheenan77 you should declare your function with the parameter without quotes so it looks like this:

var foodDemand = function(food)

then, in your code block (the code reusable code between the curly brackets), you want to remove the quotes around "food" so that this is identifying the parameter only, like this:

{console.log("I want to eat" + " " + food);
};

try that and see if it works... it should


#4

This is my code

why doesn't it work? Thanks.


#5
 var foodDemand = function(food) {    <---- no semi colon before the bracket!
        
        console.log("I want to eat" + " " + food);     need the +'s 
        };
        foodDemand(Rice);

That should work.


#6

You might be right, but it doesn't work yet ( "missing ) after argument list")


#7

oh and also put rice in quotation marks "Rice"


#8

Still the same, any more suggestions?


#9

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

This works for me if not for you, refresh the browser.


#10

Thanks! You helped me a lot!


#11

I tried making those changes to my code leaving it as this:

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

But I'm still receiving the "SyntaxError: Unexpected string" error.

Thank you for your explanation of the components of the code, it was helpful


#12

Update to everyone I was able to solve the problem by returning to exercise 3 and comparing my code structure against that code

(Exercise three)
This code was working

var greeting = function (name) {
console.log("Great to see you," + " " + name);
};
greeting ("James")

(Exercise four)
This code was not

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

After removing the quotation marks from food shown here:

var foodDemand=function ("food")

var foodDemand=function (food)

I submitted the code again and it worked as intended


#13

What is wrong?????


#14

food is the parameter of the function and therefore it only exists inside of the function. So instead of food("Pizza") better call your foodDemand function:foodDemand("Pizza");


#15

this should work

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


How does a function work?
#19