Functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(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.
日本語
関数
- 関数は、再度実行可能な名付けられたコードブロックです。
function name(params) { ... return value; }。paramsが入力値です。returnは呼び出した側へ値を返します。
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").
日本語
何かをするだけの関数
- 関数は値を返す代わりに、 something を行う(例:印刷など)ことができます。
- 名前と括弧を書くことで呼び出します:
greet("Ada")。
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
Explore · 探索
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.
日本語
注意
- 括弧内の名前の(
n,name)はパラメータであり、関数の内部でのみ存在します。 returnを与えない関数はundefinedを返します。答えを出したい場合はreturnを加えます。
English
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
日本語
よくあるミス
returnが値を返しますが、与えない場合、関数はundefinedを返します。- 関数に
()を渡して呼び出します。
English
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
日本語
あなたも試してみよう
- 各関数を記述してください(チェックでは自動的に呼び出されます)。
- Check answer を押して確認する。
Write a function double(n) that returns n times 2.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write a function add(a, b) that returns a + b.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。