You Don’t Know JS: Up & Going Chapter 1: Into Programming

Shuma Mizuno
Sep 8, 2018 · 13 min read

学習日: 180909
所要時間: 14時間

Code

プログラムはコンソールに入力することもできる。
通常テキストファイルに保存して実行する。

有効なフォーマットと組み合わせルールのことを
・computer language
・syntax

と呼ぶ。

Statements

特定のタスクを実行する単語、数字、演算子のグループのことをstatement(文)と呼ぶ。

a = b * 2;

a and b: 変数/Variables
2 : 値/Value
= *: 演算子/Operators

JavaScriptのほとんどの文は最後はセミコロンで終わる。

Expressions

文は1つ以上の式で構成される。

a = b * 2;

2: value expression
b: variable expression
b * 2: arithmetic expression
a = b * 2: assignment expression

b * 2;

だけだと実行されないので式分の形にする。

alert( a );

Executing a Program

コンピューターに何をどう実行してもらうか、伝える必要がある。

プログラミング言語は、人間にとってわかりやすい形だがコンピューターはそのままの形では認識できない。

コンパイラ または インタプリタを利用して
2進数のコンピューターがわかるコードに変換する。

インタプリタ
プログラム実行時に変換する

コンパイラ
事前に変換する

JavaScriptはインタプリタ言語と言われているが
正確にはJavaScriptエンジンが即座にコードをコンパイルしてその結果を見ている。

Try It Yourself

Output

 console.log(..)

console.オブジェクト
log(..) 関数

Input

age = prompt( “Please tell me your age:” );console.log( age );

prompt(..) 関数はポップアップを表示する。

この場合だとprompt(..)"Please tell me your age:" が投げられてるのでこれがポップアップで表示される。

input textに入力したものはageに格納され、その後 console.log(..)を使ってコンソールに表示される。

Operators

演算子は、変数と値をどのよう実行するか決めるもの。

* 値をかける。
= 値を代入する。

“=” は右側で計算をおこなってから、左側に値を代入する。

a = 2;
b = a + 1;

上から順に変数の値がかわる。
最終的にbの値は3になる。

var a = 20;

a = a + 1;
a = a * 2;

console.log( a ); // 42

変数には宣言が必要。

JavaScriptで一般的によく使われる演算子

・代入:=

・数式: + (乗算), - (減算), * (加算), /(除算)

・複合代入:+=, -=, *=, /=

・インクリメント/デクリメント: ++ , --

・オブジェクトプロパティアクセス: .

・等号: == (等価), === (厳密等価), != (不等価), !== (厳密不等価)

・不等号: < (大なり), > (小なり), <= (以上), >= (以下)

・論理演算子: && (かつ), || (または)

Values & Types

値によって異なる表現は、type(型)と呼ばれる。
JavaScriptはプリミティブ型と呼ばれるbuilt in typeをもっている。

プリミティブ型には数値、文字列、真偽値などがある。

数値: number
文字列:string
真偽値:boolean

リテラルとはスクリプト中に直接記述するデータの値のこと。
例えば文字列リテラルだと"..." or '...'という表現。

"I am a string";
'I am also a string';

42;

true;
false;

プログラミング言語では、文字列/数値/真偽値以外にも、配列、オブジェクト、関数などが提供されることが一般的。

Converting Between Types

型の変換をJavaScriptではコリジョンと呼ぶ。

JavaScriptは、いくつかの異なる機能を提供している。

var a = "42";
var b = Number( a );

console.log( a ); // "42"
console.log( b ); // 42

組み込み関数であるNumber(..)を用いた場合、
他の型から数値型へ明示的な変換が行われる。

"99.99" == 99.99

等価演算子(==)は異なる型であった場合、
同じ型になるように暗黙的な変換をしてから比較を行う。

"99.99"99.99に型変換が行われ、結果はtrueになる。

このルールを把握しておくことは、意図しないバグを防ぎ、良いプログラムを書く手助けとなる。

Code Comments

コード内のコメントは人間になにかを説明するためのもの。

コンパイラ またはインタプリタはコメントを無視するのでコンピューターは認識しない。

  • コメントなしのコードは最適ではない
  • コメントが多すぎるのはよくないコードを書いているという証とも言える
  • コメントはwhatではなくwhyを説明する。特別必要な場合のみhowを書いても良い。
// This is a single-line comment/* But this is
a multiline
comment.
*/

1行の場合 //
複数行の場合/* .. */

Variables

JavaScriptは動的型付け言語に分類され、変数はあらゆる型の値を保持できる。

var TAX_RATE = 0.08;	// 8% sales tax

var amount = 99.99;

amount = amount * 2;

amount = amount + (amount * TAX_RATE);

console.log( amount ); // 215.9784
console.log( amount.toFixed( 2 ) ); // "215.98"

変数の使いみちは、値の設定をまとめること。
変数で定義することでプログラム全体に0.08の値が出現することなく、すべてを更新することができる 。

// as of ES6:
const TAX_RATE = 0.08;

var amount = 99.99;

// ..

プログラム中で値を変化させたくない時には、
再代入ができないconstを使う。

Blocks

