Functions

函數是設計用於執行特定任務的代碼塊。函數可以幫助組織代碼,避免重複並降低代碼的複雜性。

// Creating the function

    function sum_numbers() {
        var num1 = 5;
        var num2 = 2;
        var sum  = x + y;
        console.log(sum);   
    }

    // The function is only executed after being invoked(被調用):

    sum_numbers(); // The console will show 7

Some important observations about what we've just done:

Function arguments

By using arguments we can make it dynamic動態的 and sum different numbers everytime.

function sum_args(num1,num2) {
        var sum  = num1 + num2;
        console.log(sum); 
    }

    /* Now when invoking the function we can use any numbers we want: */

    sum_args(10,25); // The console will show 35

    sum_args(1000,375); // The console will show 1375

    sum_args(-2,47); // The console will show 45

The return statement

It would be good if our function could return the value so we could do anything we want with it.

function sum_args(num1,num2) {
        var sum  = num1 + num2;
        return sum; 
    }
//Now we can do anything we want with it, like using in other calculations and sending the result to an HTML element.
var average = sum_args(6,10) / 2;

    console.log( sum_args(13,21) );