此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Functions
- A function is a named block of code you can run again and again.
function name(params) { ... return value; }. Theparamsare the inputs.returnhands a value back to whoever called the function.

English
function square(n) {
return n * n;
}
console.log(square(6)); // → 36
English
Functions that just do something
- A function can do something (like print) instead of returning a value.
- Call it by writing its name and brackets:
greet("Ada").
English
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
探索
Call and return
Each call runs the body with its own input, then return hands a value back.
English
Watch out
- The names in the brackets (
n,name) are parameters — they only exist inside the function. - A function with no
returngives backundefined. Addreturnwhen you want an answer out.
English
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
English
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function double(n) that 返回值 n times 2.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function add(a, b) that returns a + b.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada.
点击“运行”查看此处输出。