LoginSignup
1
2

More than 1 year has passed since last update.

Reactを扱う上でのJavascriptの基本(分割代入、スプレッド構文、論理演算子、三項演算子など)

Posted at

最近業務でReactを使用しているが、Jsの基本がわかっていなかったため、コードリーディングに苦労しました。
この記事では、Reactを解読する上で欠かせないJsの構文をまとめたので、よかったら参考にしていただけると幸いです。

分割代入(オブジェクトや配列から値を抽出するためのもの)

オブジェクト(↓name: '桃太郎'のようなプロパティからなる変数を「オブジェクト」という。)

const person = {
  name: '桃太郎',
  age: 13,
  birth_place: " Japan"
}

const { name, age, birth_place } = person

console.log(name) => 桃太郎
console.log(age) => 13
console.log(birth_place) => Japan

配列([]で括り、中に数字や文字列を書き、「,」でつなげたもの)

const array = [ "田中", 21, "北海道" ]

const [ name, age, birth ] = array

console.log(name) => 田中
console.log(age) => 21
console.log(birth) => 北海道

スプレッド構文(配列の要素を展開するためのもの)

const array1 = [ 10, 20, 30, 40, 50 ]

console.log(...array1) => 10 20 30 40 50

スプレッド構文は、配列の要素をまとめて使用することもできる。

const array1 = [ 10, 20, 30, 40, 50 ]

const [ num1, num2, ...array2 ] = array1

console.log(num1) => 10
console.log(num2) => 20
console.log(...array2) => 30 40 50

console.log(array2) => [ 30, 40, 50 ]

論理演算子(&&,||)

| |は、その左側がfalseなら右側を返す。

const judge1 = true

const judge2 = false

if (judge1 || judge2) {
    console.log("judgeのどっちかはtrueだよ。")
}

=> judgeのどっちかはtrueだよ。


if (judge1 && judge2) {
    console.log("judgeのどちらもtrueだよ。")
}

=> undefined



const money = undefined
const pay = money || "お金はないのかな??"
console.log(pay)

=> お金はないのかな??


const money = 1000
const pay = money || "お金はないのかな??"
console.log(pay)

=> 100

&&は、その左側がtrueなら右側を返す。

const money = 500
const pay = money && "お金じゃん!!"
console.log(pay)

=> お金じゃん!!

三項演算子( 条件 ? “trueのとき実行” : “falseのとき実行” )

const num = 5 > 10 ? "大きいやん。" : "小さいやん。"

console.log(num) => 小さいやん。

今回紹介したJsの構文はReactでたくさん使用しているので、よかったら参考に。

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