Tech Junkie Blog: JavaScript Functions

Monday, July 9, 2018

JavaScript Functions

A JavaScript function is a piece of code that is defined once and can be reused through your program.  A function can have arguments or parameters that you can pass into it and returns a value.  If an explicit return value is not specified the return value is "undefined".  During invocation of the function, the function returns the value of "this" keyword, which represents the context of the function.

As you can see a function is a lot like a method.  If a function is defined as a property of an object it is in fact called a method of the object.  It is import to keep in mind that functions in JavaScript are objects and they have the benefits of any objects, meaning they can be self contained, which provide them with a vast amount of flexibility.

The following code is a simple function that adds two numbers together


            
<script>
        function addNumbers(x, y) {
            return x + y;
        }

        console.log("The sum of 1 + 3 is " + addNumbers(1, 3));
</script>






The code above creates a function called addNumbers with two parameters and returns the sum of the two numbers

No comments:

Post a Comment