おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第51弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Basic JavaScriptの中の、
Understanding Undefined Value returned from a Function
です。
さっそく見ていきましょう。
まずは本文から。
A function can include the
return
statement but it does not have to. In the case that the function doesn’t have areturn
statement, when you call it, the function processes the inner code but the returned value isundefined
.Example var sum = 0;function addSum(num) {sum = sum + num;}addSum(3); // sum will be modified but returned value is undefined
addSum
is a function without areturn
statement. The function will change the globalsum
variable but the returned value of the function isundefined
.Create a function
addFive
without any arguments. This function adds 5 to thesum
variable, but its returned value isundefined
.
解説していきます。
前回は関数に「return」を使って処理結果の値を取得する方法について学びましたが、関数に「return」は必須ではありません。
例を見てみましょう。
上記のコードでは最後にaddSum(3);と書かれています。
この結果、sumの値は変化しますが、返される値はundefined
です。(返される値がundefined
でもエラーではありません。)
では課題を見ていきましょう。
引数のない関数addFive
をつくれ。この関数は変数sumに5を追加するが、戻り値はundefined
にしろ。
今回もご丁寧に例があります。
答えはこうです。