1
0

More than 3 years have passed since last update.

変数・定数・関数宣言方法

Posted at

変数の書き方

const testScope = (scope) => {
  if (scope === 'block') {
    let message = 'ブロックスコープ'
    console.log(message)
  }
  // console.log(message)//letの場合ブロック内{}のみ参照可能
//よってこちらはエラーになります
//ReferenceError: message is not defined 
}
testScope('block')

let mutableText = 'let変更前';
mutableText = 'let変更後';  //再代入可能
console.log(mutableText);

定数の書き方

const immutableText = 'const変更前';
immutableText = 'const変更後' //再代入不可
console.log(immutableText);

const mutableArray = [1,2,3];
mutableArray.push(4)
console.log(mutableArray);//結果[1,2,3,4]
配列やオブジェクトは定数宣言しても変更可能

const mutableObject = {id: 'hoge', value: 'fuga'}
mutableObject['name'] = 'bar'
console.log(mutableObject)
//結果 
Object {
  id: "hoge",
  name: "bar",
  value: "fuga"
}

アロー関数の書き方

function nameFunc(message){
  console.log(message)
}

nameFunc('これは名前付き関数です')

const arrowFunc = (message) => {
  console.log(message)
}

arrowFunc('これはアロー関数です')

const oneLineArrowFunc = (message) => console.log(message);
oneLineArrowFunc('これは1行で書いたアロー関数です')

const users = {
  hoge: 'Hallo Bob' //hogeというユーザーIDはHallo Bobというユーザーネームを持っている
}
const getUsername = (userId) =>{
  return users[userId]; //returnを省略できる
} 
const username = getUsername('hoge')
console.log(username)


getUsernameという関数を実行
getUsernameにはhogeという文字列を渡した
関数の中でhogeがuserIdとして引数で渡されて
usersっていうオブジェクトのhogeというキーの値を返すという形になります。
usersのhogeというキーはvalueはHallo Bob

ざっくりですが復習しました。

1
0
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
1
0