はじめに
JavaScriptはWebブラウザで動作するプログラミング言語です。現在ではNode.jsによりサーバーサイドでも使われています。
変数の宣言
// let - 再代入可能
let name = "太郎";
name = "花子"; // OK
// const - 再代入不可
const PI = 3.14159;
// PI = 3.14; // エラー
// var - 古い書き方(非推奨)
var oldStyle = "避けるべき";
let vs const の使い分け
// 基本的にconstを使う
const MAX_SIZE = 100;
const user = { name: "太郎" };
// 再代入が必要な場合のみlet
let count = 0;
count++;
// オブジェクトのプロパティは変更可能
user.name = "花子"; // OK(オブジェクト自体は同じ)
データ型
プリミティブ型
// 文字列
const str = "Hello";
const str2 = 'World';
const template = `${str} ${str2}`; // テンプレートリテラル
// 数値
const num = 42;
const float = 3.14;
// 真偽値
const isActive = true;
const isDisabled = false;
// null と undefined
const empty = null; // 意図的な空
let notDefined; // undefined(未定義)
// Symbol(ES6)
const sym = Symbol("id");
// BigInt(大きな整数)
const big = 9007199254740991n;
typeof演算子
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"(歴史的バグ)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
演算子
算術演算子
console.log(10 + 3); // 13
console.log(10 - 3); // 7
console.log(10 * 3); // 30
console.log(10 / 3); // 3.333...
console.log(10 % 3); // 1(余り)
console.log(10 ** 3); // 1000(べき乗)
// インクリメント・デクリメント
let n = 5;
n++; // 6
n--; // 5
比較演算子
// 等価(型変換あり)- 使用非推奨
console.log(5 == "5"); // true
console.log(null == undefined); // true
// 厳密等価(型変換なし)- こちらを使う
console.log(5 === "5"); // false
console.log(5 === 5); // true
// 不等価
console.log(5 !== "5"); // true
// 大小比較
console.log(5 > 3); // true
console.log(5 >= 5); // true
論理演算子
// AND
console.log(true && true); // true
console.log(true && false); // false
// OR
console.log(true || false); // true
console.log(false || false); // false
// NOT
console.log(!true); // false
console.log(!false); // true
// 短絡評価
const value = null || "デフォルト"; // "デフォルト"
const name = user && user.name; // userがnullならundefined
Null合体演算子(ES2020)
// nullまたはundefinedの場合のみデフォルト値
const value = null ?? "デフォルト"; // "デフォルト"
const zero = 0 ?? "デフォルト"; // 0(0はnullではない)
文字列操作
const str = "Hello, World!";
// 長さ
console.log(str.length); // 13
// 検索
console.log(str.indexOf("World")); // 7
console.log(str.includes("Hello")); // true
console.log(str.startsWith("Hello")); // true
// 切り出し
console.log(str.slice(0, 5)); // "Hello"
console.log(str.substring(7)); // "World!"
// 変換
console.log(str.toUpperCase()); // "HELLO, WORLD!"
console.log(str.toLowerCase()); // "hello, world!"
// 置換
console.log(str.replace("World", "JavaScript"));
// 分割
console.log("a,b,c".split(",")); // ["a", "b", "c"]
// 結合
console.log(["a", "b", "c"].join("-")); // "a-b-c"
// 空白除去
console.log(" hello ".trim()); // "hello"
テンプレートリテラル
const name = "太郎";
const age = 25;
// 変数埋め込み
console.log(`名前: ${name}, 年齢: ${age}`);
// 式の埋め込み
console.log(`来年は ${age + 1} 歳`);
// 複数行
const html = `
<div>
<h1>${name}</h1>
<p>年齢: ${age}</p>
</div>
`;
コンソール出力
console.log("通常のログ");
console.warn("警告");
console.error("エラー");
console.table([{a: 1}, {a: 2}]); // テーブル形式
console.time("処理");
// 何かの処理
console.timeEnd("処理"); // 処理: 1.234ms
まとめ
constを基本に、再代入が必要な時だけletを使う===(厳密等価)を使い、==は避ける- テンプレートリテラル(
${})で文字列を組み立てる ??(Null合体演算子)でデフォルト値を設定
次回は条件分岐とループについて学びます。