Javascript passing functions explanation

can someone explain this a little better?

A parameter is a named variable inside a function’s block which will be assigned the value of the argument passed in when the function is invoked:

https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-functions/lessons/functions/exercises/review-functions

I understand the syntax of creating functions but passing information from the function parameter ( ) to the code block { } within the function confuses the ■■■■ out of me. Can someone help me understand this?

Thanks

Hi there.

For the purposes of example, let’s define a fairly basic function. :slight_smile:

function mySimpleFunction(exampleParameter) {
    console.log(`Your parameter value was ${exampleParameter}!`);
    return 0;
}

You can think of the parameter in the function, exampleParameter, as being a variable which is only accessible inside of the function codeblock.

When you call the function, you provide the parameter and so give that variable value:

function mySimpleFunction(exampleParameter) {
    console.log(`Your parameter value was ${exampleParameter}!`);
    return 0;
}

mySimpleFunction("a basic example!"); // output: Your parameter value was a basic example!!

You can manipulate the parameter inside the codeblock as well:

function mySimpleFunction(exampleParameter) {
    originalParameter = exampleParameter;
    exampleParameter = "reassigned inside the function";
    console.log(`Your parameter value was ${exampleParameter}!`);
    return 0;
}

mySimpleFunction("a basic example!"); // output: Your parameter value was reassigned inside the function!

What you can’t do, because the parameter only exists inside the function - or “within the scope” of the function - is use it outside:

function mySimpleFunction(exampleParameter) {
    console.log(`Your parameter value was ${exampleParameter}!`);
    return 0;
}

mySimpleFunction("a basic example!"); // output: Your parameter value was a basic example!!
console.log(exampleParameter); // output: ReferenceError: exampleParameter is not defined

This is a very basic example, but hopefully it’s cleared the concept up a bit? :slight_smile:

1 Like

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