Anatomy of a JavaScript function

Before we get to the anatomy of a JavaScript function, I learned an important distinction about the scope of variables in JS today. While a variable defined in a block is local to itself and whatever context it is local to, a variable defined in a function is local only to that function. This means the variable cannot be accessed outside the function, which is great, because it negates problematic side-effects, such as unintended reassignment of variables. In other words, functions constrain the namespace of the variables they hold.

And now… a simple recipe for a JavaScript function that finds the absolute value of a number (num).

1. Declare a function and assign it a variable name. Use the keyword function, followed by parentheses:

    function absolute();

2. Parentheses serve as a container for possible arguments. If you want to use arguments, now would be good time to place them inside the parentheses.

    function absolute(num);

2. Wrap the entire body of the function in curly brackets.

    function absolute(num) {
    //I’m the body
    }

3. When using conditionals, wrap each conditional in parentheses.

    function absolute(num) {
    if (num > 0) // wrap me, i’m a condtional
    }

4. Separate control flow statements with curly brackets. In this case, if a number is less than zero, we return it’s opposite value, i.e., its absolute value.

Note: A closing curly bracket implicitly tells JavaScript that it has reached the end of a line, so no semicolon is needed after it. A semicolon must be placed at the end of all other lines.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s