1つ以上の文をグループ化したものをBlockと呼ぶ。

var amount = 99.99;

// a general block
{
amount = amount * 2;
console.log( amount ); // 199.98
}

対象を{ .. }で囲む。

var amount = 99.99;

// is amount big enough?
if (amount > 10) { // <-- block attached to `if`
amount = amount * 2;
console.log( amount ); // 199.98
}

blockはif文やloop文などに付属されている。

ブロックで終わる文の末尾には、セミコロンが不要。

Conditionals

if文はよく使われる条件分岐の1つ。
条件がtrueなら、どうするかを記述する。

var bank_balance = 302.13;
var amount = 99.99;

if (amount < bank_balance) {
console.log( "I want to buy this phone!" );
}

if () 内の条件がtrueだった場合実行される。

const ACCESSORY_PRICE = 9.99;

var bank_balance = 302.13;
var amount = 99.99;

amount = amount * 2;

// can we afford the extra purchase?
if ( amount < bank_balance ) {
console.log( "I'll take the accessory!" );
amount = amount + ACCESSORY_PRICE;
}
// otherwise:
else {
console.log( "No, thanks." );
}

trueでない場合に何かを実行したい場合は、
elseに定義する。

if以外にも、 switch文や loop文などがある。

Loops

指定した条件を満たすまで繰り返し行う処理のことをループと呼ぶ。

while do..while は、条件式がfalseになるまでblock内の処理を繰り返す。

while (numOfCustomers > 0) {
console.log( "How may I help you?" );

// help the customer...

numOfCustomers = numOfCustomers - 1;
}

// versus:

do {
console.log( "How may I help you?" );

// help the customer...

numOfCustomers = numOfCustomers - 1;
} while (numOfCustomers > 0);

whileは、条件が一致してるか先に判断し、falseの場合は何もせず終了する。

do-whileはdo {} に記述したコードが実行された後に、条件を判断する。

var i = 0;

// a `while..true` loop would run forever, right?
while (true) {
// stop the loop?
if ((i <= 9) === false) {
break;
}

console.log( i );
i = i + 1;
}
// 0 1 2 3 4 5 6 7 8 9
for (var i = 0; i <= 9; i = i + 1) {
console.log( i );
}
// 0 1 2 3 4 5 6 7 8 9

forループのほうが、while文よりコンパクトで、理解して書くのが簡単。

Functions

関数は、再利用する処理を定義して使い回すために用いる。

function 関数名 ()と書き、{}の中にその関数で実行させたい処理を書く。
{}の後にセミコロンは不要。

function printAmount() {
console.log( amount.toFixed( 2 ) );
}

var amount = 99.99;

printAmount(); // "99.99"

amount = amount * 2;

printAmount(); // "199.98"

関数内のコードは呼び出されるたびに毎回実行される。

function printAmount(amt) {
console.log( amt.toFixed( 2 ) );
}

function formatAmount() {
return "$" + amount.toFixed( 2 );
}

var amount = 99.99;

printAmount( amount * 2 ); // "199.98"

amount = formatAmount();
console.log( amount ); // "$99.99"

引数を使って、戻り値を取得することや
パラメーターを渡すこともできる。

const TAX_RATE = 0.08;

function calculateFinalPurchaseAmount(amt) {
// calculate the new amount with the tax
amt = amt + (amt * TAX_RATE);

// return the new amount
return amt;
}

var amount = 99.99;

amount = calculateFinalPurchaseAmount( amount );

console.log( amount.toFixed( 2 ) ); // "107.99"

calculateFinalPurchaseAmount(..)は一度しか呼ばれないが、
2つのfunctionに分けることで、コードの見通しが良くなる。

Scope

変数の有効範囲のことで、プログラムのどの場所から参照できるかを決める。

function one() {
// this `a` only belongs to the `one()` function
var a = 1;
console.log( a );
}

function two() {
// this `a` only belongs to the `two()` function
var a = 2;
console.log( a );
}

one(); // 1
two(); // 2

別のスコープ内であれば同じ名前の変数を使える。

function outer() {
var a = 1;

function inner() {
var b = 2;

// we can access both `a` and `b` here
console.log( a + b ); // 3
}

inner();

// we can only access `a` here
console.log( a ); // 1
}

outer();

入れ子にすることもできる。

inner()
関数内のコードは変数aとbの両方にアクセスできる。

outer()
コードはaのみにアクセスできる。

質問事項

特になし

所感

課題以外の関係ない記事をたくさん読んで
時間かかりすぎてるの良くない。

メモ

ECMAScript 2018時代のJavaScript入門書
https://asciidwango.github.io/js-primer/

JavaScriptのレベル別書籍のまとめhttps://gist.github.com/azu/027859e08e284cb8dfe7

これから学ぶ初心者必見!!プログラミング言語の違いhttp://webukatu.com/wordpress/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E%E3%81%AE%E9%81%95%E3%81%84/

プリミティブ型とオブジェクト型
https://qiita.com/makotoo2/items/9566cebf205ef8b42505

5つの基本型とオブジェクト型 JAVASCRIPTの型
http://kaihooo.com/javascript-type/

    Shuma Mizuno

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade