6 d.r.y


#1



I am super confused. Please help.


Oops, try again. There was a problem with your syntax.
SyntaxError: Unexpected token var


var orangeCost= function(price)  {
    var orangeCost = price * 5
    console.log(var orangeCost);
};

orangecost(5)


Replace this line with your code.


#3

I am still working on fixing my code. Here is where I am at.

var orangeCost= function(price)  {
    orangeCost = price * 5;
    console.log(orangeCost);
};

orangeCost(5)

I removed var and added a semicolon to the second line of code.

The error message I now receive is:

Oops, try again. It looks like you didn't define orangeCost.


#4

@tonysgarcia

Hi, you must log into the console the result of price time 5. Not set it to the result of orangeCost because it is a function that you are creating not a variable.


#5

This is what I tried:

var orangeCost= function(price)  {
    orangeCost = price * 5;
    orangeCost= 5*5;
    console.log(orangeCost);
};

orangeCost(5)

This is my error message:

Oops, try again. It looks like you didn't define orangeCost.

Is there a way to get a hint without giving the answer?


#6

@tonysgarcia

Do not do this!!!!

First define a function

var functionName = function(optional parameter) {
};

Second, log into the console price * 5

Hope this helped.


#7

Thanks for the effort @miniapple8888, but I already know the instructions, can you make any other suggestion?


#8

@tonysgarcia

Remove this line

And instead of putting orangeCost as parameter in your console.log put this:

price * 5

#9

@miniapple8888. The code worked. Thanks for the help. I think I could not make sense of the exercise because I do not see the point of making a function when the function did not do any work.


#10

In other words, I am having difficulty understanding the structure of a function and how it relates to performing tasks. I understand the explanation codecademy gives but, is there a way of putting into words how the function functions?


#11

I read a bit from W3 schools and and What I gather is the first line of a function is telling the computer, "I am making a function" and my first line of code declares,"Hey, this is a function and the parameter is in this term and it will be changing based on the block of code between the curly braces.


#12

@tonysgarcia

--------BASIC OF A FUNCTION--------

The principle of a function in programmation is DO NOT REPEAT YOURSELF (D.R.Y). Instead of having to write the same thing over and over again, you can store this in a function that will do the work for you. Per example in this exercise, it asks you to log into the console the price of an orange times 5 for five oranges. You don't want to write this code over and over, don't you?

// in the market
console.log(0.50 * 5)
// in another market
console.log(1.0 * 5)
// in a market somewhere else
console.log(0.79 * 5)

Note to self: The prices are fictional

We don't want to do this over and over again so why don't we create a function that will do this for us? We can save much more time not repeating the same code again and again:

orangeCost(0.5); // returns 2.5
orangeCost(1.0); // returns 0.5
orangeCost(0.79); // returns 3.95

This is the basic principle it does but also it allows to isolate code to debug them if there are problem. Per example if you write a bunch of code and it says

The code

var user = prompt ("As you look upon the golden chalice 'Altar of Akseni' you TAKE it, LEAVE it, or SET A TRAP around it?").toUpperCase();

if (user === "SET A TRAP") {
    console.log ("You decide it is best to" + " " + user + " " + "around the golden chalice!") } else { console.log (" You decide to" + " " + user + " " + "the golden chalice!") };

switch (user) {
    case "TAKE":
        confirm ("That chalice is looking a little... fiery...")
        var coveredHands = prompt ("Are your hands are covered?", "YES or NO").toUpperCase();
        var tempSense = prompt ("Either way, are you good with temperature defferences?" , "YES or NO").toUpperCase();
        if ((tempSense||coveredHands) === "YES") {
            //Why doesnt what I have starting here
            console.log ("Good thing" + " " +
            if (tempSense === "YES") {
                //The above if is the unexpected if causing the 
                //SyntaxError
                console.log ("you can handle temperatures well because this golden chalice is blessed under the power of the sun, forged in the flames of the Everburn and is still brimming with a fair bit of extra heat, but you should be able to manage.") }
                else {console.log (" your hands are covered because this golden chalice is blessed under the power of the sun, forged in the flames of the Everburn and is still brimming with a fair bit of extra heat, but you should be able to manage.")  }}
            else { 
                console.log ("You decide it's probably for the best that you don't pick it up due to the fact that you can already feel the excess heat it's putting off.") }
        //And ending here work? It says SyntaxError: Unexpected token if, which I understand, but WHY cant I do this, or is it that this just isn't the format to do it in? (Also, I got this to work before I did this, I just wanted to try this to see if I could get it to work because the end result just seems a little strange sounding.)
        break;
    case "LEAVE":
        confirm ("You decide you no longer want any business with this chalice, but as you nervously and spradically turn to leave you bump a hidden stone swith on a pillar, and the temple rattles and rolls as the it starts to fall apart!")
        var swiftFeet = prompt ("Can you run fast, and we're talking you're going to be ground into a pile of muck, fast?" , "YES or NO").toUpperCase();
        var emptyHanded = prompt ("Would it be wise to leave what you can behind to lighten the load, and move faster? Maybe even removing and ditching your armour as you go about it?" , "YES or NO").toUpperCase();
        if ((swiftFeet||emptyHanded) === "YES") {
            console.log ("With all the might in your legs and all the space in your lungs, you flee for this cabal of death to the white wheaten fields from which you came!") } 
            else {
                console.log ("You make it always entirely through the exit as one of your legs become crushed beneath a boulder, cleaving it off at your knee.  With all the resolve you can muster, however, you believe you can make it to the nearby city of Tri'atta and in turn survive.") }
        break;
    case "SET A TRAP":
        confirm ("You know full well you arent the only one here, you can feel the presence of at least one other.  However the entity you sense is mysterious, and takes on the presence of, at times, many.  Whether it be one or all, you know you're not alone.")
        var checkSense = prompt ("Do you have the ability to avoid detection while you rig a sufficient trap?" , "YES or NO").toUpperCase();
        var intelligence = prompt ("Are you even intelligent enough to build a trap?" , "YES or NO").toUpperCase();
        if((checkSense&&intelligence) === "YES") {
            console.log ("Creeping through the shadows, footfalls lighter than a louse, you use your wits to spring a trap that should ensnare any creature, ethereal or otherwise, in a magical matrix long enough for you to then escape, chalice in hand.") }
            else {
                console.log ("As you begin to set the trap, you become vividly aware that you're neither sharp enough to pull off the complex runes, nor quite enough to have gone still unnoticed.  The Pi'e'ren finds you and attaches itself to you, sucking the life from you and leaving you a dry, withered shell on the floor...") }
        break;
    default:
        console.log ("What, no, that clearly wasn't an option, this is my game you'll follow my rules! MINE MINE MINE!")
        break;
}

Note to self: This code has been took from this topic https://discuss.codecademy.com/t/code-your-own-adventure-2-unexpected-token-if-syntaxerror-but-why/22216

You can isolate each case statement to see if there are any problems.

It can also be used for updating code. Per example now you don't need to buy 5 oranges but 7 oranges. It simplifies it by updating a single function and the problem is solved!

Instead of

// in the market
console.log(0.50 * 5) => console.log(0.50 * 7)
// in another market
console.log(1.0 * 5) => console.log(1.0 * 7)
// in a market somewhere else
console.log(0.79 * 5) => console.log(0.79 * 7)

You can just change one single code:

var orangeCost = function(price) {
console.log(price * 7);
};

And here we go! We updated our function saving a lot of time and a lot of line of coding!

------------Function Syntax------------

The function syntax looks a bit like this:

var functionName = function(optional parameter) {
// the code runs here
};
  1. We create a function using keyword var.
  2. We assign its name in functionName.
  3. We assign it to a function having optional parameter
  4. There are no need of parameters only if you want the code to output different things each time different thing is input
  5. The code runs between the curly brackets, the code that is going to get repeated over and over again every time it is called.
  6. We close the curly brackets for the end of the function.

How we call a function

functionName(optional parameters);

If there are no parameters in a function

functionName();

Hope this helped and sorry the long text I had to put in!


#13

Thanks for your help. The more perspectives the better.