Newer
Older
hello-programmer-world / src / pages / js / 01-foundation.mdx
@h.sakamoto h.sakamoto 21 days ago 9 KB toc
---
layout: "@/layouts/MarkdownLayout.astro"
---

export const title = "わかっている人向けの基礎";

# {title}

## TOC

## 型

### プリミティブ型

#### Number型

```js
// 整数
console.log(typeof 123); // "number"
console.log(typeof -123); // "number"

console.log(typeof 0x1A); // "number"  // 16進数
console.log(typeof 0b0101); // "number"  // 2進数
console.log(typeof 0o755); // "number"  // 8進数

// IEEE 754 倍精度浮動小数点数
console.log(typeof 3.14); // "number"
```

#### BigInt型

```js
const bigInt = 9007199254741991n; // 任意精度整数 ( BigInt )
console.log(typeof bigInt); // "bigint"
```

#### Boolean型

```js
console.log(typeof true);  // "boolean"
console.log(typeof false); // "boolean"
```

#### String型

```js
console.log(typeof "Hello, World!"); // "string"
console.log(typeof 'JavaScript');    // "string"

const multiLine = `これは
複数行の
文字列です。`;
console.log(typeof multiLine); // "string"

// テンプレートリテラル
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"
console.log(typeof greeting); // "string"
```

#### Symbol型

```js
const sym = Symbol("uniqueIdentifier");
console.log(typeof sym); // "symbol"
```

#### Null型

```js
const emptyValue = null;
console.log(typeof emptyValue); // "object" (歴史的な理由による)
```

#### Undefined型

```js
const notAssigned = undefined;
console.log(typeof notAssigned); // "undefined"
```

### オブジェクト型 (狭義)

JavaScriptでは、プリミティブ型以外のすべての値はオブジェクト型に分類されます。  
この`Object型`セクションでは、代表的なオブジェクト型を紹介します。

#### Object

```js
const obj = new Object();
obj.name = "Bob";
obj.age = 25;

console.log(obj); // { name: "Bob", age: 25 }
console.log(obj.name); // "Bob"
console.log(obj["age"]); // 25
console.log(obj.someField); // undefined


const obj2 = {
  name: "Charlie",
  age: 28
};

console.log(obj2); // { name: "Charlie", age: 28 }
```

#### Class

JavaScriptでは、他の言語でいうところの`public`や`private`などのアクセス修飾子は存在しません。

```js
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;

    greet() {
      console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
  }
}

const alice = new Person("Alice", 30);
console.log(alice); // Person { name: "Alice", age: 30 }
console.log(alice.name); // "Alice"
console.log(alice.greet()); // "Hello, my name is Alice and I am 30 years old."
```

#### Array

```js
const list = [1, 2, 3, 4, 5];
console.log(typeof list); // "object"

const list2 = new Array(1, 2, 3, 4, 5);
console.log(typeof list2); // "object"
```

#### RegExp

```js
const pattern = /ab+c/i;
console.log(typeof pattern); // "object"

const pattern2 = new RegExp("ab+c", "i");
console.log(typeof pattern2); // "object"
```

## 関数

宣言

```js
function add(a, b) {
  return a + b;
}

const sub = (a, b) => {
  return a - b;
}
```

複数の型を返すことが可能

```js
function getValue(flag) {
  if (flag) {
    return 42; // Number型
  } else {
    return "Hello"; // String型
  }
}
```

## コメント行

JavaScriptでは、以下の3つの方法でコメントを記述できます。

```js
// これは1行コメントです。

/*
これは複数行に
渡るコメントです。
*/

const value = 100;

/**
 * これはドキュメンテーションコメントです。
 * @param {string} name - 挨拶する相手の名前
 */
function greet(name) {
  // 挨拶を表示する
  console.log("Hello, " + name + "!");
}
```

## 標準出力

Developper Toolsなどのコンソールに出力します。

```js
console.log("Hello, World!");

// エラーレベルを分けて出力することもできます。
console.warn("This is a warning message.");
console.error("This is an error message.");
console.info("This is an informational message.");
console.debug("This is a debug message.");

// objectや配列を見やすく表示することもできます。
console.table({
  name: "Alice",
  age: 30,
  city: "New York"
});
```

## 変数

### 特別な変数

#### window

`window`はブラウザの最上位オブジェクトで、グローバルスコープに存在します。  
ブラウザ環境でJavaScriptを実行すると、`window`オブジェクトにはブラウザが提供する多くの機能が含まれています。

#### document

ブラウザに表示されているHTMLの全体を表すオブジェクトです。  
ここからHTML要素を取得したり、操作したりできます。

