1. 程式人生 > >Section 2.3 Function

Section 2.3 Function

What’s function

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when “something” invokes it (calls it).

JavaScript Function Syntax:
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas: (parameter1, parameter2, …)

Function Statements and Expressions

Funtion declaration:
This is the function declaration, by using this way, you can call this function in anywhere.

 // No error
  whatDoYouDo ();
  
function whatDoYouDo (job, firstName) {

 }
 
//  No error
 whatDoYouDo ();

Function expression:
This is the function expression, by using this way, you only can call it after this function defined.

// Error undefined
  whatDoYouDo ('teacher', 'John');

var whatDoYouDo = function (job, firstName) {
    switch(job) {
        case 'teacher':
            return firstName + ' teaches in high school.';
        case 'driver':
            return firstName + ' drives high school bus.';
        case 'designer': 
            return firstName + ' designs amazing websites.';
        default:
            return firstName + ' does something else.';
        }
}

  // No error
  whatDoYouDo ('teacher', 'John');

console.log(whatDoYouDo('teacher', 'John')); //result: John teaches in high school.
console.log(whatDoYouDo('designer', 'Nison')); //result: Nison designs amazing websites.
console.log(whatDoYouDo('Accounter', 'Faye')); //result: Faye does something else.

Also the switch statement in above, you can use if else statement to do it. You can try it.

This is a very simple simple example. We can pass argument into a function, we can return result from function with return key words, also function can call other functions.

var now = 2018;

function calculateAge(birthYear) { //function calculateAge(birthYear, x, y)
    return now-birthYear;
}

var ageJohn = calculateAge(1989);
var ageMike = calculateAge(1948);
var ageMary = calculateAge(1996);

console.log("John is " + ageJohn + " years old"); //result: John is 29 years old
console.log("Mike is " + ageMike + " years old"); //result: Mike is 70 years old
console.log("Mary is " + ageMary + " years old"); //result: Mary is 22 years old

How many years X will retire. Here we will create a function and call it to get the results. Function can call other functions.

function yearsUntilRetirement (year, firstName) {
    var age = calculateAge(year);
    var retirement = 65 - age;
    if (retirement > 0 ){
    console.log(firstName + " retires in " + retirement + " years.")
} else {
    console.log( firstName + " is alreay retired.")
}
}

yearsUntilRetirement(1989, 'Alan');  //We will pass two values (number, string) to the function
yearsUntilRetirement(1949, 'Faye');