Why do I have to call a function after I have defined it?


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-qDwp0/1/4?curriculum_id=506324b3a7dffd00020bf661

I am wondering why it is invalid to do this

var answer = prompt("valid options are yes, no, maybe, invalid choices goto default");

functionOne(answer);

var functionOne = function (answer){
switch (answer){
case "yes":
console.log("yes works");
break;

    case "no":
        console.log("no works");
    break;

    case "maybe":
        console.log("maybe works");
    break;

    default:
        console.log("went to default");
    break;
}

};

But it is valid when I move **functionOne(Answer); ** below the function definition like this

var answer = prompt("valid options are yes, no, maybe, invalid choices goto default");

var functionOne = function (answer){
switch (answer){
case "yes":
console.log("yes works");
break;

    case "no":
        console.log("no works");
    break;

    case "maybe":
        console.log("maybe works");
    break;

    default:
        console.log("went to default");
    break;
}

};
functionOne(answer);


#2

you can't call something you haven't defined yet, well, that would be a bit of a lie, see MDN documentation:

scroll down to calling functions section. using Function declarations you can call the function before defining the function. This has to do with how the different functions types (declaration vs expressions) are implemented in JS


#3

So it's the difference between function declarations and function expressions? because as I understand functions, when they are called the computer tries to find the memory that the function name is stored that will point it to the body of the function, which the computer then executes. So how come in javascript there is an approach that requires you to define the function first (so the way I did it above) and another way kind of like this?

var answer = prompt("some sort of question");

functionOne(answer);

function functionOne(answer){
switch (answer){
case "yes":
console.log("yes works");
break;

case "no":
    console.log("no works");
break;

case "maybe":
    console.log("maybe works");
break;

default:
    console.log("went to default");
break;

}
};


#4

very good, seems your understanding is fine :slight_smile:

when using Function declarations (function functionOne(answer)) are hoisted to the top of the scope, so they're always available, unlike function expression which are assigned when that line of code executes


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.