[Learning] #18 JS: Intro to function

Vida Lin
2 min readOct 6, 2021

--

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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vida Lin
Vida Lin

Written by Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

No responses yet

Write a response