![Only Javascript cheatsheet you need !](https://img.php.cn/upload/article/000/000/000/173499962381550.jpg)
var、let、const の違い
1. var、let、const の概要
Feature |
var |
let |
const |
Scope |
Function-scoped |
Block-scoped |
Block-scoped |
Re-declaration |
Allowed within the same scope |
Not allowed in the same scope |
Not allowed in the same scope |
Re-assignment |
Allowed |
Allowed |
Not allowed after initialization |
Initialization |
Can be declared without initialization |
Can be declared without initialization |
Must be initialized at the time of declaration |
Hoisting |
Hoisted but initialized to undefined
|
Hoisted but not initialized |
Hoisted but not initialized |
機能 |
var
|
させて |
定数
|
Type |
Function Scope |
Block Scope |
var |
Variables are scoped to the enclosing function. |
Does not support block scope. A var inside a block (if, for, etc.) leaks into the enclosing function or global scope. |
let / const |
Not function-scoped. |
Variables are confined to the block they are declared in. |
スコープ |
関数スコープ |
ブロックスコープ |
ブロックスコープ |
再宣言 |
同じスコープ内で許可されます |
同じスコープ内では許可されません |
同じスコープ内では許可されません |
再割り当て
|
許可 |
許可 |
初期化後は許可されません |
初期化if (true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // 10 (accessible because of function scope)
console.log(y); // ReferenceError (block-scoped)
console.log(z); // ReferenceError (block-scoped)
ログイン後にコピー ログイン後にコピー ログイン後にコピー ログイン後にコピー
|
初期化せずに宣言できます |
初期化せずに宣言できます |
宣言時に初期化する必要があります |
ホイスティング
|
ホイストされましたが、未定義に初期化されました
|
ホイストされましたが初期化されていません |
ホイストされましたが初期化されていません |
2.スコープの違い
Feature |
var |
let |
const |
Re-declaration |
Allowed |
Not allowed |
Not allowed |
Re-assignment |
Allowed |
Allowed |
Not allowed |
タイプ |
関数スコープ |
ブロックスコープ |
var |
変数のスコープは、それを囲んでいる関数に限定されます。 |
ブロックスコープはサポートしていません。ブロック内の変数 (if、for など) が、それを囲んでいる関数またはグローバル スコープに漏れます。 |
let / const |
関数スコープではありません。 |
変数は、宣言されているブロックに限定されます。 |
例:
3.再宣言と再割り当て
機能 |
var |
させて |
定数 |
再宣言 |
許可 |
許可されません |
許可されません |
再割り当て |
許可 |
許可 |
許可されません |
テーブル>
例:
if (true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // 10 (accessible because of function scope)
console.log(y); // ReferenceError (block-scoped)
console.log(z); // ReferenceError (block-scoped)
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
4.巻き上げ動作
Type |
Hoisting Behavior |
var |
Hoisted to the top of the scope but initialized as undefined. |
let |
Hoisted but not initialized. Accessing it before declaration causes a ReferenceError. |
const |
Hoisted but not initialized. Must be initialized at the time of declaration. |
タイプ |
巻き上げ動作 |
var
|
スコープの先頭にホイストされますが、未定義として初期化されます。 |
させてください// Re-declaration
var a = 10;
var a = 20; // Allowed
let b = 30;
// let b = 40; // SyntaxError: Identifier 'b' has already been declared
const c = 50;
// const c = 60; // SyntaxError: Identifier 'c' has already been declared
// Re-assignment
a = 15; // Allowed
b = 35; // Allowed
// c = 55; // TypeError: Assignment to constant variable
ログイン後にコピー ログイン後にコピー
|
ホイストされましたが、初期化されていません。宣言前にアクセスすると ReferenceError が発生します。 |
定数
|
ホイストされましたが、初期化されていません。宣言時に初期化する必要があります。 |
例:
Feature |
let and const
|
Block Scope |
Both are confined to the block in which they are declared. |
No Hoisting Initialization |
Both are hoisted but cannot be accessed before initialization. |
Better Practice |
Preferred over var for predictable scoping. |
5. let と const
の類似点
Scenario |
Recommended Keyword |
Re-declare variables or use function scope |
var (generally avoid unless necessary for legacy code). |
Variables that may change |
let (e.g., counters, flags, intermediate calculations). |
Variables that should not change |
const (e.g., configuration settings, fixed values). |
機能 |
let と const
ブロックスコープ |
両方とも、宣言されているブロックに限定されます。 |
ホイスティング初期化なし |
両方ともホイストされていますが、初期化前にはアクセスできません。 |
より良い実践方法 |
スコープを予測できるため、var よりも優先されます。 |
6.いつどちらを使用するべきですか?
シナリオ |
推奨キーワード |
変数を再宣言するか、関数スコープを使用してください |
var (従来のコードに必要な場合を除き、通常は避けてください)。 |
変更される可能性のある変数 |
let (例: カウンタ、フラグ、中間計算)。 |
変更すべきではない変数 |
const (構成設定、固定値など)。 |
テーブル>
7.吊り上げ説明
ホイスティングとは何ですか?
ホイスティングは、コンパイル段階で宣言をスコープの先頭に移動する JavaScript のデフォルトの動作です。
-
var: ホイストされ、未定義に初期化されます。
-
let / const: ホイストされていますが、初期化されていません。これにより、ブロックの開始から宣言が検出されるまで、時間的デッド ゾーン (TDZ) が作成されます。
なぜホイスティングがこのように機能するのですか?
-
コンパイルフェーズ:
JavaScript はまずコードをスキャンして、変数と関数の宣言のためのメモリ空間を作成します。この段階では:
-
var 変数は未定義に初期化されます。
-
let 変数と const 変数は「ホイスト」されますが、初期化されないままになるため、TDZ となります。
- 関数宣言は完全にホイストされています。
-
実行フェーズ:
JavaScript はコードを 1 行ずつ実行し始めます。変数と関数には、このフェーズ中に値が割り当てられます。
8.吊り上げの概要
Type |
Hoisting |
Access Before Declaration |
var |
Hoisted and initialized to undefined. |
Allowed but value is undefined. |
let |
Hoisted but not initialized. |
Causes a ReferenceError. |
const |
Hoisted but not initialized. |
Causes a ReferenceError. |
タイプ |
吊り上げ |
宣言前のアクセス |
var |
ホイストされ、未定義に初期化されました。 |
許可されていますが、値は未定義です。 |
させてください |
ホイストされましたが、初期化されていません。 |
ReferenceError が発生します。 |
定数 |
ホイストされましたが、初期化されていません。 |
ReferenceError が発生します。 |
テーブル>
例:
if (true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // 10 (accessible because of function scope)
console.log(y); // ReferenceError (block-scoped)
console.log(z); // ReferenceError (block-scoped)
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
結論
- 再代入の必要のない変数には、可能な限り const を使用してください。
- 同じスコープ内で再割り当てする必要がある変数には let を使用します。
- 従来のコードを使用する場合、または関数スコープの動作が必要な場合を除き、var を使用しないでください。
JavaScriptのデータ型
JavaScript には、プリミティブ タイプと 非プリミティブ (参照) タイプに分類されるさまざまなデータ型があります。以下に例と違いを示しながらそれぞれを説明します。
1. プリミティブデータ型
プリミティブ型は不変です。つまり、作成後に値を変更することはできません。これらはメモリに直接保存されます。
Data Type |
Example |
Description |
String |
"hello", 'world'
|
Represents a sequence of characters (text). Enclosed in single (''), double (""), or backticks (). |
Number |
42, 3.14, NaN
|
Represents both integers and floating-point numbers. Includes NaN (Not-a-Number) and Infinity. |
BigInt |
123n, 9007199254740991n
|
Used for numbers larger than Number.MAX_SAFE_INTEGER (2^53 - 1). Add n to create a BigInt. |
Boolean |
true, false
|
Represents logical values, used in conditions to represent "yes/no" or "on/off". |
Undefined |
undefined |
Indicates a variable has been declared but not assigned a value. |
Null |
null |
Represents an intentional absence of value. Often used to reset or clear a variable. |
Symbol |
Symbol('id') |
Represents a unique identifier, mainly used as property keys for objects to avoid collisions. |
データ型 |
例 |
説明 |
文字列 |
"こんにちは世界'
|
文字列 (テキスト) を表します。単一 ('')、二重 ("")、またはバッククォート () で囲みます。 |
番号 |
42、3.14、NaN
|
整数と浮動小数点数の両方を表します。 NaN (非数) と無限大が含まれます。 |
BigInt |
123n、9007199254740991n
|
Number.MAX_SAFE_INTEGER (2^53 - 1) より大きい数値に使用されます。 n を追加して BigInt を作成します。 |
ブール値 |
真、偽
|
「はい/いいえ」または「オン/オフ」を表す条件で使用される論理値を表します。 |
未定義 |
未定義 |
変数は宣言されているが、値が割り当てられていないことを示します。 |
Null |
null |
意図的に値が存在しないことを表します。変数をリセットまたはクリアするためによく使用されます。 |
シンボル |
シンボル('id') |
一意の識別子を表し、主に衝突を避けるためのオブジェクトのプロパティ キーとして使用されます。 |
テーブル>
2. 非プリミティブ (参照) データ型
非プリミティブ型は変更可能であり、参照によって保存されます。これらは、データのコレクションまたはより複雑なエンティティを保存するために使用されます。
Data Type |
Example |
Description |
Object |
{name: 'John', age: 30} |
A collection of key-value pairs. Keys are strings (or Symbols), and values can be any type. |
Array |
[1, 2, 3, "apple"] |
A list-like ordered collection of values. Access elements via index (e.g., array[0]). |
Function |
function greet() {} |
A reusable block of code that can be executed. Functions are first-class citizens in JavaScript. |
Date |
new Date() |
Represents date and time. Provides methods for manipulating dates and times. |
RegExp |
/pattern/ |
Represents regular expressions used for pattern matching and string searching. |
Map |
new Map() |
A collection of key-value pairs where keys can be of any type, unlike plain objects. |
Set |
new Set([1, 2, 3]) |
A collection of unique values, preventing duplicates. |
WeakMap |
new WeakMap() |
Similar to Map, but keys are weakly held, meaning they can be garbage-collected. |
WeakSet |
new WeakSet() |
Similar to Set, but holds objects weakly to prevent memory leaks. |
3. プリミティブ型と非プリミティブ型の主な違い
Aspect |
Primitive Types |
Non-Primitive Types |
Mutability |
Immutable: Values cannot be changed. |
Mutable: Values can be modified. |
Storage |
Stored directly in memory. |
Stored as a reference to a memory location. |
Copy Behavior |
Copied by value (creates a new value). |
Copied by reference (points to the same object). |
Examples |
string, number, boolean, etc. |
object, array, function, etc. |
4. 特殊な場合
オペレーターのタイプ
-
typeof null: JavaScript の歴史的なバグにより「オブジェクト」を返しますが、null はオブジェクトではありません。
-
typeof NaN: 「非数値」を意味する場合でも、「数値」を返します。
-
typeof function: オブジェクトのサブタイプである「function」を返します。
ダイナミックタイピング
JavaScript では、変数が実行時にさまざまな型の値を保持できるようになります:
if (true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // 10 (accessible because of function scope)
console.log(y); // ReferenceError (block-scoped)
console.log(z); // ReferenceError (block-scoped)
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
ログイン後にコピー
5. 各データ型の例
プリミティブ型
// Re-declaration
var a = 10;
var a = 20; // Allowed
let b = 30;
// let b = 40; // SyntaxError: Identifier 'b' has already been declared
const c = 50;
// const c = 60; // SyntaxError: Identifier 'c' has already been declared
// Re-assignment
a = 15; // Allowed
b = 35; // Allowed
// c = 55; // TypeError: Assignment to constant variable
ログイン後にコピー
ログイン後にコピー
非プリミティブ型
console.log(a); // undefined (hoisted)
var a = 10;
console.log(b); // ReferenceError (temporal dead zone)
let b = 20;
console.log(c); // ReferenceError (temporal dead zone)
const c = 30;
ログイン後にコピー
6. typeof結果の概要
Expression |
Result |
typeof "hello" |
"string" |
typeof 42 |
"number" |
typeof 123n |
"bigint" |
typeof true |
"boolean" |
typeof undefined |
"undefined" |
typeof null |
"object" |
typeof Symbol() |
"symbol" |
typeof {} |
"object" |
typeof [] |
"object" |
typeof function(){} |
"function" |
式 |
結果 |
「こんにちは」の種類 |
「文字列」 |
タイプ 42 |
「数値」 |
123n のタイプ |
「bigint」 |
true のタイプ |
"ブール値" |
未定義のタイプ |
「未定義」 |
null の型 |
「オブジェクト」 |
シンボル()の種類 |
「シンボル」 |
{} の種類 |
「オブジェクト」 |
[] の種類 |
「オブジェクト」 |
関数の種類(){} |
「関数」 |
以上が必要なのは Javascript のチートシートのみです。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。