LoginSignup
0
1

More than 3 years have passed since last update.

Reactを学ぶ前にJavaScript基礎を学ぶその1

Last updated at Posted at 2021-03-17

はじめに

Rails + Reactでポートフォリオを作ろうと思いReactの勉強を始めたけどJavaScriptの知識があまりにもなかったので、最低限Reactを使うなら知っておいた方がいいJavaScriptの知識をまとめました!

let const

letは変数で上書きが可能。


let hello = "おはよう";
console.log(value);  // =>  おはよう

hello = "こんにちは";
console.log(value); // => こんにちは

constは定数
文字列や数値では宣言した値を変えることはできないがJavaScriptのオブジェクトや配列では値を変更することができる。

・ オブジェクトの場合、nameが変わっている。

const profile = {
  name: "asahi",
  age: 25
};
profile.name = "takesi";

console.log(profile);    // => {name: "takesi", age: 25}

・ 配列の場合、佐藤を山田に変更、佐々木を追加。

const name = ["佐藤","高橋"];
name[0] = "山田";
name.push("佐々木");

console.log(name); // => ["山田", "高橋", "佐々木"]

Reactでは基本constが使われる。

テンプレート文字列

テンプレート文字列は文字列の中にJavaScriptを埋め込むためのもの
バッククフォーテーションと${}で表記する。

const name = "asahi";
const age = 25;
const message = `私の名前は${name}です 年齢は${age}歳です`;

console.log(message); // => 私の名前はasahiです 年齢は25歳です

アロー関数

アロー関数とは=>を使って関数を記述する書き方。

num1とnum2を計算する関数の場合、

const cal = (num1, num2) => {
  return num1 + num2;
}

console.log(cal(6, 4)); // => 10

今回みたいに処理が1行で終わるなら省略して書くこともできる。

const cal = (num1, num2) => num1 + num2;

console.log(cal(6, 4)); // => 10

分割代入

毎回${profile.name}のようにprofileをつけるのは読みにくく書くのも手間なので分割代入を使ってプロパティを抜き出してまとめて定義することで読みやすくなる。

・分割代入なし(オブジェクト)

const profile = {
  name: "asahi";
  age: 25 ;
}

const message = `名前は${profile.name}${profile.age}歳です`

・分割代入あり(オブジェクト)

const profile = {
  name: "asahi";
  age: 25 ;
}
const { name, age } = profile;
const message = `名前は${name}${age}歳です`;

・分割代入なし(配列)

const profile = ["asahi", 25];

const message = `名前は${profile[0]}${profile[1]}歳です`;

・分割代入あり(配列)
配列の場合は代入する順番に注意。

const profile = ["asahi", 25];

const [ name, age ] = profile;
const message = `名前は${name}${age}歳です`;

デフォルト値

JavaScriptでは変数に値が入っていない場合undefinedと判定される。

const hello = (name) => console.log(`こんにちは!${name}さん!`);

hello();
console
こんにちは! undefinedさん! 

=でデフォルト値を設定する。

const hello = (name = "ゲスト") => console.log(`こんにちは!${name}さん!`);

hello();
console
こんにちは! ゲストさん! 

ちなみにhelloの引数に値を入力すると入力した値がきちんと表示される。

const hello = (name = "ゲスト") => console.log(`こんにちは!${name}さん!`);

hello("asahi");
console
こんにちは! asahiさん! 

参考にしたもの

モダンJavaSciptの基礎から始める挫折しないためのReact入門

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