LoginSignup
0
2

More than 3 years have passed since last update.

JS基礎文法~関数~

Last updated at Posted at 2021-04-29

概要

関数についての記事です。
引数、仮引数について取り上げて行きます。

関数

関数とは様々な処理を1つの命令にまとめることができます。

index.js
function show() {
  console.log('A');
  console.log('B');
  console.log('C');
}

show();

関数は、functionに名前を付けます。今回は、名前を付けます。
関数の中の処理を呼び出すためには関数名();とすることで呼び出すことができます。

index.js
 console.log('------');
 show();
 console.log('------');
 show();
 console.log('------');

スクリーンショット 2021-04-29 17.52.23.png

このように関数化することで、後で内容を変更する必要があるときにメンテナンスが楽になりますね。

index.js
for(let i = 0; i <= 4; i++) {
 show();
}

ページ内であれば、呼び出すことができます。

仮引数,実引数

index.js
function show(msg) {//仮引数
  console.log('A');
  console.log(`--${msg}--`);
  console.log('C');
}

console.log('------');
show('hey');//実引数
console.log('------');
show('hello');
console.log('------');

また関数を呼び出す際に値を渡すことができます。これを実引数と言います。
そして元の値に仮置きする値を仮引数といいます。

スクリーンショット 2021-04-29 18.15.41.png

return

index.js
function total (a,b,c) {
  console.log(a * b * c);
}

total(2,4,6); //48
total(5,3,8); //120

これを合算したいと思います。

index.js
function total (a,b,c) {
  console.log(a * b * c);
}

const aaa = total(2,4,6); //48
const bbb = total(5,3,8); //120

const totalNum = aaa + bbb;
console.log(totalNum);

結果はNaNでした。
これは数値を求める計算で結果が数字にならないときに現れます。
この関数では、結果を返しているからです。その場合はreturnを使います。関数を実行して返ってくる値です。
returnを使うことで、関数を式に入れて使うことができます。

index.js
function total (a,b,c) {
 return a * b * c;
}

const aaa = total(2,4,6); //48
const bbb = total(5,3,8); //120


const totalNum = aaa + bbb;
console.log(totalNum);

先程の計算式の結果は168でした。

index.js
function name() {
   return
}

console.log(name());

undefinedが返ってきます。これは未定義という意味です。

またreturnの後に処理を記述しても実行されません。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2