```html
<div id="example">Hello, World!</div>

<script>
  const element = document.getElementById("example");
  console.log(element.innerHTML); // "Hello, World!"
</script>
```

### 変数の宣言

`var`、`let`、`const`の3つのキーワードで変数を宣言できます。

| キーワード | スコープ | 再代入 | 再宣言 |
| :---------- | :------- | :----- | :----- |
| `var`       | 関数スコープ | 可能   | 可能   |
| `let`       | ブロックスコープ | 可能   | 不可   |
| `const`     | ブロックスコープ | 不可   | 不可   |

`var`は関数の外側で宣言すると、その値は`window`オブジェクトのプロパティとして登録されます。

```js
var func = () => {
  return "Hello, Function!";
}

console.log(func()); // "Hello, Function!"
console.log(window.func()); // "Hello, Function!"
console.log(func === window.func); // true
```

`var`は外部のライブラリを登録するときなどに使われます。  
誤って同じ名前で変数を宣言すると、そのライブラリを上書きすることになるので注意が必要です。

```html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
console.log(typeof windiw.jQuery); // "function"
console.log(jQuery.find("body")); // body要素を取得

var jQuery = "This will overwrite jQuery!";
console.log(typeof window.jQuery); // "string"
console.log(jQuery.find("body")); // エラー
</script>
```

## HTMLの操作

### 要素を取得する

#### IDで取得

```html
<div id="myElement">Hello, World!</div>

<script>
  const element = document.getElementById("myElement");
  console.log(element.innerHTML); // "Hello, World!"
</script>
```

#### class名で取得

```html
<div class="myClass">Item 1</div>
<div class="myClass">Item 2</div>
<div class="myClass">Item 3</div>

<script>
  const elements = document.getElementsByClassName("myClass");
  console.log(elements.length); // 3
  console.log(elements[0].innerHTML); // "Item 1"
</script>
```

#### query Selectorで取得

```html
<div class="container">
  <p class="text">Paragraph 1</p>
  <p class="text">Paragraph 2</p>
</div>

<form>
  <input type="text" />
  <input type="password" />
</form>

<script>
  const firstParagraph = document.querySelector(".container .text");
  console.log(firstParagraph.innerHTML); // "Paragraph 1"

  const allParagraphs = document.querySelectorAll(".container .text");
  console.log(allParagraphs.length); // 2
  console.log(allParagraphs[1].innerHTML); // "Paragraph 2"

  const passwordInput = document.querySelector("form input[type='password']");
  console.log(passwordInput.type); // "password"
</script>
```

#### 要素を追加

```html
<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<script>
  const list = document.getElementById("myList");

  // 新しい要素を作成
  const newItem = document.createElement("li");
  newItem.innerHTML = "Item 3";

  // 要素を追加
  list.appendChild(newItem);
  console.log(list.innerHTML);
  // <li>Item 1</li><li>Item 2</li><li>Item 3</li>
</script>
```

#### 要素を削除

```html
<ul id="myList">
  <li>Item 1</li>
  <li id="itemToRemove">Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const itemToRemove = document.getElementById("itemToRemove");

  // 親要素を取得
  const parent = itemToRemove.parentNode;
  // 要素を削除
  parent.removeChild(itemToRemove);
  console.log(document.getElementById("myList").innerHTML);
  // <li>Item 1</li><li>Item 3</li>
</script>
```

## イベント

### イベントの登録

HTML属性で直接登録する方法もあります。

```html
<button onclick="alert('Button was clicked!')">Click Me!</button>
```

JavaScriptでイベントリスナーを登録する方法が一般的です。j

```html
<button id="myButton">Click Me!</button>

<script>
  const button = document.getElementById("myButton");

  // クリックイベントを登録
  button.addEventListener("click", () => {
    alert("Button was clicked!");
  });
</script>
```

同時に複数のイベントリスナーを登録することも可能です。

```html
<button id="myButton">Click Me!</button>

<script>
  const button = document.getElementById("myButton");

  function handleClick1() {
    alert("Button was clicked!");
  }

  function handleClick2() {
    console.log("Button click logged.");
  }

  button.addEventListener("click", handleClick1);
  button.addEventListener("click", handleClick2);
</script>
```

### イベントの削除

`onRemoveEventListener`メソッドを使って、登録したイベントリスナーを削除できます。  
例のように、1度だけ実行したい場合などに使えます。

```html
<button id="myButton">Click Me!</button>

<script>
  const button = document.getElementById("myButton");
  function handleClick1() {
    alert("alert only once!");
    button.removeEventListener("click", handleClick);
  }

  function handleClick2() {
    console.log("Button click logged.");
  }

  button.addEventListener("click", handleClick1);
  button.addEventListener("click", handleClick2);
</script>
```''