#18 JS: Intro to function

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


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


<<:  D18 - 如何用 Apps Script 自动化地创造与客制 Google Docs?(五)Element 的更新

>>:  自学教材选择

以Postgresql为主,再聊聊资料库 typed table的应用

上一篇介绍了 create type,以及 typed table. 本篇介绍应用,这次就不做复合型...

[区块链&DAPP介绍 Day23] Dapp 实战 安装 truffle

今天来介绍一下,要开发dapp 的另一个不可或缺的工具 truffle truffle 跟之前介绍的...

【Day01】JavaScript 是如何运行的

程序语言的运行过程 在知道如何运行之前,必须先了解程序语言是如何被运行的。 程序语言依照运行方式可分...

DAY24神经网路(续二)

昨天介绍完单层感知机模型程序,今天要来研究浅层神经网路: 单层感知机模型是只有一个输入层和输出层,如...

Day7 - 程序设计报价 (二) - 重新定义甲乙关系

从传统的接案甲乙方关系我们发现,因为利益的冲突,甲方也不可能得到乙方 100% 的专业协助,因为乙方...