# 便利だと感じたES記法とかテクニックいくつか
はじめに: この記事は田胡研アドベントカレンダー2016 25日目の記事です.
こんにちはフロント駆け出しエンジニアのnamazuです.
今日は最近JavaScriptを書いていて便利だと感じた記法をもう一度ちゃんと調べるためにもいくつか紹介していきたいと思います.
ES6の記法だったりもするのでブラウザで使うには[Babel](https://babeljs.io/)を通してくださいね(´・ω・`)
# const,let
定数とスコープを限定する変数の定義が可能です.
varは捨ててこっちを使うといいですね.
constとimutabule.jsを組み合わせて安全なJSプログラミングをしましょう.
```js
// 参照変更不可
const HOGE = 'hoge'
{
let fuga = 'fuga'
}
// undefined
console.log(fuga)
```
[MDN const](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/const)
[MDN let](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/let)
# アロー関数式
```js
var f = function (msg) {
console.log('hoge')
}
f()
```
と書いていたのが
```js
var f = (msg) => {
console.log(msg)
}
f()
```
と書けるようになりました. ついでにthisをうまく束縛できます.
functionと連打しなくてよくなって見た目がよくなりましたね!
注意ですが、prototypeベースのクラス定義をしているときにアロー関数を使うと関数内のthisがグローバル(関数を定義したところのコンテキスト=普通グローバル)になります. 稀に嵌るので気を付けましょう.
[MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/arrow_functions)
# 分割代入
importとかで何だかんだ使ってしまっていたりする記法で便利なのでよくわからないまま使っていることが多い記法です.
知っておくと便利です
普通に使うときに一番便利だったのはネストの深いオブジェクトを簡単に引く時で
```js
const store = {
state: {
information: {
title: 'hoge',
summry: 'fuga'
}
}
}
// のようなオブジェクトがあったとして
// stote.state.information.title と summeryを参照するとき
const {title, summery} = store.state.inforamtion
console.log(title) // => hoge
console.log(summery) // => fuga
```
こんな例があります.
他にも関数に簡単に引数渡したりとかするときに使えます.
[MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
# クラス構文
今までprototypeをうまく使ってクラス作ってきましたがclass構文が最近は使えます. ただこの構文シュガーシンタックスなのでいままでと中身は違いません.
prototypeベースのクラスの作り方は[ここ](http://www.yunabe.jp/docs/javascript_class_in_google.html)とか見るといいかもしれません.
これまで面倒だったのが
```js
class Human{
constructor(name, age) {
this.name = name
this.age = age
}
speak() {
return `こんにちは${name}です. ${age}歳です.`
}
}
const human = new Human('hoge', 20)
console.log(human.speak()) // => こんにちはhogeです. 20歳です.
```
こんな感じで簡単に行けます. extendsとかもちゃんとあります. jsでも十分強力ですがTypescriptとかだともっと威力発揮します.
# 式展開
JSにも式展開があります. 'をやめて`でくくるのを忘れないでください.
```js
const hour = 20
console.log(`今は${hour}時です.`)
```
# デフォルト引数定義
いままでよく
```js
const f = function (msg) {
msg = msg || 'hoge'
reutrn msg
}
console.log(f()) // => hoge
```
みたいなことをしてundefined対策をしていました.
このhogeみたいなのをデフォルトで定義できます.
```js
const f = function (msg = 'hoge') {
return msg
}
```
こんな感じに.
[MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions_and_function_scope/Default_parameters)
便利記法は山ほどQiitaに記事があるのでこれくらいにします.
いくつかもしかしたら便利かもしれないJSテクを紹介していきます
# 連想配列の値ベースで配列を検索する
```js
const array = [
{
id: 1,
title: 'hoge'
},
{
id: 2,
title: 'huga'
},
{
id: 3,
title: 'saga'
}
]
// こんなarrayがあったとします
// ここからid=2のtitleをhugahugaに置き換えたいと考えます.
// 配列の何番目にid2のオブジェクトがあるかわからないとします.
// そんなとき
const i = array.map(v=>v.id).indexOf(2)
if (i > -1 ) {
array[i].title = 'hugahuga'
}
// こうします
```
検索対象のプロパティだけの配列を写像して作成しそこからindexOfで何番目か求めます,
indexがわかったら元の配列に添え字アクセスし書き換えます.
もっといい方法あったら教えてくれると幸いです.
# 即時関数を短く
即時関数は名前空間区切るために使うあれ (function(){})() ですねあれを短くします.
```js
+function(){console.log('hoge')}()
```
+とか演算子をつけると即時実行できます. +じゃなくても!とかもろもろで動きます.
テクなんかではなくてただの闇記法ですね bootstrapの中に存在するって聞いたことがあります.
# ArrayLikeObjectをなめる
dom操作は人のすることじゃなくなったから最近はほぼ使わないけど
documet.querySelectorAll('.hoge') みたいなので帰ってきた配列をなめるときに使うテク.
そのままforEachすると回せないので...
```js
[].prototype.forEach.call(document.querySelectorAll('.hoge'), function(node) {
node.innerText = 'hogehoge'
})
```
こうすると回る. ほかにもいろいろこれをやる闇っぽいテクがあります.
# 終わりに
今回は最近好きなES記法ともしかしたらためになるかもしれないのコーディング例を示しました.
便利記法は今回紹介しただけにとどまらず大量にあるのでまた機会あったら書けたらなと思います. JavaScript好きな人が増えるといいな(´・ω・`)
あとこのコーディングすげぇってコード見かけたらぜひ教えてくれるとありがたいです.
そういえば今日はクリスマスです,昨日も今日も私は家でコード書いてました. ひきこもるのもよろしくないと思うので今夜はどこか一人で食べに行こうと思います.
それでは.
I’m excited to uncover this page. I need to thank you for your time for this, particularly fantastic read!! I definitely really liked every part of it and I also have you saved to fav to look at new information in your site.
返信削除CCNA classes in Solapur
CCNA classes in Aurangabad
CCNA classes in Satara
CCNA classes in Nashik
Very interesting post
返信削除SevenMentor
This is quite a good blog. Keep sharing. I love them. Are you also searching for cheap thesis writing services ? we are the best solution for you. We are best known for delivering nursing paper writing services to students without having to break the bank.
返信削除Your blogs are great.Are you also searching for Nursing term paper help? we are the best solution for you. We are best known for delivering great term paper services :+1-(951)-468-9855
返信削除스포츠토토
返信削除먹튀검증
Impressive web site, Distinguished feedback that I can tackle. I am moving forward and may apply to my current job which is very enjoyable, but I need to additional expand.
바카라사이트
返信削除카지노사이트
Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next post thanks once again.
You are wonderful! Thanks! I will definitely comeback.
返信削除토토사이트
배트맨토토프로
Giant Carpet Cleaner Rental– Giant food has become one of the most trusted stores for shopping for household items, thanks to its wide selection of services and products specifically designed to help create better living spaces.
返信削除Some benefits of using ES notation include better code organization, improved readability, and increased maintainability. By using modern ES features like arrow functions, destructuring, and template literals, you can write cleaner, more concise code that's easier to understand and debug. If you're new to ES notation or looking to brush up on your skills, there are plenty of resources available online. Some popular ones include the MDN web docs and the ES6 Features website. Additionally, many modern JavaScript frameworks and libraries like React and Vue.js rely heavily on ES notation, so learning it can be an important investment in your future as a frontend developer.
返信削除I ordered this jacket from America Jackets and I must say I am amazed with the high quality and fit. You guys can also try it. Arkham Knight Red Hood Leather Jacket
返信削除