iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0

What is function?

  • Simple explanation: when you find out that you’re repeating calculating a value, you may need a function.
  • Pro explanation: "Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it."
    by Mozilla

JS built-in function

Example
n1=Number(n1);
alert(“Byebye Covid-19”);

Design a function

function test(message) {
   alert(message); //→ This is a function body; message is an argument name.
}

Calling single functions

"Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.
Calling the function actually performs the specified actions with the indicated parameters."
by Mozilla

As a result, to execute the function above, we have to call it:
test(“Byebye Covid-19”); → “Byebye Covid-19” is the argument inputted to the function.
test(“Welcome to the 2.0 world”); → We can call the functions multiple times.

Calling multiple functions

Example 1. a simple version

function add(n1,n2) {
    alert(n1+n2);
}
add(1,100);
add(2,200);

=> result = 20402

Example 2. return function

function add(n1,n2) {
    alert(n1+n2);
    return n1+n2; //→ means it's finished
}
var result=add(1,100)*add(2,200);
alert(result);

=> result = 20402

Final example integrating the functions above

  • while loop
function getSum(max){
    sum=0
    var n=1;
    while(n<=max){
        sum+=n;
        n++;
        
    }
    alert(sum);
    return sum;
}
var result=getSum(50)*getSum(100);
alert(result);
  • for loop
function getSum(max){
    sum=0
    for(var n=1;n<=max;n++){
    sum+=n;
    }
    alert(sum);
    return sum;
}
var result=getSum(50)*getSum(100);
alert(result);

=> result = 1275, 5050, 6438750


Music of Today: 在這座城市遺失了你 Where I Lost Us by 告五人 Accusefive

Yes


Like/Share/Follow

Feel free to comment and share your ideas below to learn together!
If you guys find this article helpful, please kindly do the writer a favor — LIKE this article./images/emoticon/emoticon12.gif


上一篇
#17 JS: loop - Part 2
下一篇
#19 JS: Modified functions & how function create spaces
系列文
Learn & Play JavaScript -- Entry-Level Front-End Web Development30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言