docs(10_Wiki): W3Schools 위키화 — HTML/CSS/JavaScript(core)

W3Schools 튜토리얼을 P-Reinforce v3.1 포맷으로 위키화(영어 본문, 한/영 섹션 헤더).
- Topic_HTML: 59문서 (튜토리얼+예제, 레퍼런스/메타 제외)
- Topic_CSS: 190문서 (메인 + Advanced/Flexbox/Grid/RWD 전체)
- Topic_JavaScript: 120문서 (코어 언어; Temporal/DOM상세/BOM/WebAPI/AJAX/jQuery/Graphics 등은 후속)
각 폴더 00_INDEX.md(MOC) 포함. 코드 verbatim, 미확인분은 "Not found in source" 표기.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-23 19:21:18 +09:00
parent 8957890d13
commit 9609c04755
379 changed files with 54618 additions and 6 deletions
+224
View File
@@ -0,0 +1,224 @@
---
id: javascript-tutorial-index
title: "JavaScript Tutorial"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JavaScript Tutorial", "JS Tutorial", "JS MOC", "Topic_JavaScript index", "JavaScript 목차"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.90
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "moc", "index"]
raw_sources: ["https://www.w3schools.com/js/"]
applied_in: []
github_commit: ""
---
# [[JavaScript Tutorial]]
## 🎯 한 줄 통찰 (One-line insight)
Map of Content (MOC) for the W3Schools JavaScript Tutorial — the root that links every JavaScript knowledge page in this topic folder. [S1]
## 🧠 핵심 개념 (Core concepts)
- This folder (`Topic_JavaScript`) wikifies the **W3Schools JavaScript Tutorial**, one knowledge page per document, in P-Reinforce v3.1 format. [S1]
- Scope: **tutorial + "Learning by examples" pages only**. Reference pages (String/Number/DOM references), quizzes, exercises, certificate, bootcamp, and syllabus are **excluded by design**. [S1]
- **Progress:** the **core JavaScript language is complete (120 docs)** — basics, operators, conditions, loops, strings, numbers, functions, objects, scope, dates, arrays, sets, maps, iterations, math, data types, classes, errors, async, JSON, plus a first DOM/Events pass.
- **Pending (next waves):** Temporal, RegExp detail, Advanced Functions, Advanced Objects, Modules, Meta/Proxy, Typed Arrays, Debugging, Style Guide, Projects, the full DOM/Events detail, BOM/Window, Web APIs, AJAX, JSON extras, jQuery, and Graphics.
- Every page roots its Knowledge Graph back to this `[[JavaScript Tutorial]]` node.
## 📖 세부 내용 (Details)
### Basics
- [[JavaScript Introduction]]
- [[JavaScript Where To]]
- [[JavaScript Output]]
- [[JavaScript Syntax]]
- [[JavaScript Statements]]
- [[JavaScript Comments]]
- [[JavaScript Variables]]
- [[JavaScript Let]]
- [[JavaScript Const]]
- [[JavaScript Types]]
### Operators & Conditions
- [[JavaScript Operators]]
- [[JavaScript Arithmetic]]
- [[JavaScript Assignment]]
- [[JavaScript Comparisons]]
- [[JavaScript Conditional Operators]]
- [[JavaScript If]]
- [[JavaScript If Else]]
- [[JavaScript Ternary]]
- [[JavaScript Switch]]
- [[JavaScript Booleans]]
- [[JavaScript Logical Operators]]
### Loops
- [[JavaScript Loops]]
- [[JavaScript For Loop]]
- [[JavaScript While Loop]]
- [[JavaScript Break]]
- [[JavaScript Continue]]
- [[JavaScript Control Flow]]
### Strings
- [[JavaScript Strings]]
- [[JavaScript String Templates]]
- [[JavaScript String Methods]]
- [[JavaScript String Search]]
### Numbers
- [[JavaScript Numbers]]
- [[JavaScript Number Methods]]
- [[JavaScript Number Properties]]
- [[JavaScript Bitwise]]
- [[JavaScript BigInt]]
### Functions
- [[JavaScript Functions]]
- [[JavaScript Function Definitions]]
- [[JavaScript Function Invocation]]
- [[JavaScript Function Parameters]]
- [[JavaScript Function Returns]]
- [[JavaScript Function Arguments]]
- [[JavaScript Function Expressions]]
- [[JavaScript Arrow Functions]]
### Objects
- [[JavaScript Objects]]
- [[JavaScript Object Properties]]
- [[JavaScript Object Methods]]
- [[JavaScript Object this]]
- [[JavaScript Object Display]]
- [[JavaScript Object Constructors]]
### Scope
- [[JavaScript Scope]]
- [[JavaScript Code Blocks]]
- [[JavaScript Hoisting]]
- [[JavaScript var let const]]
- [[JavaScript Strict Mode]]
### Dates
- [[JavaScript Dates]]
- [[JavaScript Date Formats]]
- [[JavaScript Date Get Methods]]
- [[JavaScript Date Set Methods]]
- [[JavaScript Date Methods]]
### Arrays
- [[JavaScript Arrays]]
- [[JavaScript Array Methods]]
- [[JavaScript Array Search]]
- [[JavaScript Array Sort]]
- [[JavaScript Array Iteration]]
- [[JavaScript Array Const]]
### Sets & Maps
- [[JavaScript Sets]]
- [[JavaScript Set Methods]]
- [[JavaScript Set Logic]]
- [[JavaScript Maps]]
- [[JavaScript Map Methods]]
### Iterations
- [[JavaScript Iterables]]
- [[JavaScript Iterators]]
- [[JavaScript Generators]]
### Math
- [[JavaScript Math]]
- [[JavaScript Random]]
### Data Types
- [[JavaScript Data Types]]
- [[JavaScript Primitive Data Types]]
- [[JavaScript Object Data Types]]
- [[JavaScript Symbols]]
- [[JavaScript typeof]]
- [[JavaScript undefined]]
- [[JavaScript NaN]]
- [[JavaScript toString]]
- [[JavaScript toLocaleString]]
- [[JavaScript Type Coercion]]
- [[JavaScript Type Conversion]]
- [[JavaScript Destructuring]]
### Classes
- [[JavaScript Classes]]
- [[JavaScript Class Inheritance]]
- [[JavaScript Class Static]]
### Errors & RegExp
- [[JavaScript Errors Intro]]
- [[JavaScript Silent Errors]]
- [[JavaScript Error Statements]]
- [[JavaScript Error Object]]
- [[JavaScript RegExp]]
### Asynchronous
- [[JavaScript Asynchronous]]
- [[JavaScript Async]]
- [[JavaScript Async Timeouts]]
- [[JavaScript Async Callbacks]]
- [[JavaScript Promises]]
- [[JavaScript Async Await]]
- [[JavaScript Async Fetch]]
- [[JavaScript Async Debug]]
### JSON
- [[JavaScript JSON]]
- [[JSON Syntax]]
- [[JSON vs XML]]
- [[JSON Data Types]]
- [[JSON Parse]]
- [[JSON Stringify]]
- [[JSON Objects]]
- [[JSON Arrays]]
### HTML DOM & Events (first pass)
- [[JavaScript HTML DOM]]
- [[JavaScript DOM Methods]]
- [[JavaScript DOM Elements]]
- [[JavaScript DOM Changing HTML]]
- [[JavaScript DOM Changing CSS]]
- [[JavaScript DOM Animations]]
- [[JavaScript HTML Events]]
- [[JavaScript DOM Event Listener]]
### Pending (next waves)
- **Temporal** (Intro, vs Date, Duration, Instant, PlainDate/Time/DateTime, ZonedDateTime, Now, Arithmetic, Compare, Conversion, Formats, …)
- **RegExp detail** (Flags, Classes, Metachars, Assertions, Groups, Quantifiers, Patterns, Objects, Methods)
- **Advanced Functions** (Callbacks, this, Call/Apply/Bind, IIFE, Closures)
- **Advanced Objects** (Definitions, Iterations, Get/Set, Management, Protection, Prototypes)
- **Modules**, **Meta & Proxy**, **Typed Arrays**, **Debugging**, **Style Guide / Best Practices / Mistakes / Performance**, **Projects**
- **DOM detail** (Navigation, Nodes, Collections, NodeLists, Mouse/Keyboard/Load/Timing events, Form Validation)
- **Browser BOM** (Window, Screen, Location, History, Navigator, Popup, Timing, Cookies)
- **Web APIs** (Fetch, Geolocation, History, Pointer, Web Storage, Validation, Web Workers)
- **AJAX**, **JSON extras** (Server/PHP/HTML/JSONP), **jQuery**, **Graphics** (Canvas, Plotly, Chart.js, Google Chart, D3.js)
## 🛠️ 적용 사례 (Applied in summary)
120 knowledge documents generated for the core JavaScript language (1 exemplar + 119 batch-produced), all grounded in the corresponding W3Schools pages.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[10_Wiki]]
- **관련 개념:** [[JavaScript Introduction]], [[JavaScript HTML DOM]], [[HTML Tutorial]], [[CSS Tutorial]]
- **참조 맥락:** Entry point for the W3Schools JavaScript knowledge set; sits alongside [[HTML Tutorial]] and [[CSS Tutorial]].
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Tutorial — https://www.w3schools.com/js/
## 📝 변경 이력 (Change history)
- 2026-06-23: Created JavaScript Tutorial MOC and linked the 120 core-language docs; peripheral sections (Temporal, Advanced, DOM/BOM/Web API/AJAX/jQuery/Graphics, etc.) marked pending (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,192 @@
---
id: javascript-arithmetic
title: "JavaScript Arithmetic"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS arithmetic", "arithmetic operators", "operator precedence", "modulus operator", "exponentiation operator", "increment decrement"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "arithmetic", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_arithmetic.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Arithmetic]]
## 🎯 한 줄 통찰 (One-line insight)
Arithmetic operators perform arithmetic on numbers (literals or variables), with multiplication and division taking higher precedence than addition and subtraction. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Arithmetic on numbers** — arithmetic operators perform arithmetic on numbers, which can be literals or variables. [S1]
- **Operands and operators** — the numbers in an arithmetic operation are called operands; the operation performed between two operands is defined by an operator. [S1]
- **Eight arithmetic operators** — `+`, `-`, `*`, `**`, `/`, `%`, `++`, `--`. [S1]
- **Modulus returns the remainder** — the modulus operator `%` returns the division remainder. [S1]
- **Exponentiation equals Math.pow** — `x ** y` produces the same result as `Math.pow(x, y)`. [S1]
- **Precedence and left-to-right** — multiplication and division have higher precedence than addition and subtraction; operations of equal precedence are computed left to right; parentheses override precedence. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Operate over literals or variables** — the operands of an arithmetic expression can be literals (`100 + 50`), variables (`a + b`), or sub-expressions (`(100 + 50) * a`). [S1]
- **Increment/decrement in place** — `x++` raises and `x--` lowers a variable by one. [S1]
- **Force evaluation order with parentheses** — wrap a lower-precedence operation in `()` to make it run first. [S1]
## 📖 세부 내용 (Details)
**JavaScript Arithmetic Operators** [S1]
Arithmetic operators perform arithmetic on numbers (literals or variables):
| Operator | Description |
|----------|-------------|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| ** | Exponentiation (ES2016) |
| / | Division |
| % | Modulus (Remainder) |
| ++ | Increment |
| -- | Decrement |
**Arithmetic Operations** [S1]
A typical arithmetic operation operates on two numbers. The two numbers can be literals:
```javascript
let x = 100 + 50;
```
or variables:
```javascript
let x = a + b;
```
or expressions:
```javascript
let x = (100 + 50) * a;
```
**Operators and Operands** [S1]
The numbers (in an arithmetic operation) are called operands. The operation (to be performed between the two operands) is defined by an operator.
**Adding** [S1]
```javascript
let x = 5;
let y = 2;
let z = x + y;
```
**Subtracting** [S1]
```javascript
let x = 5;
let y = 2;
let z = x - y;
```
**Multiplying** [S1]
```javascript
let x = 5;
let y = 2;
let z = x * y;
```
**Dividing** [S1]
```javascript
let x = 5;
let y = 2;
let z = x / y;
```
**Remainder** [S1]
The modulus operator (`%`) returns the division remainder. The result of a modulo operation is the remainder of an arithmetic division.
```javascript
let x = 5;
let y = 2;
let z = x % y;
```
**Incrementing** [S1]
The increment operator (`++`) increments numbers.
```javascript
let x = 5;
x++;
let z = x;
```
**Decrementing** [S1]
The decrement operator (`--`) decrements numbers.
```javascript
let x = 5;
x--;
let z = x;
```
**Exponentiation** [S1]
The exponentiation operator (`**`) raises the first operand to the power of the second operand.
```javascript
let x = 5;
let z = x ** 2;
```
`x ** y` produces the same result as `Math.pow(x, y)`:
```javascript
let x = 5;
let z = Math.pow(x,2);
```
**Operator Precedence** [S1]
Operator precedence describes the order in which operations are performed in an arithmetic expression. Multiplication and division have higher precedence than addition and subtraction:
```javascript
let x = 100 + 50 * 3;
```
Parentheses can change the order — operations inside parentheses are computed first:
```javascript
let x = (100 + 50) * 3;
```
When many operations have the same precedence (like addition and subtraction or multiplication and division), they are computed from left to right:
```javascript
let x = 100 + 50 - 3;
```
```javascript
let x = 100 / 50 * 3;
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — adding/subtracting/multiplying/dividing into `z`, taking a remainder with `%`, incrementing/decrementing, exponentiating with `**` vs `Math.pow`, and demonstrating precedence with and without parentheses. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Operate over two variables:
```javascript
let x = 5;
let y = 2;
let z = x % y;
```
Exponentiate (two equivalent forms):
```javascript
let z = x ** 2;
let z = Math.pow(x,2);
```
Override precedence with parentheses:
```javascript
let x = (100 + 50) * 3;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source notes the exponentiation operator `**` was introduced in ES2016, which is the relevant version context.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Operators]], [[JavaScript Assignment]], [[JavaScript Types]], [[JavaScript Comparisons]]
- **참조 맥락:** Referenced whenever computing numeric values or reasoning about evaluation order in expressions.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Arithmetic — https://www.w3schools.com/js/js_arithmetic.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Arithmetic" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,179 @@
---
id: javascript-array-const
title: "JavaScript Array Const"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["const array", "constant array", "const block scope", "const reassignment", "array const declaration"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "array", "const"]
raw_sources: ["https://www.w3schools.com/js/js_array_const.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Array Const]]
## 🎯 한 줄 통찰 (One-line insight)
A `const` array cannot be *reassigned*, but its *elements* can be changed, added, or removed — `const` protects the binding, not the contents. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`const` is common practice for arrays** — ES2015 (ES6) made declaring arrays with `const` standard practice. [S1]
- **A const array cannot be reassigned** — assigning a new array to the same `const` name is an ERROR. [S1]
- **Const array elements CAN change** — you can change, add (`push`), or remove elements of a `const` array. [S1]
- **Const must be assigned when declared** — declaring without assignment is a syntax error. [S1]
- **Const has block scope** — a `const` declared inside a block is not the same variable as one outside the block. [S1]
- **Const cannot be redeclared** — you cannot redeclare or reassign a `const` in the same scope, but you can declare a new `const` with the same name in a different block scope. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Mutate-not-rebind pattern** — use `const` for arrays you will mutate in place (`cars[0] = ...`, `cars.push(...)`) but never reassign. [S1]
- **Block-scoped shadowing** — declare a same-named `const` in a nested block to safely shadow the outer one. [S1]
- **Declare-and-initialize** — always assign a `const` at declaration; deferred assignment is illegal. [S1]
## 📖 세부 내용 (Details)
**Const arrays** — It is a common practice to declare arrays using `const`: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
```
**Cannot be Reassigned** — an array declared with `const` cannot be reassigned: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
```
**Elements Can be Reassigned** — you can change the elements of a constant array: [S1]
```javascript
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Toyota";
// You can add an element:
cars.push("Audi");
```
**Assigned When Declared** — JavaScript `const` variables must be assigned a value when they are declared. This means an array declared with `const` must be initialized when it is declared. Declaring without initializing is a syntax error: [S1]
```javascript
const cars;
cars = ["Saab", "Volvo", "BMW"];
```
This is not how `var` works. With `var`, you can use the variable before it is declared: [S1]
```javascript
cars = ["Saab", "Volvo", "BMW"];
var cars;
```
**Const Block Scope** — a variable declared with `const` has block scope. A `const` declared in a block `{}` is not the same as a variable declared outside the block: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
const cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"
```
Redeclaring a `var` array with `var`, in another block, in the same program, is allowed and behaves differently (no block scope): [S1]
```javascript
var cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
var cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Toyota"
```
**Redeclaring Arrays** — Redeclaring a `var` array is allowed anywhere in a program: [S1]
```javascript
var cars = ["Volvo", "BMW"]; // Allowed
var cars = ["Toyota", "BMW"]; // Allowed
cars = ["Volvo", "Saab"]; // Allowed
```
Redeclaring or reassigning an existing `var` or `const` array to `const`, in the same scope or block, is not allowed: [S1]
```javascript
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
}
```
Redeclaring or reassigning an existing `const` array, in the same scope or block, is not allowed: [S1]
```javascript
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
}
```
Redeclaring a `const` array, in another scope or block, is allowed: [S1]
```javascript
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — declaring a `cars` array with `const`, mutating its elements via index assignment and `push`, and demonstrating block-scope shadowing. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Declare and mutate (allowed):
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota";
cars.push("Audi");
```
Reassign (error):
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`const` vs `var` for arrays** — `const` has block scope, must be initialized at declaration, and cannot be reassigned or redeclared in the same scope; `var` lacks block scope, can be used before declaration, and can be freely redeclared. `const` is the recommended common practice. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source notes that declaring arrays with `const` became common practice with ES2015 (ES6). [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Arrays]], [[JavaScript Array Iteration]], [[JavaScript Const]]
- **참조 맥락:** Referenced when deciding how to declare arrays and what mutability `const` guarantees.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Const — https://www.w3schools.com/js/js_array_const.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Const" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,316 @@
---
id: javascript-array-iteration
title: "JavaScript Array Iteration"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Array iteration", "forEach", "map", "filter", "reduce", "Array.from", "spread operator"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "array", "iteration"]
raw_sources: ["https://www.w3schools.com/js/js_array_iteration.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Array Iteration]]
## 🎯 한 줄 통찰 (One-line insight)
Array iteration methods operate on every array item — `forEach` runs a function per element, `map`/`flatMap`/`filter` produce new arrays, `reduce`/`reduceRight` fold to a single value, and `every`/`some` test conditions — while `Array.from`, `keys`, `entries`, the spread `...` and rest `...` round out array traversal and construction. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`forEach()`** calls a function once for each array element. The callback receives value, index, and array; index and array are optional. [S1]
- **`map()`** creates a new array by performing a function on each element, without changing the original. [S1]
- **`flatMap()`** (ES2019) maps each element then flattens the result by one level. [S1]
- **`filter()`** creates a new array with the elements that pass a test. [S1]
- **`reduce()`** runs a function on each element to reduce the array to a single value, working left-to-right; it can take an initial value. [S1]
- **`reduceRight()`** works like `reduce()` but right-to-left. [S1]
- **`every()`** checks if all elements pass a test; **`some()`** checks if some (at least one) pass. [S1]
- **`Array.from()`** returns an array object from any iterable, with an optional map function. [S1]
- **`keys()`** returns an Array Iterator with the keys; **`entries()`** returns key/value pairs. [S1]
- **`with()`** (ES2023) returns a new array with one element replaced, without mutating the original. [S1]
- **The spread `...` operator** expands an iterable into individual elements; **rest `...`** collects remaining elements during destructuring. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Side-effect pass** — `forEach` for running an action per element. [S1]
- **Transform pass** — `map`/`flatMap` to produce a transformed new array. [S1]
- **Select pass** — `filter` to keep matching elements. [S1]
- **Fold pass** — `reduce`/`reduceRight` to accumulate to one value, optionally with a seed. [S1]
- **Test pass** — `every`/`some` for all-match / any-match booleans. [S1]
- **Combine/copy** — spread `[...a, ...b]` to merge or `[...a]` to copy arrays. [S1]
## 📖 세부 내용 (Details)
**Array forEach()** — calls a function (a callback function) once for each array element. The callback takes value, index, array (index and array are optional): [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value + "<br>";
}
```
With only the value parameter: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value + "<br>";
}
```
**Array map()** — creates a new array by performing a function on each array element. It does not execute the function for array elements without values and does not change the original array: [S1]
```javascript
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
```
With only the value parameter: [S1]
```javascript
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
```
**Array flatMap()** — ES2019 added `flatMap()`, which first maps all elements of an array and then creates a new array by flattening the array: [S1]
```javascript
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);
```
**Array filter()** — creates a new array with array elements that pass a test: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
```
With only the value parameter: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
```
**Array reduce()** — runs a function on each array element to produce (reduce it to) a single value. It works from left-to-right and does not reduce the original array: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
```
With only total and value parameters: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
```
With an initial value (100): [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 100);
function myFunction(total, value) {
return total + value;
}
```
**Array reduceRight()** — runs a function on each array element to produce a single value, working from right-to-left: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
```
With only total and value parameters: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
```
**Array every()** — checks if all array values pass a test: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
```
With only the value parameter: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);
function myFunction(value) {
return value > 18;
}
```
**Array some()** — checks if some array values pass a test: [S1]
```javascript
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
```
**Array.from()** — returns an Array object from any object with a length property or any iterable object. Create an array from a string: [S1]
```javascript
let text = "ABCDEFG";
Array.from(text);
```
With a map function: [S1]
```javascript
const myNumbers = [1,2,3,4];
const myArr = Array.from(myNumbers, (x) => x * 2);
```
**Array keys()** — returns an Array Iterator object with the keys of an array: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
for (let x of keys) {
text += x + "<br>";
}
```
**Array entries()** — returns an Array Iterator object with key/value pairs: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
document.getElementById("demo").innerHTML += x;
}
```
**Array with()** — ES2023 added the `with()` method as a safe way to update elements without altering the original array: [S1]
```javascript
const months = ["Januar", "Februar", "Mar", "April"];
const myMonths = months.with(2, "March");
```
**Array Spread (...)** — the `...` operator expands an iterable into more elements. Combine two arrays: [S1]
```javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
```
Combine four arrays: [S1]
```javascript
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "Des"];
const year = [...q1, ...q2, ...q3, ...q4];
```
Copy an array: [S1]
```javascript
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
```
Spread into Math functions: [S1]
```javascript
const numbers = [23,55,21,87,56];
let minValue = Math.min(...numbers);
let maxValue = Math.max(...numbers);
```
**Array Rest (...)** — collects remaining elements during destructuring: [S1]
```javascript
let a, rest;
const arr1 = [1,2,3,4,5,6,7,8];
[a, ...rest] = arr1;
```
```javascript
let a, b, rest;
const arr1 = [1,2,3,4,5,6,7,8];
[a, b, ...rest] = arr1;
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — doubling numbers with `map`, filtering values over 18, summing with `reduce`, merging quarters into a year with spread, and replacing a month with `with`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Transform every element:
```javascript
const numbers2 = numbers1.map(value => value * 2);
```
Keep matching elements:
```javascript
const over18 = numbers.filter(value => value > 18);
```
Fold to a single value:
```javascript
let sum = numbers.reduce((total, value) => total + value);
```
Merge / copy arrays:
```javascript
const arr3 = [...arr1, ...arr2];
const copy = [...arr1];
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`forEach` vs `map`** — `forEach` is for side effects and returns nothing useful; `map` returns a new transformed array. [S1]
- **`reduce` vs `reduceRight`** — same folding behavior but opposite direction (left-to-right vs right-to-left). [S1]
- **`every` vs `some`** — `every` requires all elements to pass; `some` requires at least one. [S1]
- **Spread vs rest** — same `...` token; spread expands an iterable into elements, rest collects leftover elements during destructuring. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. Version provenance noted: `flatMap` is ES2019; `with` is ES2023. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Search]], [[JavaScript Array Sort]], [[JavaScript Array Const]]
- **참조 맥락:** Referenced whenever you need to traverse, transform, filter, or reduce array data.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Iteration — https://www.w3schools.com/js/js_array_iteration.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Iteration" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,246 @@
---
id: javascript-array-methods
title: "JavaScript Array Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["array methods", "push pop shift unshift", "splice slice", "concat", "toString join"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "arrays", "array-methods", "data-structures"]
raw_sources: ["https://www.w3schools.com/js/js_array_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Array Methods]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript arrays come with built-in methods to read, add, remove, copy, and slice elements — some mutate the original array (`push`, `pop`, `splice`) while others return a new one (`concat`, `slice`). [S1]
## 🧠 핵심 개념 (Core concepts)
- **Rich built-in method set** — arrays expose methods for length, conversion, access, addition, removal, copying, and slicing. [S1]
- **Mutating methods** — `push`, `pop`, `shift`, `unshift`, `splice`, and `copyWithin` modify the original array. [S1]
- **Non-mutating methods** — `concat`, `slice`, and `flat` return a new array without changing the source. [S1]
- **`delete` leaves holes** — using `delete` on an array element leaves `undefined` holes; use `pop()` or `shift()` instead. [S1]
- **`at()` is the modern accessor** — `array.at(index)` returns the element at an index (an ES2022 alternative to bracket access). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **End operations** — `push` (add) / `pop` (remove) work at the end. [S1]
- **Start operations** — `unshift` (add) / `shift` (remove) work at the start. [S1]
- **Mid-array edit** — `splice(start, deleteCount, ...items)` inserts and/or removes at any position. [S1]
- **Extract a copy** — `slice(start, end)` returns a new sub-array without mutating the original. [S1]
## 📖 세부 내용 (Details)
**Array length**
The `length` property returns the length (number of elements) of an array: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
```
**`toString()`**
The `toString()` method converts an array to a string of (comma separated) array values: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let myList = fruits.toString();
```
**`at()`**
The `at()` method returns an indexed element from an array (the same value as bracket access): [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(2);
```
This is equivalent to bracket notation: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];
```
**`join()`**
The `join()` method joins all array elements into a string. It behaves like `toString()`, but you can specify the separator: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
```
**`pop()`**
The `pop()` method removes the last element from an array: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
```
The `pop()` method returns the value that was "popped out": [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();
```
**`push()`**
The `push()` method adds a new element to an array (at the end): [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
```
The `push()` method returns the new array length: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");
```
**`shift()`**
The `shift()` method removes the first array element and "shifts" all other elements to a lower index: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
```
The `shift()` method returns the value that was "shifted out": [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
```
**`unshift()`**
The `unshift()` method adds a new element to an array (at the beginning) and "unshifts" older elements: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
```
**Changing elements**
Array elements are accessed using their index number. Setting an indexed value changes that element: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
```
**Deleting elements**
Since arrays are objects, array elements can be deleted with the JavaScript operator `delete`. Using `delete` leaves `undefined` holes in the array — use `pop()` or `shift()` instead: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element to undefined
```
**`concat()`**
The `concat()` method creates a *new* array by merging (concatenating) existing arrays. It does not change the existing arrays: [S1]
```javascript
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
```
`concat()` can take any number of array arguments: [S1]
```javascript
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
```
`concat()` can also take values (strings) as arguments: [S1]
```javascript
const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");
```
**`copyWithin()`**
The `copyWithin()` method copies array elements to another position in the array, overwriting existing values: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
```
**`flat()`**
The `flat()` method (ES2019) creates a new array by flattening a nested array into a one-dimensional array: [S1]
```javascript
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
```
**`splice()`**
The `splice()` method can be used to add new items to an array. The first parameter defines the position where new elements should be added (spliced in); the second parameter defines how many elements should be removed; the remaining parameters define the new elements to be added: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
```
With a non-zero second parameter, `splice()` removes elements while adding: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
```
You can use `splice()` to remove elements without leaving holes: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
```
**`slice()`**
The `slice()` method slices out a piece of an array into a *new* array. It does not remove any elements from the source array. This example slices out a part of the array starting from element 1 ("Orange"): [S1]
```javascript
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
```
Starting from element 3 ("Apple"): [S1]
```javascript
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(3);
```
The `slice()` method can take two arguments — `slice(1, 3)` selects elements from the start argument up to (but not including) the end argument: [S1]
```javascript
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets are the applied cases: managing a `fruits` array by reading its length, converting/joining to a string, adding/removing at either end (`push`/`pop`/`shift`/`unshift`), editing in the middle (`splice`), and producing new arrays without mutation (`concat`, `slice`, `flat`). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
End/start add-remove (language: JavaScript):
```javascript
fruits.push("Kiwi"); // add at end
fruits.pop(); // remove from end
fruits.unshift("Lemon"); // add at start
fruits.shift(); // remove from start
```
Insert/remove anywhere:
```javascript
fruits.splice(2, 0, "Lemon", "Kiwi"); // insert at index 2, remove 0
fruits.splice(2, 2, "Lemon", "Kiwi"); // remove 2 at index 2, then insert
```
New array without mutation:
```javascript
const merged = arr1.concat(arr2);
const part = fruits.slice(1, 3);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Mutating vs. non-mutating** — `push`/`pop`/`shift`/`unshift`/`splice`/`copyWithin` change the original; `concat`/`slice`/`flat` return a new array. Choose by whether you want to preserve the source. [S1]
- **`delete` vs. `pop`/`shift`/`splice`** — `delete` leaves `undefined` holes; prefer `pop`/`shift`/`splice` to remove cleanly. [S1]
- **`at()` vs. bracket access** — both return the element at an index; `at()` is the newer (ES2022) accessor. [S1]
- **`toString()` vs. `join()`** — both stringify; `join()` lets you choose the separator. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The page notes version origins for some methods (`flat()` is ES2019; `at()` is ES2022).
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Arrays]], [[JavaScript Array Search]], [[JavaScript Array Sort]], [[JavaScript Array Iteration]]
- **참조 맥락:** Referenced whenever transforming or restructuring array data in JavaScript.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Methods — https://www.w3schools.com/js/js_array_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,163 @@
---
id: javascript-array-search
title: "JavaScript Array Search"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Array search", "indexOf", "find array", "findIndex", "includes array", "findLast"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "array", "search"]
raw_sources: ["https://www.w3schools.com/js/js_array_search.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Array Search]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript offers a family of array search methods — position-based (`indexOf`, `lastIndexOf`, `includes`) and predicate-based (`find`, `findIndex`, `findLast`, `findLastIndex`) — that let you locate either a value's index or the first/last element matching a test. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`indexOf()`** searches an array for a value and returns its first matching position (0-indexed), or `-1` if not found. [S1]
- **`lastIndexOf()`** works like `indexOf()` but returns the position of the *last* occurrence. [S1]
- **`includes()`** (ES2016) checks whether an element exists in an array and, unlike `indexOf()`, can correctly detect `NaN` values. [S1]
- **`find()`** (ES6) returns the value of the first element that passes a test function. [S1]
- **`findIndex()`** returns the index of the first element that passes a test function. [S1]
- **`findLast()`** (ES2023) returns the value of the last element that passes a test, searching from the end. [S1]
- **`findLastIndex()`** (ES2023) returns the index of the last element that passes a test. [S1]
- **The callback for `find`/`findIndex`** receives three arguments: the value, the index, and the array itself. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Position lookup pattern** — call `indexOf`/`lastIndexOf` and add `+ 1` to convert a 0-based index into a human-readable position. [S1]
- **Existence check pattern** — prefer `includes()` over `indexOf() !== -1` when you only need a boolean and need `NaN` to be detectable. [S1]
- **Predicate search pattern** — pass a test function (named or arrow) to `find`/`findIndex`/`findLast`/`findLastIndex` to locate by condition rather than by exact value. [S1]
## 📖 세부 내용 (Details)
**indexOf()** — Searches an array for a value and returns its position. The first item is at position 0, the second at position 1, and so on. It returns `-1` if the item is not found. If the item is present more than once, it returns the position of the first occurrence. [S1]
Syntax:
```javascript
array.indexOf(item, start)
```
Search an array for the item "Apple":
```javascript
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
```
**lastIndexOf()**`Array.lastIndexOf()` is the same as `Array.indexOf()`, but returns the position of the last occurrence of the specified element. [S1]
Syntax:
```javascript
array.lastIndexOf(item, start)
```
Search an array for the item "Apple":
```javascript
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
```
**includes()** — ECMAScript 2016 introduced `Array.includes()` to arrays. This allows you to check if an element is present in an array (including `NaN`, unlike `indexOf`). [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
```
Syntax:
```javascript
array.includes(search-item)
```
**find()** — The `find()` method returns the value of the first array element that passes a test function. This example finds (returns the value of) the first element that is larger than 18: [S1]
```javascript
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
```
The function takes 3 arguments: the item value, the item index, and the array itself. [S1]
**findIndex()** — The `findIndex()` method returns the index of the first array element that passes a test function. This example finds the index of the first element that is larger than 18: [S1]
```javascript
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
```
**findLast()** — ES2023 added the `findLast()` method that will start from the end of an array and return the value of the first element that satisfies a condition. Finding the last temperature above 40: [S1]
```javascript
const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x > 40);
```
**findLastIndex()** — The `findLastIndex()` method finds the index of the last element that satisfies a condition. Finding the index of the last temperature above 40: [S1]
```javascript
const temp = [27, 28, 30, 40, 42, 35, 30];
let pos = temp.findLastIndex(x => x > 40);
```
**Browser support** — The page documents browser support across Chrome, Edge, Firefox, Safari, and Opera, with most of these features fully supported since their ES2016ES2023 introductions. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — locating "Apple" in a fruits array, finding the first number over 18, and finding the last temperature above 40. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Find a value's position:
```javascript
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
```
Check existence:
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
```
Find first element by condition:
```javascript
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find((value, index, array) => value > 18);
```
Find last element by condition (ES2023):
```javascript
const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x > 40);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`indexOf` vs `includes`** — use `indexOf`/`lastIndexOf` when you need the position; use `includes` when you need a boolean and especially when `NaN` must be detectable (which `indexOf` cannot do). [S1]
- **`find`/`findIndex` vs `findLast`/`findLastIndex`** — the former search from the start of the array; the latter (ES2023) search from the end. Choose value-returning (`find`/`findLast`) vs index-returning (`findIndex`/`findLastIndex`) based on what you need. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source notes version provenance: `includes` is ES2016; `find`/`findIndex` are ES6; `findLast`/`findLastIndex` are ES2023. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Sort]], [[JavaScript Array Iteration]], [[JavaScript Arrays]]
- **참조 맥락:** Referenced whenever you need to locate elements within an array by value or by predicate.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Search — https://www.w3schools.com/js/js_array_search.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Search" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,209 @@
---
id: javascript-array-sort
title: "JavaScript Array Sort"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Array sort", "sort()", "reverse()", "toSorted", "compare function", "numeric sort"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "array", "sort"]
raw_sources: ["https://www.w3schools.com/js/js_array_sort.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Array Sort]]
## 🎯 한 줄 통찰 (One-line insight)
`sort()` orders array elements alphabetically by default (treating them as strings), so numeric sorting requires a compare function `(a, b) => a - b`; ES2023's `toSorted()`/`toReversed()` provide non-mutating alternatives. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`sort()`** sorts an array alphabetically (as strings) and mutates the original array. [S1]
- **`reverse()`** reverses the order of the elements in an array; combining `sort()` then `reverse()` produces descending alphabetical order. [S1]
- **`toSorted()`** (ES2023) returns a new sorted array, leaving the original unchanged. [S1]
- **`toReversed()`** (ES2023) returns a new reversed array, leaving the original unchanged. [S1]
- **Default sort is string-based** — so `"25"` sorts higher than `"100"` because "2" is greater than "1"; numeric sorting needs a compare function. [S1]
- **The compare function** returns a negative value (sort `a` before `b`), a positive value (sort `b` before `a`), or zero (no change). [S1]
- **Sorting is stable** as of the ES2019 standard requirement. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Numeric ascending** — `arr.sort((a, b) => a - b)`. [S1]
- **Numeric descending** — `arr.sort((a, b) => b - a)`. [S1]
- **Min/max via sort** — sort numerically, then read the first or last element. [S1]
- **Min/max via Math.apply** — `Math.min.apply(null, arr)` / `Math.max.apply(null, arr)`. [S1]
- **Sort objects by property** — pass a compare function reading the property (numeric `a.prop - b.prop`, or string comparison with `toLowerCase()`). [S1]
## 📖 세부 내용 (Details)
**Sorting an Array** — The `sort()` method sorts an array alphabetically: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
```
**Reversing an Array** — The `reverse()` method reverses the elements in an array: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
```
By combining `sort()` and `reverse()`, you can sort an array in descending order: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
```
**The toSorted() Method** (ES2023) — provides a safe way of sorting an array without altering the original: [S1]
```javascript
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
```
**The toReversed() Method** (ES2023) — reverses without altering the original: [S1]
```javascript
const months = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months.toReversed();
```
**Numeric Sort** — By default, the `sort()` function sorts values as strings, so "25" is bigger than "100" because "2" is bigger than "1". A compare function fixes this. Ascending: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
```
Descending: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
```
**Sorting an Array in Random Order** — [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
```
**The Fisher Yates Method** — a more correct way to shuffle: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}
```
**Find the Lowest (or Highest) Array Value** — using `Math.min.apply`: [S1]
```javascript
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
```
Using `Math.max.apply`: [S1]
```javascript
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
```
A custom minimum function (fastest method): [S1]
```javascript
function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}
```
A custom maximum function: [S1]
```javascript
function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
```
**Sorting Object Arrays** — JavaScript arrays often contain objects. Even if objects have properties of different data types, `sort()` can be used to sort the array, using a compare function for the property. By numeric property: [S1]
```javascript
cars.sort(function(a, b){return a.year - b.year});
```
By string property: [S1]
```javascript
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
```
**Stable Sort** — As of the ES2019 standard, sorting is required to be stable: elements with equal sort keys keep their relative order. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — sorting fruit names, numeric points ascending/descending, shuffling, finding min/max, and sorting car objects by `year` or `type`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Alphabetical sort:
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
```
Numeric sort ascending / descending:
```javascript
points.sort((a, b) => a - b); // ascending
points.sort((a, b) => b - a); // descending
```
Non-mutating (ES2023):
```javascript
const sorted = months.toSorted();
const reversed = months.toReversed();
```
Sort objects by numeric property:
```javascript
cars.sort(function(a, b){return a.year - b.year});
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`sort()`/`reverse()` vs `toSorted()`/`toReversed()`** — the former mutate the original array in place; the latter (ES2023) return new arrays and leave the original intact. Choose the non-mutating versions when you must preserve the source. [S1]
- **Random sort vs Fisher-Yates** — `sort(() => 0.5 - Math.random())` is shown but the page presents the Fisher-Yates loop as the more correct shuffle. [S1]
- **Min/max approaches** — sort-and-read, `Math.min/max.apply`, or a custom loop; the page notes the custom loop is the fastest. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source notes that stable sorting became a requirement in the ES2019 standard and that `toSorted`/`toReversed` were added in ES2023. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Search]], [[JavaScript Array Iteration]], [[JavaScript Math]]
- **참조 맥락:** Referenced whenever array elements must be ordered, shuffled, or reduced to a min/max value.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Sort — https://www.w3schools.com/js/js_array_sort.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Sort" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,217 @@
---
id: javascript-arrays
title: "JavaScript Arrays"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["array literal", "new Array", "array index", "array length", "isArray"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "arrays", "data-structures", "objects"]
raw_sources: ["https://www.w3schools.com/js/js_arrays.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Arrays]]
## 🎯 한 줄 통찰 (One-line insight)
An array is a special object that holds an ordered, zero-indexed collection of values — use `[]` literals to create them, and remember `typeof` reports them as `"object"`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Arrays store ordered collections** — a single variable can hold multiple values, accessed by zero-based index numbers. [S1]
- **Literal syntax is preferred** — `[]` is the recommended way to create an array (over `new Array()`). [S1]
- **Indexes start at 0** — the first element is at index `0`, the second at `1`, and so on. [S1]
- **Arrays are objects** — `typeof` returns `"object"`; elements can themselves be objects, functions, or other arrays. [S1]
- **No named indexes** — JavaScript does not support arrays with named indexes; using named indexes turns the array into a plain object and breaks array methods. [S1]
- **Detect with `Array.isArray()` / `instanceof`** — because `typeof` returns `"object"`, use these to recognize an array. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Create with a literal** — `const cars = ["Saab", "Volvo", "BMW"];`. [S1]
- **Access / change by index** — `cars[0]` reads, `cars[0] = "Opel"` writes. [S1]
- **Append with `push` or `length`** — `fruits.push("Lemon")` or `fruits[fruits.length] = "Lemon"`. [S1]
- **Iterate with `for` or `forEach`** — loop by index, or pass a callback to `forEach`. [S1]
## 📖 세부 내용 (Details)
**Creating an array (literal)**
Using an array literal is the easiest way to create a JavaScript array: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
```
Spaces and line breaks are not important; a declaration can span multiple lines: [S1]
```javascript
const cars = [
"Saab",
"Volvo",
"BMW"
];
```
You can also create an array and then provide the elements: [S1]
```javascript
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
```
**Using the `new Array()` keyword**
The following example also creates an array and assigns values to it, but the array literal method is recommended: [S1]
```javascript
const cars = new Array("Saab", "Volvo", "BMW");
```
**Accessing array elements**
You access an array element by referring to its index number. Array indexes start with 0: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
```
**Changing an array element**
This statement changes the value of the first element in `cars`: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
```
**Accessing the full array**
With JavaScript, the full array can be accessed by referring to the array name: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
```
**Arrays are Objects**
Arrays are a special type of object. The `typeof` operator returns `"object"` for arrays. But JavaScript arrays are best described as arrays. Arrays use *numbers* to access their "elements". This array uses numbers to access its elements: [S1]
```javascript
const person = ["John", "Doe", 46];
```
Objects use *names* to access their "members". This object uses names to access its members: [S1]
```javascript
const person = {firstName:"John", lastName:"Doe", age:46};
```
**Array elements can be objects**
JavaScript variables can be objects, and arrays are special kinds of objects. Because of this, you can have variables of different types in the same array, and array elements can themselves be objects or functions: [S1]
```javascript
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
```
**The `length` property**
The `length` property of an array returns the number of array elements: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
```
**Looping array elements (for loop)**
One way to loop through an array is using a `for` loop: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
```
**Looping array elements (forEach)**
You can also use the `Array.forEach()` function: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
```
**Adding array elements**
The easiest way to add a new element to an array is using the `push()` method: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon");
```
A new element can also be added to an array using the `length` property: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon";
```
**Associative arrays**
Many programming languages support arrays with named indexes (associative arrays). JavaScript does *not* support arrays with named indexes. In JavaScript, arrays always use numbered indexes. If you use named indexes, JavaScript will redefine the array as an object, and array methods and properties will produce incorrect results. [S1]
**The difference between arrays and objects**
In JavaScript, arrays use *numbered* indexes, while objects use *named* indexes. Use an object when you want the element names to be strings (text); use an array when you want the element names to be numbers. [S1]
**How to recognize an array**
A common question is: how do I know if a variable is an array? The problem is that the `typeof` operator returns `"object"`. The first solution is `Array.isArray()`: [S1]
```javascript
Array.isArray(fruits);
```
The second solution is the `instanceof` operator, which returns true if an object is created by a given constructor: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
(fruits instanceof Array);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets are the applied cases: building a `cars`/`fruits` array, reading/writing by index, rendering a `<ul>` list via `for` and `forEach`, appending with `push`/`length`, and distinguishing arrays from objects via `Array.isArray`/`instanceof`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Create, read, write (language: JavaScript):
```javascript
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0]; // read
cars[0] = "Opel"; // write
```
Append:
```javascript
fruits.push("Lemon");
fruits[fruits.length] = "Lemon";
```
Detect an array:
```javascript
Array.isArray(fruits);
(fruits instanceof Array);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Array literal `[]` vs. `new Array()`** — the literal is recommended for readability and to avoid `new Array()` pitfalls. [S1]
- **Array vs. object** — use an array when element names are numbers (ordered/indexed data); use an object when names are strings. [S1]
- **`Array.isArray()` vs. `instanceof Array`** — both detect arrays where `typeof` cannot (it returns `"object"`). [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Methods]], [[JavaScript Objects]], [[JavaScript Loop For]], [[JavaScript var let const]]
- **참조 맥락:** The foundation for any indexed/ordered data handling in JavaScript.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Arrays — https://www.w3schools.com/js/js_arrays.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,203 @@
---
id: javascript-arrow-functions
title: "JavaScript Arrow Functions"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS arrow functions", "arrow function syntax", "fat arrow", "=> functions", "lexical this", "concise functions"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "arrow-functions", "this"]
raw_sources: ["https://www.w3schools.com/js/js_arrow_function.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Arrow Functions]]
## 🎯 한 줄 통찰 (One-line insight)
Arrow functions give a shorter syntax for function expressions and do not have their own `this` — they inherit it from the surrounding code, which makes them great for callbacks but poor as object methods. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Shorter function expressions** — arrow functions let you skip the `function` keyword, the `return` keyword, and the curly brackets. [S1]
- **Always an expression** — an arrow function uses `=>` and is always written as a function expression. [S1]
- **Implicit return** — a single-statement body returns its value automatically without `return` or braces. [S1]
- **Parentheses rules** — one parameter can omit parentheses; zero or multiple parameters require them. [S1]
- **No own `this`** — arrow functions do not have their own `this`; they inherit it from the surrounding code, so they are unsuitable as object methods. [S1]
- **Not hoisted** — arrow functions are expressions, must be assigned to a variable, and cannot be used before they are defined. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Concise one-liner** — `const multiply = (a, b) => a * b;` collapses an expression into a single statement with implicit return. [S1]
- **Single-param shorthand** — drop the parentheses for exactly one parameter: `const square = x => x * x;`. [S1]
- **Always-keep-braces habit** — because implicit return only works for a single statement, keeping `{ return ... }` avoids accidental `undefined`. [S1]
## 📖 세부 내용 (Details)
Arrow functions allow a shorter syntax for function expressions. You can skip the `function` keyword, the `return` keyword, and the curly brackets. [S1]
**Arrow Function Syntax**
An arrow function uses the `=>` symbol and is always written as a function expression. [S1]
```javascript
const add = (a, b) => {
return a + b;
};
```
**Shorter Syntax**
If the function body contains only one statement, you can remove the word `function`, the curly brackets, and the `return` keyword. Before arrow: [S1]
```javascript
const multiply = function(a, b) {return a * b}
```
With arrow: [S1]
```javascript
const multiply = (a, b) => a * b;
```
With arrow: [S1]
```javascript
const hello = () => "Hello World!";
```
Before arrow: [S1]
```javascript
const hello = function() {return "Hello World!";}
```
**Arrow Functions with One Parameter**
If a function has only one parameter, you can omit the parentheses. With parentheses: [S1]
```javascript
const square = (x) => x * x;
```
Without parentheses: [S1]
```javascript
const square = x => x * x;
```
With parentheses: [S1]
```javascript
const hello = (val) => "Hello " + val;
```
Without parentheses: [S1]
```javascript
const hello = val => "Hello " + val;
```
**Arrow Functions Return Value by Default**
If the function has only one statement that returns a value, you can remove the brackets and the `return` keyword. This works only if the function has only one statement. [S1]
```javascript
const hello = () => "Hello World!";
```
**Arrow Function Parameters**
If you have parameters, you pass them inside the parentheses: [S1]
```javascript
const hello = (val) => "Hello " + val;
```
If you have only one parameter, you can skip the parentheses as well: [S1]
```javascript
const hello = val => "Hello " + val;
```
**Arrow Functions with No Parameters**
If there are no parameters, parentheses are required: [S1]
```javascript
const hello = () => "Hello World!";
```
You can only omit the `return` keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them: [S1]
```javascript
// This will return undefined
const myFunction = (x, y) => { x * y };
// This will return undefined
const myFunction = (x, y) => return x * y;
// This will return the expected result
const myFunction = (x, y) => { return x * y };
```
**Arrow Functions Are Not Declarations**
Arrow functions are always expressions and must be assigned to a variable. They cannot be used before they are defined: [S1]
```javascript
hello(); // Error
const hello = () => "Hello";
```
Arrow functions must be defined before they are used. [S1]
**Arrow Functions and the this Keyword**
Arrow functions do not have their own `this` value. They inherit `this` from the surrounding code. [S1]
```javascript
const person = {
name: "John",
greet: function() {
return this.name;
}
};
```
Using an arrow function as a method often gives unexpected results: [S1]
```javascript
const person = {
name: "John",
greet: () => {
return this.name;
}
};
```
In this case, `this` does not refer to the person object. [S1]
**When to Use Arrow Functions**
For short functions; for callbacks and array methods; when you do not need your own `this`. [S1]
**When Not to Use Arrow Functions**
As object methods; when you need your own `this`; when using function declarations. [S1]
**Common Mistakes**
Forgetting parentheses rules (parentheses are required for zero or multiple parameters); using arrow functions as methods (arrow functions do not bind `this`); expecting hoisting (arrow functions are not hoisted). [S1]
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Situation | Use arrow function? | Reason |
| --- | --- | --- |
| Short functions, callbacks, array methods | Yes | Concise syntax; no own `this` needed | [S1]
| Object methods | No | Arrow functions do not bind `this` to the object | [S1]
| Need your own `this` | No | Arrow `this` is inherited from surrounding code | [S1]
| Function declarations | No | Arrow functions are always expressions, not declarations | [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `multiply`, `square`, and `hello` concise forms, plus the `person.greet` method comparison demonstrating the `this` pitfall. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Concise single-expression arrow:
```javascript
const multiply = (a, b) => a * b;
```
Single-parameter without parentheses:
```javascript
const square = x => x * x;
```
Explicit-return habit (avoids accidental undefined):
```javascript
const myFunction = (x, y) => { return x * y };
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Function Expressions]], [[JavaScript Function Arguments]], [[JavaScript Object this]]
- **참조 맥락:** Referenced when writing concise callbacks and when reasoning about `this` binding in object methods.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Arrow Functions — https://www.w3schools.com/js/js_arrow_function.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Arrow Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,161 @@
---
id: javascript-assignment
title: "JavaScript Assignment"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS assignment operators", "compound assignment", "logical assignment", "falsy values", "truthy values", "nullish coalescing assignment", "spread operator"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "assignment", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_assignment.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Assignment]]
## 🎯 한 줄 통찰 (One-line insight)
Assignment operators assign values to variables — `=` for a plain assignment and compound forms (`+=`, `-=`, `*=`, `**=`, `/=`, `%=`) plus logical forms (`&&=`, `||=`, `??=`) for assign-and-operate in one step. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Assignment operators assign values** — they assign values to JavaScript variables. [S1]
- **Compound assignment** — arithmetic compound operators combine an operation with assignment, e.g. `x += y` is the same as `x = x + y`. [S1]
- **Logical assignment** — `&&=`, `||=`, and `??=` assign conditionally based on truthiness/falsiness/nullishness. [S1]
- **8 falsy values** — `false`, `0`, `-0`, `0n`, `""` (empty strings), `null`, `undefined`, and `NaN` are falsy. [S1]
- **Truthy surprises** — `"0"`, `"false"`, `[]`, and `{}` are truthy even though they look "empty". [S1]
- **Spread `...`** — the `...` operator splits iterables into individual elements. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Mutate in place** — apply an operation to a variable and store back with one compound operator (`x += 5`). [S1]
- **Conditional assignment** — `x ??= 10` assigns only when `x` is null/undefined; `x ||= 10` when falsy; `x &&= 10` when truthy. [S1]
- **Falsy check awareness** — remember `"0"` and `"false"` strings (and `[]`/`{}`) are truthy when writing conditions. [S1]
## 📖 세부 내용 (Details)
**JavaScript Assignment Operators** [S1]
Assignment operators assign values to JavaScript variables. Using `x = 10` and `y = 5` for the examples below, the result column shows the value after applying the operator:
| Operator | Example | Same As | Result |
|----------|---------|---------|--------|
| = | x = y | x = y | x = 5 |
| += | x += y | x = x + y | x = 15 |
| -= | x -= y | x = x - y | x = 5 |
| *= | x *= y | x = x * y | x = 50 |
| **= | x **= y | x = x ** y | x = 100000 |
| /= | x /= y | x = x / y | x = 2 |
| %= | x %= y | x = x % y | x = 0 |
**The = Operator** [S1]
```javascript
let x = 10;
```
**The += Operator** [S1]
```javascript
let x = 10;
x += 5;
```
**The -= Operator** [S1]
```javascript
let x = 10;
x -= 5;
```
**The *= Operator** [S1]
```javascript
let x = 10;
x *= 5;
```
**The **= Operator** [S1]
```javascript
let x = 10;
x **= 5;
```
**The /= Operator** [S1]
```javascript
let x = 10;
x /= 5;
```
**The %= Operator** [S1]
```javascript
let x = 10;
x %= 5;
```
**Logical Assignment Operators** [S1]
The `&&=` Operator (Logical AND assignment):
```javascript
let x = true;
let y = x &&= 10;
```
The `||=` Operator (Logical OR assignment):
```javascript
let x = false;
let y = x ||= 10;
```
The `??=` Operator (Nullish Coalescing assignment):
```javascript
let x;
x ??= 10;
```
**The 8 FALSY Values** [S1]
The following values are falsy: `false`, `0`, `-0`, `0n`, `""` / `''` / `` (empty strings), `null`, `undefined`, and `NaN`.
**These are TRUTHY** [S1]
The following values are truthy: `"0"` (string), `"false"` (string), `[]` (empty array), and `{}` (empty object).
**The Spread (...) Operator** [S1]
The `...` operator splits iterables into individual elements.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — each compound operator demonstrated against `let x = 10`, and the logical-assignment operators shown against boolean/undefined seeds. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Compound arithmetic assignment:
```javascript
let x = 10;
x += 5;
```
Nullish-coalescing assignment (only assigns when null/undefined):
```javascript
let x;
x ??= 10;
```
Logical OR assignment (assigns when falsy):
```javascript
let x = false;
let y = x ||= 10;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. Worth noting: `"0"`, `"false"`, `[]`, and `{}` are truthy despite intuition, which the source explicitly flags.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Operators]], [[JavaScript Arithmetic]], [[JavaScript Comparisons]], [[JavaScript Types]]
- **참조 맥락:** Referenced whenever updating a variable's value or doing conditional/defaulting assignment.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Assignment — https://www.w3schools.com/js/js_assignment.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Assignment" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,162 @@
---
id: javascript-async
title: "JavaScript Async"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Async programming", "JS async basics", "Synchronous vs asynchronous", "Async execution order", "Non-blocking code"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "asynchronous", "settimeout"]
raw_sources: ["https://www.w3schools.com/js/js_async.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript runs line by line by default, but async code can start a long-running task and keep working — so the visible order of results may differ from the source order. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Default execution is top-to-bottom, left-to-right** — JavaScript normally executes one line at a time in source order. [S1]
- **Async reorders work** — async code lets a program start a long-running task (like fetching data from a file) and continue with other tasks before the first finishes, which can change the execution order. [S1]
- **The result-not-ready problem** — reading an async result too early yields `undefined` because the async code has not finished yet. [S1]
- **Async is not parallel** — parallel runs multiple things simultaneously on different processors; async switches between tasks without necessarily running them at the same time. [S1]
- **Six building blocks** — synchronous flow, timers, callbacks, events, promises, and async/await. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Order swap by call order** — calling `mySecond()` before `myFirst()` simply changes which output appears first; ordinary synchronous calls obey source order. [S1]
- **Deferred call via setTimeout** — wrapping a call in `setTimeout(fn, ms)` pushes it after the synchronous lines, yielding A, C, B. [S1]
- **Event-driven callback** — an HTML attribute like `onclick` wires user interaction to a function that runs later. [S1]
## 📖 세부 내용 (Details)
**Synchronous calls run in order**
Plain calls produce output A, B, C: [S1]
```javascript
myDisplayer("A");
myDisplayer("B");
myDisplayer("C");
```
**Function order matters**
Defining two functions and calling them in order: [S1]
```javascript
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
```
Swapping the call order swaps the output: [S1]
```javascript
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
mySecond();
myFirst();
```
**Asynchronous flow with setTimeout**
The deferred `B` runs after the synchronous `C`, so the order is A, C, B: [S1]
```javascript
myDisplayer("A");
setTimeout(function() {
myDisplayer("B");
}, 1000);
myDisplayer("C");
```
**The result-not-ready trap**
The result is `undefined` because the async code has not finished yet: [S1]
```javascript
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
```
**JavaScript events**
Events wire callbacks to user interaction: [S1]
```javascript
<button onclick="displayDate()">The time is?</button>
```
**Core async concepts**
[S1]
| Concept | Description |
|---------|-------------|
| Synchronous | The JavaScript standard flow is executing line by line |
| Timers | Allows code to run while other code is waiting |
| Callbacks | Callbacks were the first solution for async JavaScript |
| Events | Stores a callback function waiting to be executed |
| Promises | Tools to handle asynchronous operations cleanly |
| Async/Await | The clean and modern way to handle async code |
**Asynchronous vs parallel**
Parallel means doing multiple things at the same time on different processors. Asynchronous means switching between tasks, not necessarily running them simultaneously. [S1]
**Restaurant analogy**
Place your order (async call); sit down and do other things while the chef makes it; the server brings the food (the callback). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets — ordered/reordered function calls, the deferred A/C/B `setTimeout`, the `undefined` result trap, and the `onclick` event button — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Deferred execution that reorders output (language: JavaScript):
```javascript
myDisplayer("A");
setTimeout(function() {
myDisplayer("B");
}, 1000);
myDisplayer("C");
```
Event-driven callback:
```javascript
<button onclick="displayDate()">The time is?</button>
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Asynchronous]], [[JavaScript Async Timeouts]], [[JavaScript Async Callbacks]], [[JavaScript Promise]]
- **참조 맥락:** The foundational lesson establishing why execution order matters before introducing timeouts, callbacks, and promises.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async — https://www.w3schools.com/js/js_async.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,250 @@
---
id: javascript-async-await
title: "JavaScript Async Await"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["async await", "await keyword", "async function", "try catch await", "Promise.all"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "async-await", "promises"]
raw_sources: ["https://www.w3schools.com/js/js_async_await.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async Await]]
## 🎯 한 줄 통찰 (One-line insight)
`async` and `await` make promises easier by letting you write asynchronous code like normal step-by-step code, with familiar `try...catch` error handling. [S1]
## 🧠 핵심 개념 (Core concepts)
- **They simplify promises** — `async` and `await` make promises easier by letting code be written like normal step-by-step code. [S1]
- **`async` returns a promise** — an `async` function returns a promise; its return value is what the promise resolves to. [S1]
- **`await` unwraps a promise** — `await` pauses inside the async function until the awaited promise resolves, giving back the value directly. [S1]
- **Error handling with try...catch** — wrap awaited calls in `try { ... } catch (error) { ... }` to handle rejections. [S1]
- **Sequential vs parallel** — awaiting one call after another runs them in sequence; `Promise.all([...])` runs them together and awaits all. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Linearize a promise chain** — replace `.then()` chaining with successive `await` calls inside an `async function`. [S1]
- **try/catch around await** — catch a rejected promise (e.g. `await fail()`) like a synchronous error. [S1]
- **Promise.all for parallelism** — start promises first, then `await Promise.all([p1, p2])` to collect results together. [S1]
## 📖 세부 내용 (Details)
**Promises approach (before)**
[S1]
```javascript
// Three functions to run in steps
function step1() {
return Promise.resolve("A");
}
function step2(value) {
return Promise.resolve(value + "B");
}
function step3(value) {
return Promise.resolve(value + "C");
}
// Run the three functions in steps
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.then(function(value) {
myDisplayer(value);
});
```
**async/await approach (after)**
The same logic reads like sequential code: [S1]
```javascript
// Function to run the three functions in steps
async function run() {
let v1 = await step1();
let v2 = await step2(v1);
let v3 = await step3(v2);
myDisplayer(v3);
}
run();
```
**The async keyword**
An `async` function returns a promise: [S1]
```javascript
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);}
);
```
**The await keyword**
`await` waits for a promise and returns its resolved value: [S1]
```javascript
function step1() {
return Promise.resolve("A");
}
async function run() {
let value = await step1();
myDisplayer(value);
}
run();
```
**Error handling with try...catch**
[S1]
```javascript
function fail() {
return Promise.reject("Failed");
}
async function run() {
try {
let value = await fail();
console.log(value);
} catch (error) {
console.log(error);
}
}
run();
```
**Sequential execution**
[S1]
```javascript
async function run() {
let a = await step1();
let b = await step2();
console.log(a, b);
}
```
**Parallel with Promise.all()**
Start the promises first, then await them together: [S1]
```javascript
async function run() {
let p1 = step1();
let p2 = step2();
let values = await Promise.all([p1, p2]);
console.log(values);
}
```
**fetch() with async/await**
[S1]
```javascript
async function loadData() {
try {
let response = await fetch("data.json");
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
loadData();
```
**Basic syntax with a Promise**
Awaiting a constructed promise: [S1]
```javascript
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
```
Without the reject parameter: [S1]
```javascript
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
```
**Waiting for a timeout**
[S1]
```javascript
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I love You !!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — the `run()` function linearizing step1/step2/step3, the `try...catch` around `await fail()`, and `await Promise.all([p1, p2])` — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Linearize a chain with await (language: JavaScript):
```javascript
async function run() {
let v1 = await step1();
let v2 = await step2(v1);
let v3 = await step3(v2);
myDisplayer(v3);
}
run();
```
Error handling and parallelism:
```javascript
async function run() {
try {
let values = await Promise.all([step1(), step2()]);
console.log(values);
} catch (error) {
console.log(error);
}
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Promise `.then()` chaining** — explicit, but reads as nested handler functions and requires returning each step. [S1]
- **async/await** — the same logic written like normal step-by-step code, with `try...catch` for errors; recommended for readability. Use sequential `await` for dependent steps and `Promise.all` for independent ones. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Promise]], [[JavaScript Async Fetch]], [[JavaScript Async Callbacks]], [[JavaScript Async Debug]]
- **참조 맥락:** The syntactic sugar over promises that most modern async data-fetching code uses.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async Await — https://www.w3schools.com/js/js_async_await.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Await" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,232 @@
---
id: javascript-async-callbacks
title: "JavaScript Async Callbacks"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Callbacks", "Callback functions", "Error-first callbacks", "Callback hell", "JS callbacks"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "callbacks", "asynchronous"]
raw_sources: ["https://www.w3schools.com/js/js_async_callbacks.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async Callbacks]]
## 🎯 한 줄 통찰 (One-line insight)
A callback is a function passed as an argument into another function, intended to run later — the first solution for sequencing asynchronous JavaScript. [S1]
## 🧠 핵심 개념 (Core concepts)
- **What a callback is** — a function passed as an argument into another function, intended for later execution, typically when an event occurs or an async operation completes. [S1]
- **Why callbacks exist** — async code finishes later, so you cannot return its result immediately; instead you pass a callback to run once the result is ready, enabling sequential control. [S1]
- **Error-first pattern** — pass two parameters, error first then data, so the function can handle failures gracefully. [S1]
- **Callback hell** — deeply nested callbacks create complex, hard-to-read structures that complicate debugging. [S1]
- **Modern alternatives** — Promises and async/await provide cleaner flow and better error handling, and modern asynchronous JavaScript does not use callbacks. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Pass-a-function-to-run-later** — give a function a callback parameter and invoke it once work is done (e.g. `myCalculator(5, 5, myDisplayer)`). [S1]
- **Error-first signature** — `callback(error, data)`; check `error` first and `return` early on failure. [S1]
- **Event-listener callback** — `addEventListener("click", displayDate)` runs the callback on the event. [S1]
## 📖 세부 내용 (Details)
**Event handling**
Callbacks handle user interactions through event listeners; the listener runs the callback when the user clicks: [S1]
```javascript
document.getElementById("myButton").addEventListener("click", displayDate);
```
**Asynchronous operations with setTimeout**
`setTimeout()` uses a callback that executes after the delay without freezing the page: [S1]
```javascript
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = "I love You !!";
}
```
**The timing problem**
Async code finishes later, so the result is not available immediately: [S1]
```javascript
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
```
**The callback idea**
Instead of reading the result directly, pass it into a function that runs when ready: [S1]
```javascript
function done(value) {
myDisplayer(value);
}
setTimeout(function() {
done(5);
}, 1000);
// What is result here?
```
**Sequence control — first approach (return then display)**
[S1]
```javascript
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}
let result = myCalculator(5, 5);
myDisplayer(result);
```
**Sequence control — second approach (display inside)**
[S1]
```javascript
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
```
**Using callbacks**
Pass the displayer in as a callback so the caller controls what happens with the result: [S1]
```javascript
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
```
**Error-first callbacks — success case**
[S1]
```javascript
function getData(callback) {
let ok = true;
if (ok) {
callback(null, "Data");
} else {
callback("Something failed", null);
}
}
getData(function(error, data) {
if (error) {
myDisplayer(error);
return;
}
myDisplayer(data);
});
```
**Error-first callbacks — failure case**
[S1]
```javascript
function getData(callback) {
let ok = false;
if (ok) {
callback(null, "Data");
} else {
callback("Something failed", null);
}
}
getData(function(error, data) {
if (error) {
myDisplayer(error);
return;
}
myDisplayer(data);
});
```
**Callback drawbacks (callback hell)**
Deeply nested callbacks become hard to read and debug: [S1]
```javascript
step1(function(r1) {
step2(r1, function(r2) {
step3(r2, function(r3) {
console.log(r3);
});
});
});
```
Modern asynchronous JavaScript does not use callbacks; Promises and async/await are recommended instead. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — the `myCalculator(5, 5, myDisplayer)` callback handoff, the error-first `getData` pattern, and the nested `step1/step2/step3` "callback hell" — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Pass a callback to run later (language: JavaScript):
```javascript
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
```
Error-first callback:
```javascript
getData(function(error, data) {
if (error) {
myDisplayer(error);
return;
}
myDisplayer(data);
});
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Callbacks** — the original async solution; pass a function to run later. Drawback: nesting becomes "callback hell," hard to read and chain. [S1]
- **Promises / async-await** — recommended modern alternatives providing cleaner flow and better error handling; modern asynchronous JavaScript does not use callbacks. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async Timeouts]], [[JavaScript Promise]], [[JavaScript Async Await]], [[JavaScript Async]]
- **참조 맥락:** The first solution to async sequencing, motivating Promises as the cleaner successor.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async Callbacks — https://www.w3schools.com/js/js_async_callbacks.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Callbacks" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,196 @@
---
id: javascript-async-debug
title: "JavaScript Async Debug"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Debugging async", "Debug fetch", "Promise debugging", "response.ok debugging", "Network tab"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "debugging", "asynchronous", "fetch"]
raw_sources: ["https://www.w3schools.com/js/js_async_debug.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async Debug]]
## 🎯 한 줄 통찰 (One-line insight)
Async bugs are hard because the code runs later — debug them by handling errors early, checking `response.ok`, logging between steps, and using the Network tab. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Async bugs run later** — async code often fails after your function has already returned, so it feels like nothing happened. [S1]
- **Handle rejections early** — unhandled promise rejections confuse beginners; handle errors early and clearly. [S1]
- **Fetch does not reject on HTTP errors** — fetch does not reject on errors like 404; you must check `response.ok`. [S1]
- **Logging a promise ≠ logging data** — log the response and status first; logging a promise is not the same as logging the data. [S1]
- **Use the Network tab** — it shows every request and is the fastest way to debug fetch problems. [S1]
- **Forgetting await is the top mistake** — it is the most common beginner mistake. [S1]
- **Promises can fail anywhere** — add logs between steps to find where a chain fails. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Wrap awaits in try/catch** — catch failures around awaited code. [S1]
- **Guard with response.ok / status** — check and short-circuit on HTTP errors before reading the body. [S1]
- **Log response details first** — log `response.status` and headers before assuming JSON. [S1]
- **Log between chain steps** — add `console.log` inside each `.then()`/`.catch()` to locate the failing step. [S1]
## 📖 세부 내용 (Details)
**Why async is hard**
Async bugs are difficult because the code runs later. Async code often fails after your function has already returned, which makes it feel like nothing happened. [S1]
**Missing error handling**
The unhandled version (with a trailing synchronous log running before the async work resolves): [S1]
```javascript
async function loadData() {
let response = await fetch("missing.json");
let data = await response.json();
console.log(data);
}
loadData();
console.log("Done");
```
**Add try/catch**
Handle errors early and clearly: [S1]
```javascript
async function loadData() {
try {
let response = await fetch("missing.json");
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
```
**Check response.ok**
Fetch does not reject on HTTP errors like 404, so check `response.ok`: [S1]
```javascript
async function loadData() {
try {
let response = await fetch("missing.json");
if (!response.ok) {
console.log("HTTP Error:", response.status);
return;
}
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Network error");
}
}
```
**Log response details first**
Logging a promise is not the same as logging the data — log the response and status first: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
console.log(response.status);
console.log(response.headers.get("content-type"));
}
```
**Forgetting await (incorrect)**
Forgetting `await` is the most common beginner mistake — this logs a promise: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
let data = response.json();
console.log(data);
}
```
Correct version: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
let data = await response.json();
console.log(data);
}
```
**Log between promise-chain steps**
Promises can fail anywhere in the chain; add logs between steps to find where it fails: [S1]
```javascript
fetch("data.json")
.then(function(response) {
console.log("Got response");
return response.json();
})
.then(function(data) {
console.log("Got data");
console.log(data);
})
.catch(function(error) {
console.log("Failed");
console.log(error);
});
```
**Debugging checklist**
[S1]
- Check the console for errors.
- Add try/catch around awaited code.
- Check `response.ok` and `response.status`.
- Use the Network tab (it shows every request).
- Use breakpoints on `await` lines.
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — the unhandled `loadData()` + `console.log("Done")`, the try/catch and `response.ok` guards, and the logged promise chain — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Robust fetch with guard and logging (language: JavaScript):
```javascript
async function loadData() {
try {
let response = await fetch("missing.json");
if (!response.ok) {
console.log("HTTP Error:", response.status);
return;
}
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Network error");
}
}
```
Log between chain steps to locate failures:
```javascript
fetch("data.json")
.then(function(response) { console.log("Got response"); return response.json(); })
.then(function(data) { console.log("Got data"); console.log(data); })
.catch(function(error) { console.log("Failed"); console.log(error); });
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async Fetch]], [[JavaScript Async Await]], [[JavaScript Promise]], [[JavaScript Async Callbacks]]
- **참조 맥락:** The practical troubleshooting capstone of the asynchronous study path.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async Debug — https://www.w3schools.com/js/js_async_debug.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Debug" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,235 @@
---
id: javascript-async-fetch
title: "JavaScript Async Fetch"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["fetch", "fetch API", "response.json", "response.ok", "HTTP request JavaScript", "XMLHttpRequest vs fetch"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "fetch", "asynchronous", "http"]
raw_sources: ["https://www.w3schools.com/js/js_async_fetch.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async Fetch]]
## 🎯 한 줄 통찰 (One-line insight)
`fetch()` is the modern, asynchronous way to request data from a server — it returns a promise for a Response, and you must read the body (and check `response.ok`) to get the actual data. [S1]
## 🧠 핵심 개념 (Core concepts)
- **fetch returns a promise** — `fetch()` is the modern way to request data from a server; it is asynchronous and returns a promise that becomes a response later. [S1]
- **Response is not the data** — the result is a `Response` object, not the JSON data; to get JSON you must read the body with `response.json()`, which itself returns a promise. [S1]
- **async/await is recommended** — `async` and `await` make fetch code easier to read; this is the recommended way for beginners. [S1]
- **404/500 do not reject** — fetch only rejects on network errors; a 404 response is not a rejected promise, so you must check `response.ok`. [S1]
- **Network errors reject** — a network error (offline mode, DNS errors) happens when the request cannot be completed and does reject the promise. [S1]
- **Forgetting await yields a promise** — omitting `await` on `response.json()` logs a promise instead of the data. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **fetch → json promise chain** — `fetch(url).then(r => r.json()).then(data => ...)`. [S1]
- **async/await fetch** — `let response = await fetch(url); let data = await response.json();`. [S1]
- **Guard with response.ok** — check `if (!response.ok)` to handle HTTP errors that fetch will not reject. [S1]
- **try/catch for network errors** — wrap the await calls to catch true network failures. [S1]
## 📖 세부 내용 (Details)
**fetch returns a promise, not the data**
`fetch()` does not return the data; it returns a promise that becomes a response later. The result is a `Response` object, not the JSON data: [S1]
```javascript
fetch("data.json")
.then(function(response) {
console.log(response);
});
```
**Reading the body**
To get JSON you must read the response body; `response.json()` returns a promise. The following is a promise chain: [S1]
```javascript
fetch("data.json")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
```
**async/await version (recommended)**
`async` and `await` make fetch code easier to read; this is the recommended way for beginners: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
let data = await response.json();
console.log(data);
}
loadData();
```
**Checking response.ok (HTTP errors)**
A common beginner mistake is expecting fetch to fail on 404 or 500. Fetch only rejects on network errors; a 404 response is not a rejected promise — you must check `response.ok`. The following handles HTTP errors correctly: [S1]
```javascript
async function loadData() {
let response = await fetch("missing.json");
if (!response.ok) {
console.log("HTTP Error:", response.status);
return;
}
let data = await response.json();
console.log(data);
}
loadData();
```
**Network errors with try...catch**
A network error happens when the request cannot be completed (offline mode, DNS errors); network errors reject the promise: [S1]
```javascript
async function loadData() {
try {
let response = await fetch("data.json");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Network error");
}
}
```
**Forgetting await on response.json()**
Forgetting `await` gives you a promise instead of data; the following logs a promise — you must use `await` to get the JSON: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
let data = response.json();
console.log(data);
}
```
Correct version: [S1]
```javascript
async function loadData() {
let response = await fetch("data.json");
let data = await response.json();
console.log(data);
}
```
**Callback (XMLHttpRequest) vs fetch**
Callback approach with XMLHttpRequest: [S1]
```javascript
function loadFile(callback) {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onload = function() {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback("HTTP Error: " + xhr.status, null);
}
};
xhr.onerror = function() {
callback("Network Error", null);
};
xhr.send();
}
loadFile(function(error, data) {
if (error) {
console.log(error);
return;
}
console.log(data);
});
```
Fetch approach: [S1]
```javascript
async function loadFile() {
try {
let response = await fetch("data.json");
if (!response.ok) {
throw new Error("HTTP Error: " + response.status);
}
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
loadFile();
```
**Callback vs Promise/async-await comparison**
[S1]
| Callback | Promise / async-await |
|----------|----------------------|
| You pass a function to run later | You wait for a promise |
| Manual error-first pattern | Built-in error flow |
| Can become nested | Reads like normal code |
| Hard to chain steps | Easy to chain steps |
**Debugging hint**
If fetch is not working, check the console, then the Network tab: is the file path correct, is the status code 200, is the response JSON. Most fetch bugs are not JavaScript bugs — they are path and response problems. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — the `fetch().then(r => r.json())` chain, the `await fetch` + `response.ok` guard, and the XMLHttpRequest-vs-fetch comparison — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Recommended async/await fetch with HTTP-error guard (language: JavaScript):
```javascript
async function loadData() {
let response = await fetch("missing.json");
if (!response.ok) {
console.log("HTTP Error:", response.status);
return;
}
let data = await response.json();
console.log(data);
}
loadData();
```
Promise-chain form:
```javascript
fetch("data.json")
.then(function(response) { return response.json(); })
.then(function(data) { console.log(data); });
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Callback (XMLHttpRequest)** — pass a function to run later; manual error-first pattern; can become nested and is hard to chain. [S1]
- **Promise / async-await (fetch)** — wait for a promise; built-in error flow; reads like normal code and is easy to chain. Recommended for beginners. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async Await]], [[JavaScript Promise]], [[JavaScript Async Debug]], [[JavaScript Async Callbacks]]
- **참조 맥락:** The practical application of promises and async/await for retrieving server data.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async Fetch — https://www.w3schools.com/js/js_async_fetch.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Fetch" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,122 @@
---
id: javascript-async-timeouts
title: "JavaScript Async Timeouts"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["setTimeout", "setInterval", "JS timers", "Timeout scheduling", "Delayed execution"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "settimeout", "setinterval", "timers"]
raw_sources: ["https://www.w3schools.com/js/js_async_timeouts.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Async Timeouts]]
## 🎯 한 줄 통찰 (One-line insight)
`setTimeout()` schedules a function to run after a delay in milliseconds, and `setInterval()` repeats it every interval — both delay execution without freezing the browser. [S1]
## 🧠 핵심 개념 (Core concepts)
- **setTimeout schedules once** — `setTimeout()` schedules a function to run after a delay in milliseconds; it is an async operation used to delay code execution without freezing the browser. [S1]
- **setInterval repeats** — with `setInterval()` you specify a function to be executed for each interval. [S1]
- **Pass the function, not its call** — when passing a function as an argument, do not use parentheses; `setTimeout(myFunction, 3000)` is right, `setTimeout(myFunction(), 3000)` is wrong. [S1]
- **Timeouts lead into callbacks** — a callback runs after another function finishes, and callbacks were the first solution for asynchronous JavaScript. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Named-callback scheduling** — `setTimeout(myFunction, ms)` defers a named function. [S1]
- **Anonymous wrapper for arguments** — wrap the call in an anonymous function, `setTimeout(function(){ myFunction("...") }, ms)`, when you need to pass arguments. [S1]
- **Repeating clock with setInterval** — `setInterval(fn, ms)` re-runs a function on a fixed cadence (e.g. a live clock). [S1]
## 📖 세부 내용 (Details)
**The setTimeout() method**
The `setTimeout()` method schedules a function to run after a delay in milliseconds. It is an async operation used to delay code execution without freezing the browser. [S1]
```javascript
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = "I love You !!";
}
```
In the example above, `myFunction` is passed to `setTimeout()` as an argument. `3000` is the number of milliseconds before `myFunction` will be called. When you pass a function as an argument, remember not to use parenthesis. [S1]
**Passing arguments with an anonymous function**
[S1]
```javascript
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
```
**The setInterval() method**
When using the `setInterval()` method, you can specify a function to be executed for each interval. In the example below, `myFunction` is passed to `setInterval()` as an argument and `1000` is the number of milliseconds between every time `myFunction` will be called. [S1]
```javascript
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
```
**Note (right vs wrong):**
[S1]
- Right: `setTimeout(myFunction, 3000);`
- Wrong: `setTimeout(myFunction(), 3000);`
**Next step**
A callback runs after another function finishes. Callbacks were the first solution for asynchronous JavaScript. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — deferring a message with `setTimeout`, passing an argument via an anonymous wrapper, and a live clock with `setInterval` — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Schedule a named function once (language: JavaScript):
```javascript
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = "I love You !!";
}
```
Pass an argument via an anonymous wrapper:
```javascript
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
```
Repeat every interval:
```javascript
setInterval(myFunction, 1000);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async]], [[JavaScript Async Callbacks]], [[JavaScript Asynchronous]], [[JavaScript Promise]]
- **참조 맥락:** The first concrete async tool — timers — that motivates callbacks as the next solution.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Async Timeouts — https://www.w3schools.com/js/js_async_timeouts.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Timeouts" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,136 @@
---
id: javascript-asynchronous
title: "JavaScript Asynchronous"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Async JavaScript", "Asynchronous programming", "JS async overview", "Async study path", "Non-blocking JavaScript"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "asynchronous", "concurrency"]
raw_sources: ["https://www.w3schools.com/js/js_asynchronous.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Asynchronous]]
## 🎯 한 줄 통찰 (One-line insight)
Asynchronous code lets a program start a long-running task and continue with other work before that task finishes, instead of executing strictly one blocking line at a time. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Default flow is synchronous** — JavaScript executes code one line at a time, and each line must finish before the next can run. [S1]
- **Async changes the order** — async code allows a program to start a long-running task (like fetching data from a file) and continue with other tasks before the first one finishes. [S1]
- **A learning progression** — the page frames async as a curriculum to "Learn Asynchronous JavaScript in the Right Order," moving from timeouts → callbacks → promises → async/await → fetch → debugging. [S1]
- **Async ≠ parallel** — parallel means doing multiple things at the same time on different processors; asynchronous means switching between tasks, not necessarily running them simultaneously. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Defer-and-continue** — schedule work to run later (e.g. via a timer) so the current call stack can finish first, producing an out-of-order result such as A, C, B. [S1]
- **Result-not-ready trap** — reading the result of an async operation immediately yields `undefined` because the async code has not finished yet. [S1]
- **Restaurant model** — place the order (async call), do other things while it is prepared, and the server brings the food (the callback). [S1]
## 📖 세부 내용 (Details)
**What is asynchronous code?**
Async code allows a program to start a long-running task (like fetching data from a file) and continue with other tasks before the first one finishes. By default JavaScript executes from top to bottom, one line at a time; each line must finish before the next can run. Async programming can change this execution order. [S1]
**Synchronous flow**
Calls run in source order, producing output A, B, C: [S1]
```javascript
myDisplayer("A");
myDisplayer("B");
myDisplayer("C");
```
**Asynchronous flow with setTimeout**
When a timer defers a call, the output order changes to A, C, B — the deferred `B` runs after the synchronous `C`: [S1]
```javascript
myDisplayer("A");
setTimeout(function() {
myDisplayer("B");
}, 1000);
myDisplayer("C");
```
**The "result is not ready yet" challenge**
Beginners often expect async results immediately. Here the result is `undefined` because the async code has not finished yet: [S1]
```javascript
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
```
**Core async concepts**
The module covers these building blocks: [S1]
| Concept | Description |
|---------|-------------|
| Synchronous | The JavaScript standard flow is executing line by line |
| Timers | Allows code to run while other code is waiting |
| Callbacks | Callbacks were the first solution for async JavaScript |
| Events | Stores a callback function waiting to be executed |
| Promises | Tools to handle asynchronous operations cleanly |
| Async/Await | The clean and modern way to handle async code |
**Asynchronous vs parallel**
Parallel means doing multiple things at the same time on different processors. Asynchronous means switching between tasks, not necessarily running them simultaneously. [S1]
**Restaurant analogy**
Place your order (async call); sit down and do other things while the chef makes it; the server brings the food (the callback). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page itself is an index/study path; its illustrative snippets (synchronous A/B/C, deferred A/C/B, and the `undefined` result trap) are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Deferring work so later lines run first (language: JavaScript):
```javascript
myDisplayer("A");
setTimeout(function() {
myDisplayer("B");
}, 1000);
myDisplayer("C");
```
Demonstrating the not-yet-ready result:
```javascript
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async Timeouts]], [[JavaScript Async Callbacks]], [[JavaScript Promise]], [[JavaScript Async Await]], [[JavaScript Async Fetch]]
- **참조 맥락:** The conceptual entry point for the entire asynchronous JavaScript study path.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Asynchronous — https://www.w3schools.com/js/js_asynchronous.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Asynchronous" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,212 @@
---
id: javascript-bigint
title: "JavaScript BigInt"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["BigInt", "arbitrary precision integer", "n suffix", "BigInt()", "ES2020 integers", "large integers"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "bigint", "number", "es2020"]
raw_sources: ["https://www.w3schools.com/js/js_bigint.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript BigInt]]
## 🎯 한 줄 통찰 (One-line insight)
`BigInt` is a JavaScript data type for whole numbers too large for the ordinary `Number` type — it represents integers of arbitrary size (limited only by memory), but cannot hold decimals and cannot be freely mixed with `Number` values. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Purpose** — `BigInt` handles integers larger than the safe-integer limits of the `Number` type, representing integers of any size constrained only by available memory. [S1]
- **Why it exists** — JavaScript Numbers are 64-bit floating point (IEEE 754) and only accurate up to 15 digits; safe integers run from `9007199254740991` (`2⁵³ 1`) down to `-9007199254740991`. [S1]
- **Two creation forms** — an integer literal with an `n` suffix, or the `BigInt()` constructor (from a string or a Number). [S1]
- **It is a distinct type** — `typeof` a BigInt is `"bigint"`; it is the third numeric-family data type, making eight JavaScript types in total. [S1]
- **No mixing without conversion** — arithmetic between a BigInt and a Number throws a `TypeError`; convert explicitly with `Number()` or `BigInt()`. [S1]
- **No decimals** — a BigInt cannot have decimal values. [S1]
- **ES2020 feature** — supported in modern browsers since September 2020. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`n` literal vs constructor** — `999999999999999n` (literal) or `BigInt("999999999999999")` (string constructor avoids the 15-digit accuracy loss). [S1]
- **Explicit cross-type conversion** — to combine with a Number, wrap one side: `Number(x) + y`. [S1]
- **Loose vs strict equality** — `10n == 10` is `true`, but `10n === 10` is `false` because the types differ. [S1]
- **No `>>>` on BigInt** — unsigned right shift is not allowed with BigInts. [S1]
## 📖 세부 내용 (Details)
**What is JavaScript BigInt?** — `BigInt` is a data type that can represent integers of any size, limited only by available memory. [S1]
**JavaScript Accuracy / Numbers are 64-bits Floating Point** — JavaScript Numbers are only accurate up to 15 digits and use 64-bit floating-point format (IEEE 754). The safe integer range is `9007199254740991` (`2⁵³ 1`) to `-9007199254740991` (`(2⁵³ 1)`). [S1]
```javascript
// 15 digits:
let x = 999999999999999;
// 16 digits:
let y = 9999999999999999;
```
```javascript
// MAX = 9007199254740991
let x = Number.MAX_SAFE_INTEGER;
// MIN = -9007199254740991
let y = Number.MIN_SAFE_INTEGER;
```
```javascript
// Max (accurate)
let x = 9007199254740991;
// Max + 10 (inaccurate)
let y = x + 10;
```
**How to Create a BigInt** — use an integer literal with an `n` suffix, or the `BigInt()` constructor: [S1]
```javascript
// Using an integer literal with an n suffix:
let x = 999999999999999n;
// Using the BigInt() constructor with a string:
let y = BigInt("999999999999999");
```
**BigInt is a JavaScript Datatype**`typeof` returns `"bigint"`: [S1]
```javascript
let x = BigInt(999999999999999);
let type = typeof x;
```
BigInt is the third numeric data type. The eight JavaScript data types are: String, Number, Bigint, Boolean, Undefined, Null, Symbol, Object. [S1]
**Arithmetic Operators** — BigInt supports `+`, `-`, `++`, `--`, `*`, `/`, `%`, `**`: [S1]
```javascript
let x = 9007199254740995n;
let y = 9007199254740995n;
let z = x * y;
```
**Mixing BigInt and Numbers** — mixing throws a `TypeError`; convert explicitly: [S1]
```javascript
let x = 10n;
let y = 5;
let z = x + y; // ❌ TypeError
```
```javascript
let x = 10n;
let y = 5;
let z = Number(x) + y;
```
**BigInt / Number Conversions** — BigInt to Number with `Number(value)`, Number to BigInt with `BigInt(value)`; large conversions may result in Infinity or precision loss. [S1]
**BigInt Decimals** — a BigInt cannot have decimals, and mixing with division throws an error: [S1]
```javascript
let x = 5n;
let y = x / 2;
// ❌ Error: Cannot mix BigInt and other types, use explicit conversion.
```
**Comparison Operators** — BigInt supports `<`, `>`, `==`, `===`, `!==`, `<=`, `>=`. Strict equality between a BigInt and a Number is always false: [S1]
```javascript
// true
let x = (10n > 5n);
// false (different types)
let y = (10n === 10);
// true (loose equality)
let z = (10n == 10);
```
**Bitwise Operators** — BigInt supports `&`, `|`, `^`, `~`: [S1]
```javascript
let a = 5n; // 0101
let b = 3n; // 0011
let x = (a & b); // 1n (0001)
let y = (a | b); // 7n (0111)
let z = (a ^ b); // 6n (0110)
let n = (~a); // -6n
```
**Bitwise Shift Operators** — BigInt supports `<<` and `>>`. Unsigned right shift (`>>>`) is not allowed with BigInts: [S1]
```javascript
let big = 10n; // binary: 1010
let x = (big << 2n); // 40n (101000)
let y = (big >> 1n); // 5n (0101)
```
**BigInt Hex, Octal and Binary** [S1]
```javascript
let num = 256n;
let oct = 0o400n;
let hex = 0x100n;
let bin = 0b100000000n;
```
**Precision Curiosity** — Number rounding makes two distinct large integers compare equal, while BigInt keeps them distinct: [S1]
```javascript
9007199254740992 === 9007199254740993; // is true !!!
```
```javascript
9007199254740992n === 9007199254740993n; // is false !!!
```
**Summary** — BigInt enables arbitrary-precision integer arithmetic. Limitations: no decimal support, incompatibility with `Math` functions, and `JSON.stringify()` cannot handle BigInts. [S1]
**Browser Support** — BigInt is an ES2020 feature, fully supported in modern browsers since September 2020. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — creating BigInts via the `n` literal and the `BigInt()` constructor, multiplying large values, the explicit `Number(x) + y` conversion, and the precision-comparison curiosity. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Create a BigInt (language: JavaScript):
```javascript
let a = 999999999999999n;
let b = BigInt("999999999999999");
```
Mix safely with a Number via explicit conversion:
```javascript
let x = 10n;
let y = 5;
let z = Number(x) + y;
```
Compare with loose vs strict equality:
```javascript
10n == 10; // true
10n === 10; // false
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Use `Number`** for everyday math and any value within the safe-integer range (`±9007199254740991`) or requiring decimals. [S1]
- **Use `BigInt`** when integers exceed the safe-integer range and must stay exact (the page cites cryptography, IDs, and timestamps), accepting that decimals, `Math` functions, and `JSON.stringify()` are unavailable. [S1]
- **Never mix the two directly** — arithmetic across the types throws a `TypeError`; convert one side explicitly. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Numbers]], [[JavaScript Number Properties]], [[JavaScript Bitwise]], [[JavaScript Data Types]]
- **참조 맥락:** Referenced when exact large-integer arithmetic is required beyond the Number safe-integer limit.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript BigInt — https://www.w3schools.com/js/js_bigint.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript BigInt" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,162 @@
---
id: javascript-bitwise
title: "JavaScript Bitwise"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["bitwise operators", "bit manipulation", "AND OR XOR", "bit shift", "two's complement", "32-bit operations"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "bitwise", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_bitwise.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Bitwise]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript bitwise operators work bit-by-bit on the binary representation of numbers — even though numbers are stored as 64-bit floats, every bitwise operation is performed on 32-bit binary numbers and returns a standard number. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Seven bitwise operators** — AND (`&`), OR (`|`), XOR (`^`), NOT (`~`), zero fill left shift (`<<`), signed right shift (`>>`), and zero fill right shift (`>>>`). [S1]
- **64-bit storage, 32-bit operations** — JavaScript stores numbers as 64-bit floating point numbers, but all bitwise operations are performed on 32-bit binary numbers. [S1]
- **NOT and signed shift can produce negatives** — `~5` returns `-6`, and `-5 >> 1` returns `-3`, because of two's complement representation. [S1]
- **Bitwise assignment operators** — shift assignments (`<<=`, `>>=`, `>>>=`) and bitwise assignments (`&=`, `^=`, `|=`) combine the operation with assignment. [S1]
- **Base conversion via bitwise** — decimal-to-binary and binary-to-decimal can be done with `(dec >>> 0).toString(2)` and `parseInt(bin, 2).toString(10)`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Per-bit combination** — `&`, `|`, `^` compare each pair of bits; `~` inverts every bit. [S1]
- **Shift to multiply/divide by powers of two** — `5 << 1` doubles to `10`; `5 >>> 1` halves to `2`. [S1]
- **Unsigned coercion for printing** — `(dec >>> 0)` forces an unsigned 32-bit view before `.toString(2)` to render binary. [S1]
## 📖 세부 내용 (Details)
**Bitwise Operators** — JavaScript provides seven bitwise operators: [S1]
| Operator | Name | Description |
|----------|------|-------------|
| `&` | AND | Sets each bit to 1 if both bits are 1 |
| `\|` | OR | Sets each bit to 1 if one of two bits is 1 |
| `^` | XOR | Sets each bit to 1 if only one of two bits is 1 |
| `~` | NOT | Inverts all the bits |
| `<<` | Zero fill left shift | Shifts left by pushing zeros in from the right and let the leftmost bits fall off |
| `>>` | Signed right shift | Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
| `>>>` | Zero fill right shift | Shifts right by pushing zeros in from the left, and let the rightmost bits fall off |
**Note:** JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. [S1]
**Bitwise AND** — returns `1`: [S1]
```javascript
let x = 5 & 1;
```
**Bitwise OR** — returns `5`: [S1]
```javascript
let x = 5 | 1;
```
**Bitwise XOR** — returns `4`: [S1]
```javascript
let x = 5 ^ 1;
```
**Bitwise NOT** — returns `-6`: [S1]
```javascript
let x = ~5;
```
**Left Shift (`<<`)** — returns `10`: [S1]
```javascript
let x = 5 << 1;
```
**Signed Right Shift (`>>`)** — returns `-3`: [S1]
```javascript
let x = -5 >> 1;
```
**Zero Fill Right Shift (`>>>`)** — returns `2`: [S1]
```javascript
let x = 5 >>> 1;
```
**Operator results summary** (verbatim values from the page) [S1]
| Expression | Result |
|------------|--------|
| `5 & 1` | `1` |
| `5 \| 1` | `5` |
| `5 ^ 1` | `4` |
| `~5` | `-6` |
| `5 << 1` | `10` |
| `-5 >> 1` | `-3` |
| `5 >>> 1` | `2` |
**Bitwise assignment operators** — the page documents shift assignment operators (`<<=`, `>>=`, `>>>=`) and bitwise assignment operators (`&=`, `^=`, `|=`). [S1]
**Converting Decimal to Binary** [S1]
```javascript
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
```
**Converting Binary to Decimal** [S1]
```javascript
function bin2dec(bin){
return parseInt(bin, 2).toString(10);
}
```
The page also includes binary-representation tables showing decimal values and their binary form, and two's-complement format for negative numbers. The exact full numeric contents of those tables were not captured verbatim in the fetched source rendering: Not found in source.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — the seven single-operator demonstrations and the `dec2bin` / `bin2dec` conversion helpers. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Single bitwise operations (language: JavaScript):
```javascript
let a = 5 & 1; // 1
let b = 5 | 1; // 5
let c = 5 ^ 1; // 4
let d = ~5; // -6
let e = 5 << 1; // 10
let f = -5 >> 1; // -3
let g = 5 >>> 1; // 2
```
Base conversion helpers:
```javascript
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function bin2dec(bin){
return parseInt(bin, 2).toString(10);
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Operators]], [[JavaScript Numbers]], [[JavaScript BigInt]], [[JavaScript Number Properties]]
- **참조 맥락:** Referenced when working with flags, masks, low-level math, or base conversions.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Bitwise — https://www.w3schools.com/js/js_bitwise.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Bitwise" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,217 @@
---
id: javascript-booleans
title: "JavaScript Booleans"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["boolean", "true false", "JS booleans", "Boolean function", "truthy falsy"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "boolean", "truthy", "data-types"]
raw_sources: ["https://www.w3schools.com/js/js_booleans.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Booleans]]
## 🎯 한 줄 통찰 (One-line insight)
A Boolean is a primitive type with only two values — `true` or `false` — and the boolean value of an expression is the basis for all JavaScript comparisons and conditions. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Two values only** — a Boolean can only have one of two values: `true` or `false`, written in lowercase and without quotes. [S1]
- **Comparisons return booleans** — all JavaScript comparison operators (`==`, `!=`, `<`, `>`) return `true` or `false`. [S1]
- **Drives control flow** — booleans are used in `if` statements and loops to decide which code blocks run. [S1]
- **`Boolean()` evaluates truthiness** — the `Boolean()` function reports whether an expression or variable is true. [S1]
- **Truthy vs falsy** — everything with a "value" is true; everything without a "value" is false. [S1]
- **Avoid Boolean objects** — booleans can be created as objects with `new Boolean()`, but this should not be done. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Coerce-to-boolean check** — wrap an expression in `Boolean(...)` (or rely on an expression like `(10 > 9)`) to obtain its truth value. [S1]
- **Truthiness rule** — empty arrays `[]` and empty objects `{}` are truthy because all objects evaluate to true; `0`, `""`, `undefined`, `null`, `NaN`, and `false` are falsy. [S1]
- **Never compare a primitive boolean to a Boolean object** — `(x == y)` may be true while `(x === y)` is false, and two objects always compare as not equal. [S1]
## 📖 세부 내용 (Details)
**The Boolean data type** [S1]
In JavaScript, a Boolean is a primitive data type that can only have one of two values: `true` or `false`. The boolean value of an expression is the basis for all JavaScript comparisons and conditions. `true` and `false` are boolean data types, are the only possible boolean values, and must be written in lowercase and without quotes.
**Boolean use cases** [S1]
Very often, in programming, you will need a data type that can represent one of two values, like: yes or no; on or off; true or false. Boolean values are fundamental for logical operations and control flow.
**Comparisons** [S1]
All JavaScript comparison operators (like `==`, `!=`, `<`, `>`) return `true` or `false`. Given that `x = 5`:
| Description | Example | Returns |
|---|---|---|
| Equal to | (x == 8) | false |
| Not equal to | (x != 8) | true |
| Greater than | (x > 8) | false |
| Less than | (x < 8) | true |
```javascript
let x = 5;
(x == 8); // equals false
(x != 8); // equals true
```
**Conditions** [S1]
Booleans are extensively used in `if` statements to determine which code blocks to execute.
| Example | Result |
|---|---|
| if (day == "Monday") | true or false |
| if (salary > 9000) | true or false |
| if (age < 18) | true or false |
```javascript
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
```
**Loops** [S1]
Booleans are extensively used in loops to determine the looping condition.
| Description | Example |
|---|---|
| For loop | for (i = 0; i < 5; i++) |
| While loop | while (i < 10) |
| For in loop | for (x in person) |
| For of loop | for (x of cars) |
```javascript
while (i < 10) {
text += i;
i++;
}
```
**The `Boolean()` function** [S1]
You can use the `Boolean()` function to find out if an expression (or a variable) is true:
```javascript
Boolean(10 > 9)
```
Or even easier:
```javascript
(10 > 9)
```
**Everything with a "value" is true** [S1]
The following all evaluate to true: `100`, `3.14`, `-15`, `true`, `"Hello"`, `"false"`, `(7 + 1 + 3.14)`, `[ ]`, `{ }`.
Note: In JavaScript, both an empty array `[ ]` and an empty object `{ }` are truthy because they are objects. All objects in JavaScript evaluate to true in a boolean context, regardless of their content.
**Everything without a "value" is false** [S1]
The following all evaluate to false: `0`, `""`, `undefined`, `null`, `NaN`, `false`.
The boolean value of `0` (zero) is false:
```javascript
let x = 0;
Boolean(x);
```
The boolean value of `-0` (minus zero) is false:
```javascript
let x = -0;
Boolean(x);
```
The boolean value of `""` (empty string) is false:
```javascript
let x = "";
Boolean(x);
```
The boolean value of `undefined` is false:
```javascript
let x;
Boolean(x);
```
The boolean value of `null` is false:
```javascript
let x = null;
Boolean(x);
```
The boolean value of `false` is false:
```javascript
let x = false;
Boolean(x);
```
The boolean value of `NaN` is false:
```javascript
let x = 10 / "Hallo";
Boolean(x);
```
**JavaScript booleans as objects** [S1]
Normally JavaScript booleans are primitive values created from literals:
```javascript
let x = false;
```
But booleans can also be defined as objects with the keyword `new`:
```javascript
let y = new Boolean(false);
```
```javascript
let x = false;
let y = new Boolean(false);
// typeof x returns boolean
// typeof y returns object
```
Warning: Do not create Boolean objects. The `new` keyword complicates the code and slows down execution speed. Boolean objects can produce unexpected results.
Booleans and boolean objects cannot be safely compared:
```javascript
let x = Boolean(false);
let y = new Boolean(false);
// (x == y) returns true
// (x === y) returns false
```
Comparing two JavaScript objects always returns false.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — comparison results, an `if/else` greeting, a `while` accumulation loop, and `Boolean()` truthiness checks across falsy values. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Check truthiness of an expression:
```javascript
Boolean(10 > 9)
```
Detect a falsy value:
```javascript
let x = "";
Boolean(x); // false
```
Avoid Boolean objects (anti-pattern noted by source):
```javascript
let y = new Boolean(false); // typeof y returns object
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source explicitly warns against the `new Boolean()` object form as an anti-pattern.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Comparisons]], [[JavaScript If Else]], [[JavaScript Logical]], [[JavaScript Data Types]]
- **참조 맥락:** Underlies every condition and comparison; central to truthy/falsy reasoning in conditionals and loops.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Booleans — https://www.w3schools.com/js/js_booleans.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Booleans" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,169 @@
---
id: javascript-break
title: "JavaScript Break"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["break statement", "JS break", "labeled break", "break continue", "break label"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "break", "loops", "labels", "control-flow"]
raw_sources: ["https://www.w3schools.com/js/js_break.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Break]]
## 🎯 한 줄 통찰 (One-line insight)
The `break` statement jumps out of a loop or switch; with a label, it can jump out of any code block. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Jumps out** — the `break` statement "jumps out" of loops and switches, terminating execution immediately. [S1]
- **Break in loops** — when `break` is reached in a loop, the loop terminates immediately and control transfers to the statements following the loop; no further iterations execute. [S1]
- **Break in a switch** — in a `switch`, `break` exits the block after a matching case executes; without it, execution falls through to subsequent cases. [S1]
- **Labels** — a label is an identifier followed by a colon (`labelname: statement;`), and `break labelname;` jumps out of the labeled block. [S1]
- **Only break and continue jump out of a block** — `break` and `continue` are the only JavaScript statements that can jump out of a code block; without a label, `break` only exits loops or switches. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Early exit on a sentinel** — test a condition inside the loop and `break` when it is met. [S1]
- **Labeled break for nested loops** — name outer/inner loops and `break loop1;` / `break loop2;` to control exactly which loop terminates. [S1]
- **Break out of a plain code block** — label a `{ ... }` block and `break label;` to skip the remaining statements. [S1]
## 📖 세부 내용 (Details)
**The break statement** [S1]
The `break` statement "jumps out" of loops and switches, terminating execution of a loop or switch statement immediately.
**Break in loops** [S1]
When `break` is encountered in a loop, the loop terminates immediately and control transfers to the statements following the loop. No further iterations execute.
```javascript
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
```
**Break in a switch** [S1]
In a `switch` statement, `break` exits the block after a matching case executes. Without it, execution "falls through" to subsequent cases.
```javascript
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
```
**JavaScript labels** [S1]
A label is an identifier followed by a colon: `labelname: statement;`. A labeled break uses the syntax `break labelname;`.
**Break to loop1** [S1]
```javascript
let text = "";
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { break loop1; }
text += i;
}
}
```
**Break to loop2** [S1]
```javascript
let text = "";
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { break loop2; }
text += i;
}
}
```
**Break out of a code block** [S1]
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
break list;
text += cars[2] + "<br>";
text += cars[3] + "<br>";
}
```
**Note** [S1]
`break` and `continue` are the only JavaScript statements that can "jump out of" a code block. Without a label, `break` only exits loops or switches; with a label, it exits any code block.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — early-exiting a `for` loop at `i === 3`, exiting `switch` cases, labeled breaks targeting `loop1`/`loop2`, and breaking out of a labeled `list:` block. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Early exit from a loop:
```javascript
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
```
Labeled break out of an outer loop:
```javascript
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { break loop1; }
text += i;
}
}
```
Break out of a labeled code block:
```javascript
list: {
text += cars[0] + "<br>";
break list;
text += cars[2] + "<br>";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Loops]], [[JavaScript For Loop]], [[JavaScript While Loop]], [[JavaScript Switch]]
- **참조 맥락:** Used to terminate loops/switches early; paired with `continue` as the only block-jumping statements.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Break — https://www.w3schools.com/js/js_break.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Break" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,181 @@
---
id: javascript-class-inheritance
title: "JavaScript Class Inheritance"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["extends", "super", "getters and setters", "class hoisting", "subclass"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "classes", "inheritance", "oop"]
raw_sources: ["https://www.w3schools.com/js/js_class_inheritance.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Class Inheritance]]
## 🎯 한 줄 통찰 (One-line insight)
Use `extends` to make one class inherit all methods of another and `super()` to reach the parent's constructor; classes also support `get`/`set` accessors and, unlike functions, are not hoisted. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`extends` for inheritance** — a class created with `extends` acquires all methods from another class. [S1]
- **`super()` references the parent** — calling `super()` in the constructor accesses parent properties and methods. [S1]
- **Inheritance aids reuse** — inheritance is useful for code reusability. [S1]
- **Getters and setters** — classes support `get` and `set` keywords for special property handling. [S1]
- **Getter access has no parentheses** — even though the getter is a method, you do not use parentheses to get the property value. [S1]
- **Classes are not hoisted** — unlike functions, classes must be declared before use. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Subclass = `extends` + `super(...)`** — pass parent constructor arguments through `super()`, then add subclass-specific state. [S1]
- **Underscore backing field for accessors** — store the value in `_carname` and expose it via `get carname()` / `set carname(x)` to avoid name collision with the accessor. [S1]
- **Declare before use** — because classes aren't hoisted, place the declaration ahead of any `new`. [S1]
## 📖 세부 내용 (Details)
**Class Inheritance**
To create class inheritance, use the `extends` keyword; the subclass acquires all methods of the parent. `super()` refers to the parent class, and calling it in the constructor accesses parent properties and methods. Inheritance is useful for code reusability: [S1]
```javascript
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
let myCar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = myCar.show();
```
**Getters and Setters**
Classes support getters and setters using the `get` and `set` keywords: [S1]
```javascript
class Car {
constructor(brand) {
this.carname = brand;
}
get cnam() {
return this.carname;
}
set cnam(x) {
this.carname = x;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = myCar.cnam;
```
**Note:** Even if the getter is a method, you do not use parentheses when you want to get the property value. [S1]
Using an underscore backing field so the accessor name matches the property: [S1]
```javascript
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
set carname(x) {
this._carname = x;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = myCar.carname;
```
Using the setter to change the value: [S1]
```javascript
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
set carname(x) {
this._carname = x;
}
}
const myCar = new Car("Ford");
myCar.carname = "Volvo";
document.getElementById("demo").innerHTML = myCar.carname;
```
**Hoisting**
Class declarations are not hoisted; classes must be declared before use: [S1]
```javascript
//You cannot use the class yet.
//myCar = new Car("Ford") will raise an error.
class Car {
constructor(brand) {
this.carname = brand;
}
}
//Now you can use the class:
const myCar = new Car("Ford")
```
For other declarations, like functions, you will NOT get an error when you try to use it before it is declared, because the default behavior of JavaScript declarations is hoisting. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The `Car` / `Model` pair is the running applied example for `extends` and `super()`; the `_carname` accessor examples demonstrate getters/setters, and the hoisting snippet shows the declare-before-use requirement. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Subclass with `extends` and `super()` (language: JavaScript):
```javascript
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
```
Getter/setter with an underscore backing field:
```javascript
get carname() { return this._carname; }
set carname(x) { this._carname = x; }
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Classes]], [[JavaScript Class Static]], [[JavaScript Objects]], [[JavaScript Object Accessors]]
- **참조 맥락:** Builds on JavaScript Classes by adding inheritance (`extends`/`super`), accessors, and hoisting behavior.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Class Inheritance — https://www.w3schools.com/js/js_class_inheritance.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Class Inheritance" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,112 @@
---
id: javascript-class-static
title: "JavaScript Class Static"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["static methods", "static keyword", "class-level method", "Car.hello", "static members"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "classes", "static", "oop"]
raw_sources: ["https://www.w3schools.com/js/js_class_static.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Class Static]]
## 🎯 한 줄 통찰 (One-line insight)
Static methods are defined with the `static` keyword on the class itself and can only be called on the class, not on its objects — pass an object in as a parameter if a static method needs instance data. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Static methods live on the class** — static class methods are defined on the class itself. [S1]
- **Call on the class, not the object** — you cannot call a `static` method on an object, only on an object class. [S1]
- **Use a parameter for instance data** — to use an object within a static method, send it as a parameter. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`static` for class-level utilities** — declare methods with `static` when they belong to the class rather than to any single instance. [S1]
- **Inject the instance** — when a static method needs object state, pass the object in (e.g. `Car.hello(myCar)`) since `this` will not be an instance. [S1]
## 📖 세부 내용 (Details)
**Static Methods**
Static class methods are defined on the class itself. You cannot call a `static` method on an object, only on an object class: [S1]
```javascript
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
const myCar = new Car("Ford");
// You can call 'hello()' on the Car Class:
document.getElementById("demo").innerHTML = Car.hello();
// But NOT on a Car Object:
// document.getElementById("demo").innerHTML = myCar.hello();
// this will raise an error.
```
**Passing an Object to a Static Method**
If you want to use an object inside a static method, you can send it as a parameter: [S1]
```javascript
class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);
```
## 🛠️ 적용 사례 (Applied in summary)
The `Car.hello()` examples are the canonical applied cases — one showing that the static method is callable only on the class, the other showing the object passed in as a parameter to access `x.name`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Declare and call a static method on the class (language: JavaScript):
```javascript
class Car {
constructor(name) { this.name = name; }
static hello() { return "Hello!!"; }
}
Car.hello(); // ✅ on the class
// myCar.hello(); // ❌ on an object → error
```
Pass an instance into a static method:
```javascript
static hello(x) { return "Hello " + x.name; }
Car.hello(myCar);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Classes]], [[JavaScript Class Inheritance]], [[JavaScript Objects]], [[JavaScript Object Methods]]
- **참조 맥락:** Extends JavaScript Classes with class-level (static) methods and their call-site restriction.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Class Static — https://www.w3schools.com/js/js_class_static.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Class Static" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,165 @@
---
id: javascript-classes
title: "JavaScript Classes"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["ES6 classes", "class syntax", "constructor method", "class methods", "use strict"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "classes", "oop", "es6"]
raw_sources: ["https://www.w3schools.com/js/js_classes.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Classes]]
## 🎯 한 줄 통찰 (One-line insight)
A JavaScript class, introduced in ES6, is a template for objects (not an object itself), defined with the `class` keyword and a `constructor()` method that runs automatically on `new`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Classes are ES6 templates** — a class is a template for JavaScript objects, defined with the `class` keyword and a `constructor()` method. [S1]
- **A class is not an object** — it is a template from which objects are created. [S1]
- **The constructor runs automatically** — the `constructor` method is called automatically when a new object is created with `new`. [S1]
- **Constructor rules** — it must use the exact name `constructor`, executes automatically, and initializes properties. [S1]
- **Class methods** are defined inside the class body and can take parameters. [S1]
- **Strict mode** — classes require "strict mode" compliance (e.g. variables must be declared with `const`/`let`). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **constructor + `this` initialization** — assign incoming arguments to `this.*` in the constructor to set up object state. [S1]
- **Method computes from state** — methods like `age()` derive values from the instance's own properties (e.g. `this.year`). [S1]
- **Pass external data as a parameter** — when a method needs outside data (like the current year), pass it in as an argument rather than recomputing. [S1]
## 📖 세부 내용 (Details)
**JavaScript Class Syntax**
ES6 introduced JavaScript Classes as templates for objects. The basic syntax uses the `class` keyword with a `constructor()` method: [S1]
```javascript
class ClassName {
constructor() { ... }
}
```
A concrete example: [S1]
```javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
```
A JavaScript class is **not** an object. It is a **template** for JavaScript objects. [S1]
**Using a Class**
Instantiate with `new`: [S1]
```javascript
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
```
The constructor method is called automatically when a new object is created. [S1]
**The Constructor Method**
The constructor must use the exact name `constructor`, executes automatically when objects are created, and initializes properties. [S1]
**Class Methods**
A method computing the car's age from `this.year`: [S1]
```javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
```
A method that accepts a parameter: [S1]
```javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
const date = new Date();
let year = date.getFullYear();
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML=
"My car is " + myCar.age(year) + " years old.";
```
**"use strict"**
Classes require "strict mode" compliance — variables must be properly declared: [S1]
```javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
// date = new Date(); // This will not work
const date = new Date(); // This will work
return date.getFullYear() - this.year;
}
}
```
## 🛠️ 적용 사례 (Applied in summary)
The `Car` class is the running applied example — defining name/year in the constructor, deriving age in a method (with and without a parameter), and demonstrating strict-mode variable declaration. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Define a class and instantiate it (language: JavaScript):
```javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
```
Add a method that uses instance state:
```javascript
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Class Inheritance]], [[JavaScript Class Static]], [[JavaScript Objects]], [[JavaScript Object Constructors]]
- **참조 맥락:** The foundation for object-oriented JavaScript; extended by class inheritance and static-method pages.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Classes — https://www.w3schools.com/js/js_classes.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Classes" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,136 @@
---
id: javascript-code-blocks
title: "JavaScript Code Blocks"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["curly braces", "block statement", "standalone block", "block scope", "statement grouping"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "code-blocks", "scope", "syntax"]
raw_sources: ["https://www.w3schools.com/js/js_codeblocks.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Code Blocks]]
## 🎯 한 줄 통찰 (One-line insight)
A code block is a group of statements wrapped in curly braces `{ }` that are treated as a single unit — and with `let`/`const` it also creates a private scope. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Curly braces group statements** — a code block is one or more statements enclosed in `{ }`, executed together as a unit. [S1]
- **Used by language constructs** — functions, `if/else`, `for`, and `while` all use code blocks to hold their body. [S1]
- **Blocks define scope** — variables declared with `let` and `const` inside a block are block-scoped and accessible only within that block. [S1]
- **Standalone blocks exist** — a `{ }` block can stand on its own (not attached to a function or control statement) purely to create a local scope for `let`/`const` variables. [S1]
- **Benefits of blocks** — encapsulation, use of temporary variables, and organized code that avoids name conflicts while staying readable. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Wrap a body in `{ }`** — every function/condition/loop body is a code block. [S1]
- **Use a standalone block for a temporary scope** — `{ let x = ...; }` confines short-lived variables and prevents leaks into the surrounding scope. [S1]
## 📖 세부 내용 (Details)
**Curly Braces**
JavaScript code blocks are groups of statements enclosed in curly braces `{ }`. They are essential for controlling the flow of execution and for defining variable scope. [S1]
**Code Blocks and Statements**
A code block lets multiple statements be treated as a single unit. Code blocks are required by functions, `if` statements, and loops. [S1]
A function uses a code block: [S1]
```javascript
function myFunction() {
// This is a code block
}
```
An `if...else` statement uses code blocks: [S1]
```javascript
if (condition) {
// This is a code block
} else {
// This is a code block
}
```
A `for` loop uses a code block: [S1]
```javascript
for (expression 1; expression 2; expression 3) {
// This is a code block
}
```
A `while` loop uses a code block: [S1]
```javascript
while (condition) {
// This is a code block
}
```
**Defining Scope**
Variables declared with `let` and `const` inside a code block are block-scoped — they are accessible only within that specific block: [S1]
```javascript
{
let x = 10;
// x is accessible here
}
// x is not accessible here
```
**Standalone Blocks**
A code block can exist independently, without being attached to a function or control structure, simply to create a scope for `let` and `const` variables: [S1]
```javascript
{
let x = 10;
let y = 100;
let areal = x * y;
}
```
Benefits of standalone blocks include encapsulation (variables are confined to the block scope), use of temporary variables, and organized code that prevents name conflicts while maintaining readability. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets are the applied cases: bodies of functions, `if/else`, `for`, and `while`, plus a standalone `{ }` block used to scope temporary variables (`x`, `y`, `areal`). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Block-scoped variables (language: JavaScript):
```javascript
{
let x = 10;
// x is accessible here
}
// x is not accessible here
```
Standalone block as a temporary scope:
```javascript
{
let x = 10;
let y = 100;
let areal = x * y;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Scope]], [[JavaScript var let const]], [[JavaScript Functions]], [[JavaScript If Else]]
- **참조 맥락:** Referenced when explaining how `{ }` both groups statements and confines `let`/`const` variables.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Code Blocks — https://www.w3schools.com/js/js_codeblocks.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Code Blocks" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,116 @@
---
id: javascript-comments
title: "JavaScript Comments"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS comments", "single line comment", "multi-line comment", "block comment", "prevent execution"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "comments"]
raw_sources: ["https://www.w3schools.com/js/js_comments.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Comments]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript comments explain code and improve readability — single-line comments start with `//`, multi-line comments are wrapped in `/* */`, and either form can also be used to prevent code from executing. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Purpose of comments** — comments can be used to explain JavaScript code and to make it more readable; they can also be used to prevent execution when testing alternative code. [S1]
- **Single line comments** — start with `//`; any text between `//` and the end of the line is ignored (not executed). [S1]
- **Multi-line comments** — start with `/*` and end with `*/`; any text between is ignored. [S1]
- **Comments to prevent execution** — placing `//` or `/* */` around code lines is a convenient way to prevent execution, e.g. while debugging. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **End-of-line annotation** — append `// ...` after a statement to document what that line does. [S1]
- **Block intro comment** — use a `/* ... */` block before a group of statements to describe what the following code does. [S1]
- **Comment-out for debugging** — prefix a single line with `//`, or wrap several lines in `/* */`, to temporarily disable them. [S1]
## 📖 세부 내용 (Details)
**Single Line Comments** — Single line comments start with `//`. Any text between `//` and the end of the line will be ignored by JavaScript (will not be executed). This example uses a single line comment before each line of code: [S1]
```javascript
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
```
This example uses a single line comment at the end of each line to explain the code: [S1]
```javascript
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
```
**Multi-line Comments** — Multi-line comments start with `/*` and end with `*/`. Any text between `/*` and `*/` will be ignored by JavaScript. This example uses a multi-line comment (a comment block) to explain the code: [S1]
```javascript
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
```
**Using Comments to Prevent Execution** — Using comments to prevent execution of code is suitable for testing. Adding `//` in front of a code line changes the lines from an executable line to a comment: [S1]
```javascript
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
```
This example uses a comment block to prevent execution of multiple lines: [S1]
```javascript
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — single-line intro/end-of-line comments, a multi-line explanatory block, and commenting out one line vs a multi-line block to prevent execution. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Single line, end-of-line:
```javascript
let x = 5; // Declare x, give it the value of 5
```
Multi-line block:
```javascript
/*
This block describes the code below.
*/
```
Comment out to disable:
```javascript
//document.getElementById("myH").innerHTML = "My First Page";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Syntax]], [[JavaScript Statements]], [[JavaScript Variables]]
- **참조 맥락:** Documentation practice referenced across every code example in the tutorial.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Comments — https://www.w3schools.com/js/js_comments.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Comments" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,141 @@
---
id: javascript-comparisons
title: "JavaScript Comparisons"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS comparison operators", "comparison operators", "equality operators", "strict equality", "string comparison", "type coercion comparison"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "comparisons", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_comparisons.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Comparisons]]
## 🎯 한 줄 통찰 (One-line insight)
Comparison operators compare two values and always return `true` or `false`; they work on strings (compared alphabetically) and coerce a string to a number when comparing a string with a number. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Comparison operators compare two values** — they always return `true` or `false`. [S1]
- **Loose vs strict equality** — `==` checks equal value; `===` checks equal value *and* equal type (and `!=` vs `!==` likewise). [S1]
- **String comparison is alphabetical** — all comparison operators can be used on strings, and strings are compared alphabetically. [S1]
- **Type coercion on mixed compare** — when comparing a string with a number, JavaScript converts the string to a number; an empty string converts to `0`, and a non-numeric string converts to `NaN`, which is always `false`. [S1]
- **String-vs-string is lexical** — when comparing two strings, `"2"` is greater than `"12"` because, alphabetically, `1` is less than `2`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Prefer `===` for safety** — use strict equality to avoid surprising coercions, since `x == "5"` is `true` but `x === "5"` is `false` when `x` is the number 5. [S1]
- **Guard numeric input** — `Number(age)` then `isNaN(...)` before comparing handles non-numeric input. [S1]
- **Beware lexical string compare** — comparing numeric-looking strings compares them character by character, not numerically. [S1]
## 📖 세부 내용 (Details)
**Comparison Operators** [S1]
Comparison operators are used to compare two values. Comparison operators always return `true` or `false`. Assuming `x = 5`:
| Operator | Description | Comparing | Returns |
|----------|-------------|-----------|---------|
| == | equal to | x == 8 | false |
| == | equal to | x == 5 | true |
| == | equal to | x == "5" | true |
| === | equal value and equal type | x === 5 | true |
| === | equal value and equal type | x === "5" | false |
| != | not equal | x != 8 | true |
| !== | not equal value or not equal type | x !== 5 | false |
| !== | not equal value or not equal type | x !== "5" | true |
| !== | not equal value or not equal type | x !== 8 | true |
| > | greater than | x > 8 | false |
| < | less than | x < 8 | true |
| >= | greater than or equal to | x >= 8 | false |
| <= | less than or equal to | x <= 8 | true |
**JavaScript String Comparison** [S1]
All the comparison operators above can also be used on strings. Strings are compared alphabetically:
```javascript
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
```
Note that, when comparing two strings, the comparison is lexical, not numeric:
```javascript
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
```
**Comparing Different Types** [S1]
When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to `0`. A non-numeric string converts to `NaN`, which is always `false`. When comparing two strings, `"2"` will be greater than `"12"`, because (alphabetically) `1` is less than `2`.
| Case | Value |
|------|-------|
| 2 < 12 | true |
| 2 < "12" | true |
| 2 < "John" | false |
| 2 > "John" | false |
| 2 == "John" | false |
| "2" < "12" | false |
| "2" > "12" | true |
| "2" == "12" | false |
**Conditional (Ternary) Operator** [S1]
The page demonstrates guarding numeric input and then using a ternary expression for the decision:
```javascript
age = Number(age);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — comparing strings alphabetically, comparing numeric strings lexically, and guarding input with `Number(...)` + `isNaN(...)` before a ternary decision. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Alphabetical string comparison:
```javascript
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
```
Validate then decide:
```javascript
age = Number(age);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`==` (loose) vs `===` (strict)** — `==` compares value after type coercion, so `5 == "5"` is `true`; `===` requires equal value *and* type, so `5 === "5"` is `false`. Prefer `===`/`!==` when you want to avoid implicit coercion surprises. [S1]
- **Number vs string comparison** — with `<`/`>`, a string operand is coerced to a number (empty string → `0`, non-numeric → `NaN``false`); but when *both* operands are strings, the comparison is alphabetical (lexical), so `"2" > "12"` is `true`. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The apparent paradox that `2 < "12"` is `true` while `"2" < "12"` is `false` is explained by coercion-vs-lexical comparison, not an inconsistency.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Operators]], [[JavaScript Conditional Operators]], [[JavaScript If]], [[JavaScript Types]]
- **참조 맥락:** Referenced whenever evaluating a condition for branching, loops, or validation.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Comparisons — https://www.w3schools.com/js/js_comparisons.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Comparisons" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,84 @@
---
id: javascript-conditional-operators
title: "JavaScript Conditional Operators"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS conditional statements", "conditional statements", "ternary operator", "if else switch overview", "control flow", "decision statements"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "conditionals", "control-flow"]
raw_sources: ["https://www.w3schools.com/js/js_conditionals.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Conditional Operators]]
## 🎯 한 줄 통찰 (One-line insight)
Conditional statements run different code depending on `true`/`false` conditions — JavaScript provides `if`, `else`, `else if`, `switch`, and the ternary `(? :)` shorthand. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Conditional statements branch on conditions** — they let you perform different actions for different conditions. [S1]
- **`if`** — use `if` to specify a code block to be executed if a specified condition is `true`. [S1]
- **`else`** — use `else` to specify a code block to be executed if the same condition is `false`. [S1]
- **`else if`** — use `else if` to specify a new condition to test if the first condition is `false`. [S1]
- **`switch`** — use `switch` to specify many alternative code blocks to be executed. [S1]
- **Ternary `(? :)`** — use `(? :)` (ternary) as a shorthand for `if...else`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Pick the right branching construct** — single decision → `if`/`else`; chained conditions → `else if`; many discrete cases → `switch`; one-line value choice → ternary. [S1]
- **Ternary as expression** — the ternary form `condition ? expression1 : expression2` returns a value, unlike statement-only `if`. [S1]
## 📖 세부 내용 (Details)
**Conditional Statements** [S1]
Conditional statements allow you to perform different actions for different conditions — running different code depending on `true` or `false` conditions. Conditional statements include:
- **if** — Use `if` to specify a code block to be executed, if a specified condition is `true`.
- **else** — Use `else` to specify a code block to be executed, if the same condition is `false`.
- **else if** — Use `else if` to specify a new condition to test, if the first condition is `false`.
- **switch** — Use `switch` to specify many alternative code blocks to be executed.
- **ternary (? :)** — Use `(? :)` (ternary) as a shorthand for `if...else`.
**Ternary (? :) syntax** [S1]
The page shows the ternary as a syntax template rather than a runnable named example:
```javascript
condition ? expression1 : expression2
```
This page is an overview/index of the conditional constructs; the detailed runnable examples live on the dedicated pages it links to. A concrete named-variable ternary example was Not found in source on this page.
## 🛠️ 적용 사례 (Applied in summary)
This is an overview page; it points to the dedicated `if`, `else`, `switch`, and ternary pages where the working examples reside. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Ternary shorthand for `if...else`:
```javascript
condition ? expression1 : expression2
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript If]], [[JavaScript If Else]], [[JavaScript Comparisons]], [[JavaScript Operators]]
- **참조 맥락:** The entry point for control-flow branching, referenced before choosing `if`/`else`/`switch`/ternary.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Conditional Operators — https://www.w3schools.com/js/js_conditionals.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Conditional Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,194 @@
---
id: javascript-const
title: "JavaScript Const"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["const keyword", "constant reference", "constant objects", "constant arrays", "const hoisting"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "const", "block-scope"]
raw_sources: ["https://www.w3schools.com/js/js_const.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Const]]
## 🎯 한 줄 통찰 (One-line insight)
`const` (ES6, 2015) declares a block-scoped constant reference that cannot be reassigned or redeclared — but for objects and arrays it only fixes the reference, so their contents can still be changed. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Cannot be reassigned** — a variable declared with `const` cannot be reassigned. [S1]
- **Must be assigned at declaration** — `const` variables must be assigned a value when they are declared. [S1]
- **Constant reference, not constant value** — `const` defines a constant reference to a value; it does not make the value itself immutable. [S1]
- **Objects/arrays are mutable** — you cannot reassign a `const` array or object, but you can change array elements and object properties. [S1]
- **Block scope** — `const` (like `let`) has block scope. [S1]
- **Hoisted but not initialized** — `const` is hoisted but not initialized; using it before declaration causes a `ReferenceError`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **const-by-default** — declare with `const` whenever the value should not change; reserve `let` for the cases where it must. [S1]
- **Mutate-not-reassign** — for collections, modify elements/properties in place rather than rebinding the variable. [S1]
- **Declare-with-value** — `const` cannot be split into a bare declaration plus a later assignment; assign at the point of declaration. [S1]
## 📖 세부 내용 (Details)
**Cannot be Reassigned** — A variable declared with `const` cannot be reassigned: [S1]
```javascript
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
```
**Must be Assigned** — JavaScript `const` variables must be assigned a value when they are declared. Correct: [S1]
```javascript
const PI = 3.14159265359;
```
Incorrect: [S1]
```javascript
const PI;
PI = 3.14159265359;
```
**When to use JavaScript const?** — Always declare a variable with `const` when you know that the value should not be changed. Use `const` when you declare: a new Array, a new Object, a new Function, or a new RegExp. [S1]
**Constant Objects and Arrays** — The keyword `const` is a little misleading. It does not define a constant value; it defines a constant reference to a value. Because of this you can NOT reassign a constant value, array, or object, but you CAN change the elements of a constant array and change the properties of a constant object. [S1]
**Constant Arrays** — You can change the elements of a constant array: [S1]
```javascript
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Toyota";
// You can add an element:
cars.push("Audi");
```
But you can NOT reassign the array: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
```
**Constant Objects** — You can change the properties of a constant object: [S1]
```javascript
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
```
But you can NOT reassign the object: [S1]
```javascript
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"} // ERROR
```
**Block Scope** — Declaring a variable with `const` is similar to `let` regarding Block Scope. The `x` declared in the block is not the same as the `x` declared outside the block: [S1]
```javascript
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
```
**Redeclaring** — Redeclaring an existing `var` or `let` variable to `const`, in the same scope, is not allowed: [S1]
```javascript
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
```
Reassigning or redeclaring an existing `const`, in the same scope, is not allowed: [S1]
```javascript
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
```
Redeclaring a `const`, in another scope or in another block, is allowed: [S1]
```javascript
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
```
**Hoisting** — Variables defined with `const` are hoisted to the top, but not initialized. Using a `const` variable before it is declared results in a `ReferenceError`: [S1]
```javascript
alert (carName);
const carName = "Volvo";
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — the reassignment errors on `PI`, mutating vs reassigning a `const` array and object, block-scoped `const x`, the redeclaration rules, and the hoisting `ReferenceError`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Constant reference:
```javascript
const PI = 3.141592653589793;
```
Mutate a const collection without reassigning:
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota";
cars.push("Audi");
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
The source compares the three declaration keywords: [S1]
| Feature | var | let | const |
|---------|-----|-----|-------|
| Scope | Function or global scope | Block-scope `{ }` | Block-scope `{ }` |
| Reassignment | Can be updated | Can be updated | Cannot be updated |
| Redeclaration | Can be redeclared | Cannot be redeclared | Cannot be redeclared |
| Hoisting | Initialized as `undefined` | Hoisted, not initialized | Hoisted, not initialized |
Choose `const` whenever the binding should never be reassigned (the default for Arrays, Objects, Functions, RegExp); use `let` only when reassignment is required; avoid `var`. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source highlights that "const" is itself a little misleading — it fixes the reference, not the value — which is a clarification rather than a contradiction.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Variables]], [[JavaScript Let]], [[JavaScript Statements]]
- **참조 맥락:** The immutable-binding declaration keyword, the recommended default, paired with `let`.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Const — https://www.w3schools.com/js/js_const.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Const" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,134 @@
---
id: javascript-continue
title: "JavaScript Continue"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["continue statement", "continue keyword", "JS continue", "continue label", "labeled continue"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "loops", "continue", "labels"]
raw_sources: ["https://www.w3schools.com/js/js_continue.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Continue]]
## 🎯 한 줄 통찰 (One-line insight)
The `continue` statement skips the current iteration of a loop and moves processing on to the next one — and together with `break` it is one of the only two JavaScript statements that can "jump out of" a code block. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`continue` skips one iteration** — it skips the remaining code in the current iteration and moves processing to the next iteration of the loop. [S1]
- **Labels name statements** — a label provides a name for a statement or a block of statements, allowing them to be referenced for program flow control, particularly in loops. [S1]
- **Label syntax** — a label is an identifier followed by a colon (`:`) that precedes a statement or a block of code. [S1]
- **`continue labelname`** — `continue` can target a labeled loop, controlling which loop continues in nested loops. [S1]
- **Only two jump-out statements** — `break` and `continue` are the only JavaScript statements that can "jump out of" a code block. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Guard-and-skip** — inside a loop, test a condition (`if (i === 3)`) and call `continue` to skip processing for that one value while keeping the loop running. [S1]
- **Label a loop, then continue it** — prefix a loop with `labelname:` and use `continue labelname;` to decide, from inside a nested loop, which enclosing loop to advance. [S1]
## 📖 세부 내용 (Details)
**The Continue Statement**
The `continue` statement "skips the current iteration" in a loop. The remaining code in the iteration is skipped and processing moves to the next iteration. [S1]
```javascript
for (let i = 1; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
```
**JavaScript Labels**
A label provides a name for a statement, or a block of statements, allowing statements to be referenced for program flow control, particularly in loops. A label is an identifier followed by a colon (`:`). [S1]
A label precedes a statement:
```javascript
labelname: statement;
```
A label precedes a block of code:
```javascript
labelname: {
statements
}
```
**Continue to Labelname**
The syntax for continuing a labeled loop is: [S1]
```javascript
continue labelname;
```
Continuing the outer loop (`loop1`) from inside the inner loop: [S1]
```javascript
let text = "";
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { continue loop1; }
text += i;
}
}
```
Continuing the inner loop (`loop2`) instead: [S1]
```javascript
let text = "";
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { continue loop2; }
text += i;
}
}
```
`break` and `continue` are the only JavaScript statements that can "jump out of" a code block. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — skipping the value 3 in a `for` loop, and using labeled `continue loop1` / `continue loop2` to control which loop advances in a nested-loop scenario. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Skip one iteration with `continue`:
```javascript
for (let i = 1; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
```
Continue a labeled outer loop from a nested loop:
```javascript
loop1: for (let j = 1; j < 5; j++) {
loop2: for (let i = 1; i < 5; i++) {
if (i === 3) { continue loop1; }
text += i;
}
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Break]], [[JavaScript Control Flow]], [[JavaScript For Loop]], [[JavaScript While Loop]]
- **참조 맥락:** Referenced whenever a loop needs to skip selected iterations or control nested-loop flow with labels.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Continue — https://www.w3schools.com/js/js_continue.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Continue" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,139 @@
---
id: javascript-control-flow
title: "JavaScript Control Flow"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["control flow", "program flow", "execution order", "JS control flow", "conditional flow"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "control-flow", "loops", "conditions"]
raw_sources: ["https://www.w3schools.com/js/js_control_flow.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Control Flow]]
## 🎯 한 줄 통찰 (One-line insight)
Control flow is the order in which statements are executed; by default JavaScript runs top-to-bottom and left-to-right on a single thread, and conditions, loops, jumps, and functions are how you alter that order. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Control flow = order of execution** — control flow is the order in which statements are executed in a program. [S1]
- **Default flow is sequential** — by default JavaScript executes code sequentially from top to bottom and left to right. [S1]
- **Conditional flow** — conditions allow decision-making using `if`, `if...else`, `switch`, and the ternary (`? :`) operators. [S1]
- **Loops repeat code** — loops enable code to run multiple times using `for`, `while`, or `do...while` structures. [S1]
- **Jump statements alter flow abruptly** — using `break`, `continue`, `return`, and `throw`. [S1]
- **Functions are callable, reusable blocks** — functions run when they are called. [S1]
- **Single-threaded** — JavaScript runs on a single thread; it can only do one thing at a time, so every task waits for the completion of previous tasks. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Branch on a condition** — assign a default value, then override it inside `if/else` based on a test (e.g. `age >= 18`). [S1]
- **Repeat with a counted loop** — drive repetition with a `for` loop counter and accumulate output. [S1]
- **Early exit from a loop** — combine a loop with a `break` inside an `if` to stop early. [S1]
- **Encapsulate logic in a function** — wrap reusable computation in a function that returns a value. [S1]
## 📖 세부 내용 (Details)
**JavaScript Control Flow**
Control flow is the order in which statements are executed in a program. By default, JavaScript executes code sequentially from top to bottom and left to right. Control flow statements enable developers to alter this sequence based on conditions, loops, or keywords. [S1]
**Default Flow**
Default flow runs code sequentially from top to bottom and left to right. [S1]
```javascript
let x = 5;
let y = 6;
let z = x + y;
```
**Conditional Control Flow**
Conditions allow decision-making using `if`, `if...else`, `switch`, and ternary (`? :`) operators. [S1]
```javascript
let text = "Unknown";
if (age >= 18) {
text = "Adult";
} else {
text = "Minor";
}
```
**Loops (Repetition Control Flow)**
Loops enable code to run multiple times using `for`, `while`, or `do...while` structures. [S1]
```javascript
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
```
**Jump Statements**
Jump statements alter flow abruptly using `break`, `continue`, `return`, and `throw`. [S1]
```javascript
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
```
**Function Flow**
Functions are callable and reusable code blocks. Functions will run when they are called. [S1]
```javascript
function myFunction(p1, p2) {
return p1 * p2;
}
```
**JavaScript Is Single-Threaded**
JavaScript runs on a single thread. It can only do one thing at a time. Every task must wait for completion of previous tasks, potentially freezing applications during slow operations. Asynchronous programming is covered in the advanced section. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — sequential assignment, an `if/else` age check, a counted `for` loop, an early `break`, and a multiplying function. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Conditional branch:
```javascript
if (age >= 18) {
text = "Adult";
} else {
text = "Minor";
}
```
Counted loop with early exit:
```javascript
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
```
Reusable function:
```javascript
function myFunction(p1, p2) {
return p1 * p2;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript If Else]], [[JavaScript Switch]], [[JavaScript For Loop]], [[JavaScript Break]], [[JavaScript Continue]], [[JavaScript Functions]]
- **참조 맥락:** The conceptual umbrella for every statement that changes execution order in a JavaScript program.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Control Flow — https://www.w3schools.com/js/js_control_flow.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Control Flow" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,153 @@
---
id: javascript-dom-animations
title: "JavaScript DOM Animations"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["DOM animation", "JavaScript animation", "setInterval animation", "animate element", "frame animation"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_animate.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Animations]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript animations work by programming gradual changes to an element's style, driven by a timer — with a small interval, the motion looks continuous. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Animation = timed style changes** — JavaScript animations are done by programming gradual changes in an element's style; the changes are called by a timer, and a small interval makes the animation look continuous. [S1]
- **Relative container, absolute element** — the container element should be created with `style = 'position: relative'`, and the animation element with `style = 'position: absolute'`. [S1]
- **setInterval / clearInterval drive frames** — a repeating timer calls a `frame()` function until a finish condition is met, then clears the interval. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Timer loop** — `id = setInterval(frame, 5)` repeatedly calls `frame()`, which either ends (`clearInterval(id)`) or applies the next incremental style change. [S1]
- **Increment position** — bump a `pos` counter each frame and write it to `style.top` / `style.left` as pixel values. [S1]
- **Reset before start** — call `clearInterval(id)` before starting a new interval to avoid stacking timers. [S1]
## 📖 세부 내용 (Details)
**A Basic Web Page** [S1]
Start from a simple page with a placeholder element: [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
```
**Create an Animation Container** [S1]
Wrap the animated element in a container: [S1]
```html
<div id="container">
<div id="animate">My animation will go here</div>
</div>
```
**Style the Elements** [S1]
The container is positioned `relative` and the animated element `absolute`: [S1]
```css
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
```
**Animation Code** [S1]
The general timer-driven pattern: [S1]
```javascript
id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
```
**Create the Full Animation Using JavaScript** [S1]
The complete animation moves the element diagonally until `pos == 350`: [S1]
```javascript
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's `myMove()` function — moving `#animate` diagonally inside `#container` via `setInterval` — is the canonical applied example. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Full timer-driven animation (language: JavaScript):
```javascript
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript DOM Changing CSS]], [[JavaScript HTML DOM]], [[JavaScript HTML Events]], [[JavaScript DOM Methods]]
- **참조 맥락:** Builds on style manipulation; uses timers to apply incremental style changes over time.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Animations — https://www.w3schools.com/js/js_htmldom_animate.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Animations" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,122 @@
---
id: javascript-dom-changing-css
title: "JavaScript DOM Changing CSS"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["changing CSS", "style property", "element.style", "DOM styling", "style object"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_css.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Changing CSS]]
## 🎯 한 줄 통찰 (One-line insight)
The HTML DOM lets JavaScript change the style of any element by assigning to its `style.property`, and events can trigger those style changes dynamically. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Style via the style object** — change an element's CSS by setting a property on its `style` object. [S1]
- **Events drive style changes** — the HTML DOM allows you to execute code when an event occurs; events are generated by the browser when "things happen" to HTML elements, such as clicks, page loads, and input-field changes. [S1]
- **Reference exists** — the HTML DOM Style Object Reference documents all properties that can be set. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`document.getElementById(id).style.property = new style`** — the canonical style-change syntax. [S1]
- **Inline event handler → style change** — wire an `onclick` attribute that mutates `style` on a target element. [S1]
- **Visibility toggle** — switch `style.visibility` between `'hidden'` and `'visible'` to hide or show. [S1]
## 📖 세부 내용 (Details)
**Changing HTML Style** [S1]
The syntax for changing the style of an HTML element is: [S1]
```javascript
document.getElementById(id).style.property = new style
```
Change the color of a paragraph: [S1]
```html
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
```
**Using Events** [S1]
The HTML DOM allows you to execute code when an event occurs. Events are generated by the browser when "things happen" to HTML elements, such as clicks, page loads, and changes to input fields. The following example changes a heading's color on click: [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
```
**More Examples** [S1]
Toggle the visibility of an element with two buttons: [S1]
```html
<input type="button" value="Hide text"
onclick="document.getElementById('p1').style.visibility='hidden'">
<input type="button" value="Show text"
onclick="document.getElementById('p1').style.visibility='visible'">
```
**HTML DOM Style Object Reference** [S1]
For a complete list of all properties that can be modified through JavaScript, the page directs learners to the HTML DOM Style Object Reference. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — setting `#p2.style.color`, an `onclick` that turns a heading red, and visibility toggle buttons — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Set a style property (language: JavaScript):
```javascript
document.getElementById("p2").style.color = "blue";
```
Change style on click (language: HTML):
```html
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
```
Toggle visibility:
```html
<input type="button" value="Hide text"
onclick="document.getElementById('p1').style.visibility='hidden'">
<input type="button" value="Show text"
onclick="document.getElementById('p1').style.visibility='visible'">
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript DOM Changing HTML]], [[JavaScript DOM Animations]], [[JavaScript HTML Events]], [[JavaScript DOM Elements]]
- **참조 맥락:** The styling step used in interactive UI changes and as the basis for DOM animations.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Changing CSS — https://www.w3schools.com/js/js_htmldom_css.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Changing CSS" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,127 @@
---
id: javascript-dom-elements
title: "JavaScript DOM Elements"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["finding HTML elements", "getElementById", "getElementsByTagName", "getElementsByClassName", "querySelectorAll", "HTML object collections"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_elements.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Elements]]
## 🎯 한 줄 통찰 (One-line insight)
Before you can manipulate an HTML element with JavaScript, you must first find it — by id, tag name, class name, CSS selector, or via the built-in HTML object collections. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Find first, then manipulate** — often you want to manipulate HTML elements, and to do so you have to find the elements first. [S1]
- **By id is the easiest** — the easiest way to find an HTML element in the DOM is by using the element id; it returns the element as an object, or `null` if not found. [S1]
- **Collections by tag / class** — `getElementsByTagName()` finds all elements of a tag type; `getElementsByClassName()` finds all elements sharing a class name. [S1]
- **CSS selectors** — `querySelector()` returns the first match for a CSS selector; `querySelectorAll()` returns all matches. [S1]
- **HTML object collections** — predefined collections such as `document.forms` and `document.images` also give access to elements. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **One element vs many** — id and `querySelector()` return a single element; tag-name, class-name, and `querySelectorAll()` return collections you iterate over. [S1]
- **Loop over a collection** — index into the returned collection (e.g. `x.elements[i].value`) to read each member. [S1]
- **No `#` for getElementById** — pass the bare id, not a CSS-style selector. [S1]
## 📖 세부 내용 (Details)
**Finding HTML Elements** [S1]
Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first. [S1]
**Finding HTML Element by Id** [S1]
The easiest way to find an HTML element in the DOM is by using the element id. It returns the element as an object if found, or `null` if not found. [S1]
```javascript
const element = document.getElementById("intro");
```
**Finding HTML Elements by Tag Name** [S1]
```javascript
const element = document.getElementsByTagName("p");
```
**Finding HTML Elements by Class Name** [S1]
If you want to find all HTML elements with the same class name, use `getElementsByClassName()`. [S1]
```javascript
const x = document.getElementsByClassName("intro");
```
**Finding HTML Elements by CSS Selectors** [S1]
If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc.), use the `querySelectorAll()` method. [S1]
```javascript
const x = document.querySelectorAll("p.intro");
```
**The querySelector() Method** — returns the first element that matches a specified CSS selector. [S1]
**The querySelectorAll() Method** — returns all elements that match a specified CSS selector. [S1]
**Finding HTML Elements by HTML Object Collections** [S1]
The source also shows iterating over a collection (here a form's elements): [S1]
```javascript
const x = document.forms["frm1"];
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
```
Accessible HTML object collections include: `document.anchors`, `document.body`, `document.documentElement`, `document.embeds`, `document.forms`, `document.head`, `document.images`, `document.links`, `document.scripts`, and `document.title`. [S1]
**Common Mistakes** [S1]
- Using `#` inside `getElementById()` (wrong: `"#demo"`). [S1]
- Forgetting that `querySelector()` returns only the first match. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — selecting by id, tag, class, and CSS selector, and looping a form's `elements` collection — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Four ways to find elements (language: JavaScript):
```javascript
const byId = document.getElementById("intro");
const byTag = document.getElementsByTagName("p");
const byClass = document.getElementsByClassName("intro");
const bySelector = document.querySelectorAll("p.intro");
```
Iterate a collection:
```javascript
const x = document.forms["frm1"];
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- Use **`getElementById()`** when the element has a unique id — fastest, returns one object. [S1]
- Use **`getElementsByTagName()` / `getElementsByClassName()`** to retrieve a live collection of multiple elements. [S1]
- Use **`querySelector()`** for the first match of any CSS selector, and **`querySelectorAll()`** for all matches when you need full CSS-selector expressiveness. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript HTML DOM]], [[JavaScript DOM Methods]], [[JavaScript DOM Changing HTML]], [[JavaScript DOM Changing CSS]]
- **참조 맥락:** The element-selection step that precedes any content, style, or event manipulation.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Elements — https://www.w3schools.com/js/js_htmldom_elements.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Elements" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,115 @@
---
id: javascript-dom-changing-html
title: "JavaScript DOM Changing HTML"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["innerHTML", "changing HTML content", "changing attributes", "document.write", "dynamic HTML content"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_html.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Changing HTML]]
## 🎯 한 줄 통찰 (One-line insight)
The HTML DOM lets JavaScript change the content of an element via `innerHTML` and change its attributes by assigning new values directly. [S1]
## 🧠 핵심 개념 (Core concepts)
- **innerHTML changes content** — the easiest way to modify the content of an HTML element is with the `innerHTML` property. [S1]
- **Assign to change attributes** — to change the value of an HTML attribute, assign a new value to the element's attribute property (e.g. `element.src = ...`). [S1]
- **Dynamic content** — JavaScript can create HTML content dynamically, for example inserting the current date/time with `Date()`. [S1]
- **document.write() is for generation, not editing** — it writes directly to the HTML output stream and must not be used after the document has loaded. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`document.getElementById(id).innerHTML = new HTML`** — the canonical content-change syntax. [S1]
- **`element.attribute = new value`** — the canonical attribute-change syntax. [S1]
- **Guard against missing elements** — access DOM elements only after they exist. [S1]
## 📖 세부 내용 (Details)
**Changing HTML Content** [S1]
The easiest way to modify the content of an HTML element is by using the `innerHTML` property. [S1]
**The innerHTML Property** [S1]
The syntax for changing the content of an HTML element is: [S1]
```javascript
document.getElementById(id).innerHTML = new HTML
```
Change a paragraph's content: [S1]
```javascript
document.getElementById("p1").innerHTML = "New text!";
```
Change a heading's content: [S1]
```javascript
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
```
**Common Mistakes** [S1]
- Trying to access a DOM element before it exists. [S1]
- Forgetting the quotes in an id like `"demo"`. [S1]
**Changing an Attribute** [S1]
To change the value of an HTML attribute, assign a new value to the attribute property — for example changing the `src` of an image: [S1]
```javascript
document.getElementById("myImage").src = "landscape.jpg";
```
**Dynamic HTML content** [S1]
JavaScript can create dynamic HTML content, such as writing the current date and time with `Date()`. [S1]
**document.write()** [S1]
The `document.write()` method writes directly to the HTML output stream: [S1]
```javascript
document.write(Date());
```
**Warning!** [S1]
> Never use `document.write()` after the document is loaded. It will overwrite the document. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — setting `#p1.innerHTML`, updating an `<h1>` via `innerHTML`, swapping an image `src`, and `document.write(Date())` — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Change content (language: JavaScript):
```javascript
document.getElementById("p1").innerHTML = "New text!";
```
Change an attribute:
```javascript
document.getElementById("myImage").src = "landscape.jpg";
```
Write dynamic output (use only before the document finishes loading):
```javascript
document.write(Date());
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. (The source explicitly warns against post-load use of `document.write()`, which is a caveat rather than a contradiction.) [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript DOM Elements]], [[JavaScript DOM Changing CSS]], [[JavaScript HTML DOM]], [[JavaScript DOM Methods]]
- **참조 맥락:** The content/attribute mutation step that follows selecting an element.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Changing HTML — https://www.w3schools.com/js/js_htmldom_html.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Changing HTML" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,119 @@
---
id: javascript-dom-methods
title: "JavaScript DOM Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["DOM API", "DOM methods", "DOM properties", "HTML DOM API", "DOM Application Programming Interface"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Methods]]
## 🎯 한 줄 통찰 (One-line insight)
The DOM API is a set of methods (actions) and properties (values) that let JavaScript change the content, structure, and style of any HTML element. [S1]
## 🧠 핵심 개념 (Core concepts)
- **The DOM API** — the DOM API (Application Programming Interface) is a set of methods and properties that allow JavaScript to change the content, structure, and style of any HTML elements. [S1]
- **Method vs property** — an API method is an action you can do on an HTML element; an API property is a value you can access on an HTML element. [S1]
- **JavaScript is the language** — JavaScript is the programming language that operates the DOM API. [S1]
- **document is the entry point** — `document` represents the HTML document; methods like `getElementById()` are called on it to retrieve elements. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Select with a method, mutate with a property** — call a document method to get an element, then assign to an element property (e.g. `innerHTML`). [S1]
- **Categorized capabilities** — DOM methods group into selecting, accessing content, accessing/changing attributes, manipulating structure, and adding event handlers. [S1]
## 📖 세부 내용 (Details)
**HTML DOM API** [S1]
The DOM API (Application Programming Interface) is a set of methods and properties that allow JavaScript to change the content, structure, and style of any HTML elements. An API method is an action that you can do on an HTML element, while an API property is a value that you can access on an HTML element. [S1]
**Example** [S1]
```html
<html>
<body>
<p id="demo"></p>
<script>
// Access a paragraph Element
const myPara = document.getElementById("demo");
// Change the content of the Element
myPara.innerHTML = "Hello World!";
</script>
</body>
</html>
```
**Example Explained**`document` represents the HTML document; `getElementById()` is a document method; `myPara` retrieves the element; `innerHTML` is an element property that can be modified. [S1]
**HTML DOM API Abilities** [S1]
The DOM API enables JavaScript to: find and select elements, change element content and attributes, add/remove/modify elements, change CSS styles, and add event listeners. [S1]
**Selecting HTML Elements** [S1]
| Method | Description |
|--------|-------------|
| `document.getElementById(id)` | Find element by id |
| `document.getElementsByTagName(name)` | Find elements by tag name |
| `document.getElementsByClassName(name)` | Find elements by class name |
| `document.querySelector(selector)` | Find first matching CSS selector |
| `document.querySelectorAll(selector)` | Find all matching CSS selectors |
**Accessing Element Content** [S1]
| Property | Description |
|----------|-------------|
| `element.innerHTML` | HTML content |
| `element.textContent` | Text content |
**Manipulating Structure** [S1]
| Method | Description |
|--------|-------------|
| `document.createElement()` | Create new element |
| `document.removeChild()` | Remove element |
| `document.appendChild()` | Add element |
| `document.replaceChild()` | Replace element |
## 🛠️ 적용 사례 (Applied in summary)
The page's `#demo` paragraph example — retrieved with `getElementById()` and updated via `innerHTML` — is the canonical applied use. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Select then mutate (language: JavaScript):
```javascript
const myPara = document.getElementById("demo");
myPara.innerHTML = "Hello World!";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript HTML DOM]], [[JavaScript DOM Elements]], [[JavaScript DOM Changing HTML]], [[JavaScript DOM Event Listener]]
- **참조 맥락:** The catalog of methods/properties referenced whenever selecting, reading, or restructuring DOM nodes.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Methods — https://www.w3schools.com/js/js_htmldom_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,169 @@
---
id: javascript-data-types
title: "JavaScript Data Types"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS data types", "8 data types", "type coercion", "dynamic typing", "primitive vs object"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "data-types", "type-coercion", "dynamic-typing"]
raw_sources: ["https://www.w3schools.com/js/js_datatypes.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Data Types]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript variables can hold 8 data types — 7 primitive types and 1 object type — and because typing is dynamic, a variable can change type during execution, with type coercion in mixed operations producing string concatenation. [S1]
## 🧠 핵심 개념 (Core concepts)
- **8 data types** — JavaScript has 7 primitive types (Number, BigInt, String, Boolean, Undefined, Null, Symbol) and 1 object type (Object). [S1]
- **Dynamic typing** — JavaScript has dynamic types; the same variable can hold different data types at different times during execution. [S1]
- **Type coercion in `+`** — when an operation mixes a number and a string, JavaScript treats the number as a string and concatenates, evaluating left-to-right. [S1]
- **`typeof`** — the `typeof` operator returns the type of a variable or expression as a string. [S1]
- **Built-in object types** — beyond plain objects, JavaScript includes object types such as Array, Map, Set, Date, RegExp, Promise, and typed arrays. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Left-to-right coercion** — `16 + 4 + "Volvo"` yields `"20Volvo"` (numbers added first), while `"Volvo" + 16 + 4` yields `"Volvo164"` (concatenated as strings). [S1]
- **Type evolves over a variable's life** — `let x;` (undefined) → `x = 5;` (Number) → `x = "John";` (String). [S1]
## 📖 세부 내용 (Details)
**The 8 Data Types** [S1]
| Type | Description |
|------|-------------|
| Number | Numeric values |
| BigInt | Large integers |
| String | Text in quotes |
| Boolean | `true` or `false` |
| Undefined | Variable with no assigned value |
| Null | Absence of object value |
| Symbol | Unique primitive identifier |
| Object | Collection of key-value pairs |
7 of these are primitive; Object is the single object type. [S1]
**Number and BigInt** [S1]
```javascript
let length = 16;
let weight = 7.5;
let x = 1234567890123456789012345n;
let y = BigInt(1234567890123456789012345)
```
**Strings** [S1]
```javascript
let color = "Yellow";
let lastName = "Johnson";
```
**Boolean** [S1]
```javascript
let x = true;
let y = false;
```
**Undefined** [S1]
```javascript
let x;
let y;
```
**Null** [S1]
```javascript
let x = null;
let y = null;
```
**Symbol** [S1]
```javascript
const x = Symbol();
const y = Symbol();
```
**Object types** [S1]
```javascript
const person = {firstName:"John", lastName:"Doe"};
const cars = ["Saab", "Volvo", "BMW"];
const date = new Date("2022-03-25");
```
**The Concept of Data Types / Type Coercion**
When JavaScript encounters mixed types in an operation it can produce results that seem unexpected. Adding a number and a string treats the number as a string and concatenates: [S1]
```javascript
let x = 16 + "Volvo";
let x = "Volvo" + 16;
let x = 16 + 4 + "Volvo"; // Results in "20Volvo"
let x = "Volvo" + 16 + 4; // Results in "Volvo164"
```
JavaScript evaluates expressions left to right. In `16 + 4 + "Volvo"` the two numbers are added first (20), then concatenated with the string ("20Volvo"). In `"Volvo" + 16 + 4` everything is concatenated left to right ("Volvo164"). [S1]
**JavaScript Has Dynamic Types**
JavaScript has dynamic types. This means the same variable can be used to hold different data types: [S1]
```javascript
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
```
**Built-in Object Types**
JavaScript includes built-in objects like Array, Map, Set, Date, RegExp, Promise, and typed arrays (Int8Array, Float32Array, etc.). [S1]
**The `typeof` Operator**
You can use the `typeof` operator to find the data type of a variable: [S1]
```javascript
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own declarations (numbers, strings, booleans, the coercion examples, and the dynamic-typing `let x` sequence) are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Left-to-right type coercion (language: JavaScript):
```javascript
let x = 16 + 4 + "Volvo"; // "20Volvo"
let y = "Volvo" + 16 + 4; // "Volvo164"
```
Dynamic re-typing of one variable:
```javascript
let x; // undefined
x = 5; // Number
x = "John"; // String
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
Type coercion can produce results that seem unexpected; the page highlights this as a behavior to understand rather than a contradiction. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Primitive Data Types]], [[JavaScript Object Data Types]], [[JavaScript typeof]], [[JavaScript Symbols]]
- **참조 맥락:** Foundational reference whenever declaring variables or reasoning about operations that mix types.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Data Types — https://www.w3schools.com/js/js_datatypes.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,140 @@
---
id: javascript-date-formats
title: "JavaScript Date Formats"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["date formats", "ISO date", "Date.parse", "date string", "date input formats"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "date", "format"]
raw_sources: ["https://www.w3schools.com/js/js_date_formats.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Date Formats]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript accepts dates as ISO, Short, Long, and Full date strings; ISO is the preferred unambiguous format, and `Date.parse()` converts a valid date string into milliseconds since the epoch. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Four input formats** — JavaScript date input can be given as ISO, Short, Long, or Full date strings. [S1]
- **ISO format (YYYY-MM-DD)** is the preferred JavaScript date format and is the most reliable. [S1]
- **Partial ISO dates** are allowed — year and month (`"2015-03"`) or just year (`"2015"`). [S1]
- **ISO date-time** can include a `T` and time, with `Z` for UTC or an offset like `-06:30`. [S1]
- **Short / Long dates** use formats like `"03/25/2015"` or `"Mar 25 2015"`. [S1]
- **`Date.parse()`** parses a valid date string and returns the number of milliseconds since January 1, 1970. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Prefer ISO** — use `"YYYY-MM-DD"` for unambiguous parsing. [S1]
- **UTC vs local** — append `Z` for UTC, or an offset to specify a time zone. [S1]
- **String → ms** — `Date.parse(str)`, then optionally `new Date(msec)` to build a Date. [S1]
## 📖 세부 내용 (Details)
**Date Input Formats** — There are generally 4 types of JavaScript date input formats: ISO Date, Short Date, Long Date, and Full Date. The ISO format follows a strict standard in JavaScript and is the preferred format. [S1]
**ISO Dates** — A complete ISO date (YYYY-MM-DD): [S1]
```javascript
const d = new Date("2015-03-25");
```
ISO date without day (year and month): [S1]
```javascript
const d = new Date("2015-03");
```
ISO date with only year: [S1]
```javascript
const d = new Date("2015");
```
ISO date-time with UTC (`Z`): [S1]
```javascript
const d = new Date("2015-03-25T12:00:00Z");
```
ISO date-time with a time-zone offset: [S1]
```javascript
const d = new Date("2015-03-25T12:00:00-06:30");
```
**Short Dates** — short dates are written with an MM/DD/YYYY syntax: [S1]
```javascript
const d = new Date("03/25/2015");
```
**Long Dates** — long dates are most often written with a "MMM DD YYYY" syntax: [S1]
```javascript
const d = new Date("Mar 25 2015");
```
The month and day can be in any order: [S1]
```javascript
const d = new Date("25 Mar 2015");
```
The month can be written in full (January), or abbreviated (Jan): [S1]
```javascript
const d = new Date("January 25 2015");
```
```javascript
const d = new Date("Jan 25 2015");
```
Commas are ignored, and names are case insensitive: [S1]
```javascript
const d = new Date("JANUARY, 25, 2015");
```
**Date.parse()**`Date.parse()` parses a date string and returns the number of milliseconds between the date and January 1, 1970: [S1]
```javascript
let msec = Date.parse("March 21, 2012");
```
The result can then be used to create a Date object: [S1]
```javascript
let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — building dates from ISO, short, and long strings, including UTC and time-zone-offset variants, and converting a date string to milliseconds with `Date.parse()`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Preferred ISO date:
```javascript
const d = new Date("2015-03-25");
```
ISO date-time, UTC vs offset:
```javascript
const utc = new Date("2015-03-25T12:00:00Z");
const offset = new Date("2015-03-25T12:00:00-06:30");
```
Parse a string to ms, then to a Date:
```javascript
let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **ISO vs Short vs Long** — ISO (`YYYY-MM-DD`) is the preferred, strict, and most reliable format; Short (`MM/DD/YYYY`) and Long (`MMM DD YYYY`) are more permissive but ambiguous (month/day order can vary). Prefer ISO for unambiguous parsing. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source advises ISO as the preferred and most reliable format over the more permissive Short/Long forms. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Dates]], [[JavaScript Date Methods]], [[JavaScript Date Get Methods]]
- **참조 맥락:** Referenced whenever a date string must be parsed or formatted for the Date constructor.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Date Formats — https://www.w3schools.com/js/js_date_formats.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Date Formats" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,247 @@
---
id: javascript-date-get-methods
title: "JavaScript Date Get Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Date getters", "getFullYear", "getMonth", "getDate", "getTime", "Date.now", "getTimezoneOffset"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "date", "getter"]
raw_sources: ["https://www.w3schools.com/js/js_date_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Date Get Methods]]
## 🎯 한 줄 통찰 (One-line insight)
Date Get methods read individual parts out of a `Date` object — year, month, day, weekday, hours, minutes, seconds, milliseconds, and the underlying timestamp — with month and weekday returned as zero-based numbers. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`new Date()` creates a date object** holding a date and time. Get methods then extract individual components from it. [S1]
- **Months are zero-based** — `getMonth()` returns `0-11`, where January is 0. [S1]
- **Weekdays are zero-based** — `getDay()` returns `0-6`, where Sunday is 0. [S1]
- **`getTime()` returns the timestamp** — milliseconds since January 1, 1970. [S1]
- **`Date.now()` is a static method** that returns the current milliseconds since January 1, 1970 (it is a method of `Date`, not of a date instance). [S1]
- **`getTimezoneOffset()`** returns the difference, in minutes, between local time and UTC. UTC time is the same as GMT. [S1]
- **`getYear()` is deprecated** — old code may use it to return a 2-digit year; do not use it. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Number-to-name lookup** — because `getMonth()`/`getDay()` return zero-based numbers, map them to readable names through an array indexed by that number. [S1]
- **Hardcoded vs current date** — the same getter works on a parsed literal (`new Date("2021-03-25")`) or on the current moment (`new Date()`). [S1]
- **Derive durations from timestamps** — divide `Date.now()` by a precomputed unit (ms per year) to estimate elapsed time. [S1]
## 📖 세부 내용 (Details)
**Creating a date object** [S1]
```javascript
const date = new Date();
```
**getFullYear() — year as a four digit number (yyyy)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getFullYear();
```
```javascript
const d = new Date();
d.getFullYear();
```
**getMonth() — month as a number (0-11)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getMonth();
```
```javascript
const d = new Date();
d.getMonth();
```
You can use an array of names to return the month as a name: [S1]
```javascript
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const d = new Date("2021-03-25");
let month = months[d.getMonth()];
```
```javascript
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const d = new Date();
let month = months[d.getMonth()];
```
**getDate() — day as a number (1-31)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getDate();
```
```javascript
const d = new Date();
d.getDate();
```
**getHours() — hour (0-23)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getHours();
```
```javascript
const d = new Date();
d.getHours();
```
**getMinutes() — minute (0-59)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getMinutes();
```
```javascript
const d = new Date();
d.getMinutes();
```
**getSeconds() — second (0-59)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getSeconds();
```
```javascript
const d = new Date();
d.getSeconds();
```
**getMilliseconds() — millisecond (0-999)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getMilliseconds();
```
```javascript
const d = new Date();
d.getMilliseconds();
```
**getDay() — weekday as a number (0-6)** [S1]
```javascript
const d = new Date("2021-03-25");
d.getDay();
```
```javascript
const d = new Date();
d.getDay();
```
You can use an array of names to return the weekday as a name: [S1]
```javascript
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const d = new Date("2021-03-25");
let day = days[d.getDay()];
```
```javascript
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const d = new Date();
let day = days[d.getDay()];
```
**getTime() — milliseconds since January 1, 1970** [S1]
```javascript
const d = new Date("1970-01-01");
d.getTime();
```
```javascript
const d = new Date("2021-03-25");
d.getTime();
```
```javascript
const d = new Date();
d.getTime();
```
**Date.now() — current milliseconds since January 1, 1970** [S1]
```javascript
let ms = Date.now();
```
Calculate the number of years since 1970: [S1]
```javascript
const minute = 1000 * 60;
const hour = minute * 60;
const day = hour * 24;
const year = day * 365;
let years = Math.round(Date.now() / year);
```
**getTimezoneOffset() — difference between local time and UTC, in minutes** [S1]
```javascript
let diff = d.getTimezoneOffset();
```
**Date Get Methods** [S1]
| Method | Description |
|--------|-------------|
| getFullYear() | Get **year** as a four digit number (yyyy) |
| getMonth() | Get **month** as a number (0-11) |
| getDate() | Get **day** as a number (1-31) |
| getDay() | Get **weekday** as a number (0-6) |
| getHours() | Get **hour** (0-23) |
| getMinutes() | Get **minute** (0-59) |
| getSeconds() | Get **second** (0-59) |
| getMilliseconds() | Get **millisecond** (0-999) |
| getTime() | Get **time** (milliseconds since January 1, 1970) |
**UTC Date Get Methods** — UTC time is the same as GMT. [S1]
| Method | Same As | Description |
|--------|---------|-------------|
| getUTCDate() | getDate() | Returns the UTC date |
| getUTCFullYear() | getFullYear() | Returns the UTC year |
| getUTCMonth() | getMonth() | Returns the UTC month |
| getUTCDay() | getDay() | Returns the UTC day |
| getUTCHours() | getHours() | Returns the UTC hour |
| getUTCMinutes() | getMinutes() | Returns the UTC minutes |
| getUTCSeconds() | getSeconds() | Returns the UTC seconds |
| getUTCMilliseconds() | getMilliseconds() | Returns the UTC milliseconds |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — reading components off both a parsed literal date and the current date, and converting zero-based month/weekday numbers to names via lookup arrays. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Convert a zero-based month number to a readable name (language: JavaScript):
```javascript
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const d = new Date();
let month = months[d.getMonth()];
```
Get the current timestamp:
```javascript
let ms = Date.now();
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
The source flags `getYear()` as deprecated and non-standard; `getFullYear()` is the standard replacement. No other contradictions found in the source. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Date Set Methods]], [[JavaScript Date Methods]], [[JavaScript Dates]]
- **참조 맥락:** Used whenever reading date/time parts out of a Date object for display or computation.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Date Get Methods — https://www.w3schools.com/js/js_date_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Date Get Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,144 @@
---
id: javascript-date-methods
title: "JavaScript Date Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Date reference", "Date object methods", "Date prototype", "Date.parse", "Date.UTC", "toISOString"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "date", "reference"]
raw_sources: ["https://www.w3schools.com/js/js_date_reference.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Date Methods]]
## 🎯 한 줄 통찰 (One-line insight)
This is the complete reference of `Date` object members — constructor/properties, get and set methods (local and UTC), utility statics, and string-conversion methods — the master index behind the more focused Date tutorials. [S1]
## 🧠 핵심 개념 (Core concepts)
- **The Date API splits into families** — constructor/properties, Get methods, Set methods, utility statics, and string-conversion methods. [S1]
- **Every Get/Set field has a UTC counterpart** — e.g. `getDate()` / `getUTCDate()`, `setHours()` / `setUTCHours()`. [S1]
- **Static utility methods** — `now()`, `parse()`, and `UTC()` are called on `Date` itself and work with millisecond timestamps. [S1]
- **Many conversion methods** — `toString()`, `toISOString()`, `toDateString()`, `toLocaleString()`, and others render a Date as a string in different formats/locales. [S1]
- **Deprecated members** — `getYear()`/`setYear()` (use `getFullYear()`/`setFullYear()`) and `toGMTString()` (use `toUTCString()`). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Local vs UTC symmetry** — for any field, pick the plain method for local time or the `UTC` variant for universal time. [S1]
- **Static parsing/construction** — turn strings or component lists into timestamps with `Date.parse()` and `Date.UTC()`, current time with `Date.now()`. [S1]
- **Choose a string formatter by need** — ISO (`toISOString`), JSON (`toJSON`), locale-aware (`toLocale*String`), or date/time-only (`toDateString`, `toTimeString`). [S1]
## 📖 세부 내용 (Details)
This page is a reference index of `Date` methods and properties grouped by family. No "Example" code boxes were present to capture; the content is the reference tables below. [S1]
**Date Constructor & Properties** [S1]
| Method/Property | Description |
|---|---|
| new Date() | Creates a new Date object |
| constructor | Returns the function that created the Date prototype |
| prototype | Allows you to add properties and methods to an object |
**Date Get Methods** [S1]
| Method | Description |
|---|---|
| getDate() | Returns the day of the month (from 1-31) |
| getDay() | Returns the day of the week (from 0-6) |
| getFullYear() | Returns the year |
| getHours() | Returns the hour (from 0-23) |
| getMilliseconds() | Returns the milliseconds (from 0-999) |
| getMinutes() | Returns the minutes (from 0-59) |
| getMonth() | Returns the month (from 0-11) |
| getSeconds() | Returns the seconds (from 0-59) |
| getTime() | Returns the number of milliseconds since midnight Jan 1 1970 |
| getTimezoneOffset() | Returns the time difference between UTC time and local time, in minutes |
| getUTCDate() | Returns the day of the month, according to universal time (1-31) |
| getUTCDay() | Returns the day of the week, according to universal time (0-6) |
| getUTCFullYear() | Returns the year, according to universal time |
| getUTCHours() | Returns the hour, according to universal time (from 0-23) |
| getUTCMilliseconds() | Returns the milliseconds, according to universal time (0-999) |
| getUTCMinutes() | Returns the minutes, according to universal time (from 0-59) |
| getUTCMonth() | Returns the month, according to universal time (from 0-11) |
| getUTCSeconds() | Returns the seconds, according to universal time (from 0-59) |
| getYear() | Deprecated. Use getFullYear() instead |
**Date Set Methods** [S1]
| Method | Description |
|---|---|
| setDate() | Sets the day of the month of a date object |
| setFullYear() | Sets the year of a date object |
| setHours() | Sets the hour of a date object |
| setMilliseconds() | Sets the milliseconds of a date object |
| setMinutes() | Set the minutes of a date object |
| setMonth() | Sets the month of a date object |
| setSeconds() | Sets the seconds of a date object |
| setTime() | Sets a date to a specified number of milliseconds after/before January 1, 1970 |
| setUTCDate() | Sets the day of the month of a date object, according to universal time |
| setUTCFullYear() | Sets the year of a date object, according to universal time |
| setUTCHours() | Sets the hour of a date object, according to universal time |
| setUTCMilliseconds() | Sets the milliseconds of a date object, according to universal time |
| setUTCMinutes() | Set the minutes of a date object, according to universal time |
| setUTCMonth() | Sets the month of a date object, according to universal time |
| setUTCSeconds() | Set the seconds of a date object, according to universal time |
| setYear() | Deprecated. Use setFullYear() instead |
**Date Utility Methods** [S1]
| Method | Description |
|---|---|
| now() | Returns the number of milliseconds since midnight Jan 1, 1970 |
| parse() | Parses a date string and returns milliseconds since January 1, 1970 |
| UTC() | Returns the number of milliseconds in a date since midnight of January 1, 1970 |
**Date String Conversion Methods** [S1]
| Method | Description |
|---|---|
| toDateString() | Converts the date portion of a Date object into a readable string |
| toGMTString() | Deprecated. Use toUTCString() instead |
| toISOString() | Returns the date as a string, using the ISO standard |
| toJSON() | Returns the date as a string, formatted as a JSON date |
| toLocaleDateString() | Returns the date portion of a Date object as a string, using locale conventions |
| toLocaleTimeString() | Returns the time portion of a Date object as a string, using locale conventions |
| toLocaleString() | Converts a Date object to a string, using locale conventions |
| toString() | Converts a Date object to a string |
| toTimeString() | Converts the time portion of a Date object to a string |
| toUTCString() | Converts a Date object to a string, according to universal time |
| valueOf() | Returns the primitive value of a Date object |
## 🛠️ 적용 사례 (Applied in summary)
As a reference page it has no worked examples; it is the lookup table consulted when picking the right Date method. Worked examples live in the focused tutorials ([[JavaScript Date Get Methods]], [[JavaScript Date Set Methods]]). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Not found in source — this reference page contains no "Example" code boxes; only the method/property tables above. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
The reference marks `getYear()`/`setYear()` and `toGMTString()` as deprecated, pointing to `getFullYear()`/`setFullYear()` and `toUTCString()` respectively. No other contradictions found in the source. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Date Get Methods]], [[JavaScript Date Set Methods]], [[JavaScript Dates]]
- **참조 맥락:** The master index of the Date object — consulted to find the exact method name and signature.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Date Methods — https://www.w3schools.com/js/js_date_reference.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Date Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,154 @@
---
id: javascript-date-set-methods
title: "JavaScript Date Set Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Date setters", "setFullYear", "setMonth", "setDate", "setHours", "setTime", "date comparison"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "date", "setter"]
raw_sources: ["https://www.w3schools.com/js/js_date_methods_set.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Date Set Methods]]
## 🎯 한 줄 통찰 (One-line insight)
Date Set methods write a part of a `Date` object — year, month, day, hour, minute, second, millisecond, or the raw timestamp — and several accept cascading parameters so multiple parts can be set in one call. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Set Date methods set a part of a date.** [S1]
- **Months count from 0 to 11** — January is 0, December is 11. [S1]
- **Cascading parameters** — `setFullYear()` can also take month and day; `setHours()` can also take minutes and seconds, letting you set several fields at once. [S1]
- **Arithmetic via get + set** — combine a getter with a setter (`d.setDate(d.getDate() + 50)`) to shift a date; boundary crossings into the next month/year adjust automatically. [S1]
- **Dates are comparable** — relational operators (`>`, `<`) compare two `Date` objects directly. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Add-to-existing-field** — read a field, add to it, set it back: `d.setDate(d.getDate() + 50)`. [S1]
- **Build a target date then compare** — create a date, set its fields to a future point, then test with `if (someday > today)`. [S1]
- **One-call multi-field set** — pass extra arguments to a single setter instead of calling several setters. [S1]
## 📖 세부 내용 (Details)
**setFullYear() — set the year (yyyy)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setFullYear(2020);
```
`setFullYear()` can optionally set the month and day as well: [S1]
```javascript
const d = new Date("January 01, 2025");
d.setFullYear(2020, 11, 3);
```
**setMonth() — set the month (0-11)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setMonth(11);
```
**setDate() — set the day as a number (1-31)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setDate(15);
```
`setDate()` can also be used to add days to a date: [S1]
```javascript
const d = new Date("January 01, 2025");
d.setDate(d.getDate() + 50);
```
**setHours() — set the hour (0-23)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setHours(22);
```
`setHours()` can also set minutes and seconds: [S1]
```javascript
const d = new Date("January 01, 2025");
d.setHours(22, 10, 20);
```
**setMinutes() — set the minutes (0-59)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setMinutes(30);
```
**setSeconds() — set the seconds (0-59)** [S1]
```javascript
const d = new Date("January 01, 2025");
d.setSeconds(30);
```
**Compare Dates** — dates can easily be compared. The example sets a future date and compares it to today: [S1]
```javascript
let text = "";
const today = new Date();
const someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
```
**Set Date Methods** [S1]
| Method | Description |
|--------|-------------|
| setDate() | Set the day as a number (1-31) |
| setFullYear() | Set the year (yyyy) |
| setHours() | Set the hour (0-23) |
| setMilliseconds() | Set the milliseconds (0-999) |
| setMinutes() | Set the minutes (0-59) |
| setMonth() | Set the month (0-11) |
| setSeconds() | Set the seconds (0-59) |
| setTime() | Set the time (milliseconds since January 1, 1970) |
**Note:** JavaScript counts months from 0 to 11. January is 0. December is 11. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — setting individual fields on a parsed date, adding 50 days via `setDate(d.getDate() + 50)`, and building a future date to compare against today. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Shift a date forward by N days (language: JavaScript):
```javascript
const d = new Date("January 01, 2025");
d.setDate(d.getDate() + 50);
```
Set multiple fields in one call:
```javascript
const d = new Date("January 01, 2025");
d.setHours(22, 10, 20);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Date Get Methods]], [[JavaScript Date Methods]], [[JavaScript Dates]]
- **참조 맥락:** Used whenever mutating a Date object — adjusting fields, doing date arithmetic, or building target dates for comparison.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Date Set Methods — https://www.w3schools.com/js/js_date_methods_set.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Date Set Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,158 @@
---
id: javascript-dates
title: "JavaScript Dates"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Date object", "new Date", "Date.now", "date constructor", "JS dates"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "date", "time"]
raw_sources: ["https://www.w3schools.com/js/js_dates.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Dates]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript dates are created with `new Date()` in several argument forms (none, a date string, 27 numbers, or milliseconds since the 1970 epoch), and months are counted from 0 (January) to 11 (December). [S1]
## 🧠 핵심 개념 (Core concepts)
- **`new Date()`** creates a date object with the current date and time. [S1]
- **`new Date(date string)`** creates a date from a date string. [S1]
- **`new Date(year, month, ...)`** creates a date from numeric components (year, month, day, hours, minutes, seconds, milliseconds). [S1]
- **`new Date(milliseconds)`** creates a date as milliseconds since January 1, 1970 (the epoch / zero time). [S1]
- **Months are zero-indexed** — January = 0, December = 11. [S1]
- **Date objects are static** — the computer time is ticking, but the date object, once created, is not. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Now** — `new Date()` for current date/time. [S1]
- **From components** — `new Date(year, month, day, ...)`, remembering month is 0-based. [S1]
- **From epoch ms** — `new Date(ms)`; `new Date(0)` is the 1970 epoch. [S1]
- **Display conversions** — `toString`, `toDateString`, `toUTCString`, `toISOString`. [S1]
## 📖 세부 내용 (Details)
**Creating Date Objects** — Date objects are created with the `new Date()` constructor. There are 4 ways to create a new date object: with no arguments, with a date string, with date arguments (numbers), or with milliseconds. [S1]
**new Date()** — creates a date object with the current date and time: [S1]
```javascript
const d = new Date();
```
**new Date(date string)** — creates a date object from a date string: [S1]
```javascript
const d = new Date("October 13, 2014 11:13:00");
```
```javascript
const d = new Date("2022-03-25");
```
**new Date(year, month, ...)** — creates a date object with a specified date and time. 7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order): [S1]
```javascript
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
```
6 numbers specify year, month, day, hour, minute, second: [S1]
```javascript
const d = new Date(2018, 11, 24, 10, 33, 30);
```
5 numbers specify year, month, day, hour, and minute: [S1]
```javascript
const d = new Date(2018, 11, 24, 10, 33);
```
4 numbers specify year, month, day, and hour: [S1]
```javascript
const d = new Date(2018, 11, 24, 10);
```
3 numbers specify year, month, and day: [S1]
```javascript
const d = new Date(2018, 11, 24);
```
2 numbers specify year and month: [S1]
```javascript
const d = new Date(2018, 11);
```
> Note: JavaScript counts months from 0 to 11: January = 0. December = 11. [S1]
**new Date(milliseconds)** — creates a new date object as zero time plus milliseconds. January 01 1970 plus 100 000 000 000 milliseconds is approximately March 03 1973: [S1]
```javascript
const d = new Date(100000000000);
```
Negative milliseconds go before 1970: [S1]
```javascript
const d = new Date(-100000000000);
```
One day (24 hours) in milliseconds: [S1]
```javascript
const d = new Date(24 * 60 * 60 * 1000);
// or
const d = new Date(86400000);
```
Zero time is January 01 1970 00:00:00 UTC: [S1]
```javascript
const d = new Date(0);
```
**Displaying Dates** — JavaScript will (by default) output dates using the `toString()` method, a string representation of the date including the time zone. Other conversions: [S1]
```javascript
const d = new Date();
d.toString();
```
```javascript
const d = new Date();
d.toDateString();
```
```javascript
const d = new Date();
d.toUTCString();
```
```javascript
const d = new Date();
d.toISOString();
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — creating "now", a date from a string, a date from 27 numeric components, dates from milliseconds (including `new Date(0)`), and converting to string formats. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Current date / from components / from epoch:
```javascript
const now = new Date();
const dec24 = new Date(2018, 11, 24, 10, 33, 30); // month 11 = December
const epoch = new Date(0); // Jan 01 1970 UTC
```
Display conversions:
```javascript
const d = new Date();
d.toDateString();
d.toUTCString();
d.toISOString();
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source emphasizes the zero-based month convention (January = 0) as a common point of confusion. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Date Formats]], [[JavaScript Date Methods]], [[JavaScript Numbers]]
- **참조 맥락:** Referenced whenever date/time values must be created or displayed.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Dates — https://www.w3schools.com/js/js_dates.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Dates" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,211 @@
---
id: javascript-destructuring
title: "JavaScript Destructuring"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["destructuring", "JS destructuring", "destructuring assignment", "object destructuring", "array destructuring", "rest property"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "destructuring", "es6"]
raw_sources: ["https://www.w3schools.com/js/js_destructuring.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Destructuring]]
## 🎯 한 줄 통찰 (One-line insight)
Destructuring assignment unpacks objects and arrays (and any iterable) into individual variables without mutating the original — supporting defaults, aliases, skipping, position picks, and a rest property. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Unpacks objects into variables** — The destructuring assignment syntax can unpack objects into variables. [S1]
- **Order-independent for objects** — When destructuring objects, the order of the properties does not matter. [S1]
- **Non-destructive** — Destructuring is not destructive; it does not change the original object. [S1]
- **Default values** — For potentially missing properties you can set default values. [S1]
- **Property aliases** — A destructured property can be renamed into a different variable name. [S1]
- **Works on any iterable** — Destructuring can be used with any iterables, including strings. [S1]
- **Array picks and skips** — You can pick array variables, skip values with extra commas, and pick by specific index. [S1]
- **Rest property** — Ending a destructuring with a rest property stores all remaining values into a new array. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`{a, b} = obj`** — Object destructuring binds by property name, in any order. [S1]
- **`{x = default}`** — Supply defaults inline for properties that may be missing. [S1]
- **`{prop : alias}`** — Rename a property into a new variable. [S1]
- **`[a,,,b]`** — Use extra commas to skip array positions. [S1]
- **`{[0]:x ,[1]:y}`** — Pick array values by specific index. [S1]
- **`[a, b, ...rest]`** — Collect remaining array values into `rest`. [S1]
- **`[a, b] = [b, a]`** — Swap two variables in one statement. [S1]
## 📖 세부 내용 (Details)
**Destructuring Assignment Syntax**
The destructuring assignment syntax can unpack objects into variables: [S1]
```javascript
let {firstName, lastName} = person;
```
**Object Destructuring** [S1]
```javascript
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
// Destructuring
let {firstName, lastName} = person;
```
The order of the properties does not matter: [S1]
```javascript
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
// Destructuring
let {lastName, firstName} = person;
```
Destructuring is not destructive. Destructuring does not change the original object. [S1]
**Object Default Values** — For potentially missing properties we can set default values: [S1]
```javascript
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
// Destructuring
let {firstName, lastName, country = "US"} = person;
```
**Object Property Alias** [S1]
```javascript
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
// Destructuring
let {lastName : name} = person;
```
**String Destructuring** — One use for destructuring is unpacking string characters. Destructuring can be used with any iterables. [S1]
```javascript
// Create a String
let name = "W3Schools";
// Destructuring
let [a1, a2, a3, a4, a5] = name;
```
**Array Destructuring** — We can pick up array variables into our own variables: [S1]
```javascript
// Create an Array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit1, fruit2] = fruits;
```
**Skipping Array Values** — We can skip array values using two or more commas: [S1]
```javascript
// Create an Array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit1,,,fruit2] = fruits;
```
**Array Position Values** — We can pick up values from specific index locations of an array: [S1]
```javascript
// Create an Array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let {[0]:fruit1 ,[1]:fruit2} = fruits;
```
**The Rest Property** — You can end a destructuring syntax with a rest property. This syntax will store all remaining values into a new array: [S1]
```javascript
// Create an Array
const numbers = [10, 20, 30, 40, 50, 60, 70];
// Destructuring
const [a,b, ...rest] = numbers
```
**Destructuring Maps** [S1]
```javascript
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
// Destructuring
let text = "";
for (const [key, value] of fruits) {
text += key + " is " + value;
}
```
**Swapping JavaScript Variables** — You can swap the values of two variables using a destructuring assignment: [S1]
```javascript
let firstName = "John";
let lastName = "Doe";
// Destructuring
[firstName, lastName] = [lastName, firstName];
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — object/array destructuring, defaults, aliases, string and Map iteration, the rest property, and the variable-swap idiom. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Object destructuring with default and alias (language: JavaScript):
```javascript
let {firstName, lastName, country = "US"} = person;
let {lastName : name} = person;
```
Rest property collects the remainder:
```javascript
const [a, b, ...rest] = numbers;
```
Swap two variables:
```javascript
[firstName, lastName] = [lastName, firstName];
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Object Types Note]], [[JavaScript Type Conversion]], [[JavaScript Introduction]], [[JavaScript NaN]]
- **참조 맥락:** Referenced whenever extracting fields from objects/arrays, setting defaults, or swapping variables in modern (ES6+) JavaScript.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Destructuring — https://www.w3schools.com/js/js_destructuring.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Destructuring" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,105 @@
---
id: javascript-error-object
title: "JavaScript Error Object"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Error object", "error reference", "err.name", "err.message", "error names"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "errors", "error-object"]
raw_sources: ["https://www.w3schools.com/js/js_error_object.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Error Object]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript's built-in Error object carries information when an error occurs, exposing useful properties such as `name` and `message`, with `name` returning one of six standard error types. [S1]
## 🧠 핵심 개념 (Core concepts)
- **The Error object** is built in and provides information when errors occur, with useful properties like `name` and `message`. [S1]
- **`Error.isError(x)`** returns true if a value is an Error. [S1]
- **Six error names** — the `name` property can return `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, or `URIError`. [S1]
- **EvalError is deprecated** — use `SyntaxError` instead. [S1]
- **Avoid non-standard members** — several properties and methods are browser-specific or outdated and should not be used. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Read `name` to branch on error type** — the standardized set of six error names lets handling code distinguish what went wrong. [S1]
- **Stick to standard members** — rely on `name`, `message`, and `cause`; avoid deprecated/non-standard properties and methods. [S1]
## 📖 세부 내용 (Details)
**The Error Object**
JavaScript includes a built-in error object providing information when errors occur, with useful properties like `name` and `message`. [S1]
**Error Object Methods & Properties** [S1]
| Property / Method | Description |
|-------------------|-------------|
| `new Error()` | Creates a new Error object |
| `name` | Sets or returns an error name |
| `message` | Sets or returns an error message |
| `cause` | Sets or returns an error cause |
| `Error.isError(x)` | Returns true if a value (x) is an Error |
**Error Names**
The `name` property can return one of six error types: [S1]
| Error Name | Description |
|------------|-------------|
| `EvalError` | Deprecated - use SyntaxError instead |
| `RangeError` | A number "out of range" has occurred |
| `ReferenceError` | An illegal reference has occurred |
| `SyntaxError` | A syntax error has occurred |
| `TypeError` | A type error has occurred |
| `URIError` | An error in encodeURI() has occurred |
Each error name has an associated "Try it" button linking to examples. No inline code examples are displayed on this reference page. [S1]
**Non-Standard Properties and Methods**
The page warns against using deprecated, browser-specific, or outdated members: [S1]
- **Properties:** `arguments`, `caller`, `columnNumber`, `description`, `displayName`, `fileName`, `lineNumber`, `number`, `stack`
- **Methods:** `evalError()`, `internalError()`, `toSource()`
## 🛠️ 적용 사례 (Applied in summary)
This is a reference page; the source displays no inline code examples (only "Try it" links). The applicable usage is reading `err.name` / `err.message` inside a `catch` block, as shown on the related Error Statements page. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Not found in source as displayed inline code; the reference page exposes only the property/method and error-name tables above and links to external "Try it" examples. The canonical access pattern (drawn from the same family of pages) is reading the standard properties:
```javascript
try {
// ...
} catch(err) {
let name = err.name; // e.g. "TypeError"
let message = err.message; // human-readable description
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **EvalError deprecation** — the source marks `EvalError` as deprecated in favor of `SyntaxError`. [S1]
- **Non-standard members** — listed properties/methods are flagged as browser-specific or outdated and should be avoided. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Errors Intro]], [[JavaScript Error Statements]], [[JavaScript Silent Errors]], [[JavaScript Debugging]]
- **참조 맥락:** The reference for the object received in a `catch` block and the standardized error names used to identify failures.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Error Object — https://www.w3schools.com/js/js_error_object.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Error Object" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,161 @@
---
id: javascript-error-statements
title: "JavaScript Error Statements"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["try catch finally", "throw statement", "error statements", "input validation", "exception handling"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "errors", "try-catch", "throw"]
raw_sources: ["https://www.w3schools.com/js/js_errors.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Error Statements]]
## 🎯 한 줄 통찰 (One-line insight)
The `try`, `catch`, `finally`, and `throw` statements form JavaScript's error-handling block: try risky code, catch failures, optionally always run cleanup in `finally`, and raise custom errors with `throw`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **The try statement** handles errors during execution without stopping the program; it works with `catch`, and optionally `finally` and `throw`. [S1]
- **The try block** holds code that might throw an error; the catch block is skipped if no error occurs. [S1]
- **The catch block** executes only if an error occurs in the try block, providing error details through an error object. [S1]
- **The finally block (optional)** runs after try and catch regardless of outcome, typically for cleanup. [S1]
- **JavaScript throws errors** by creating an Error object with `name` and `message` properties. [S1]
- **The throw statement** lets you create custom errors; you can throw strings, numbers, booleans, or objects. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Validate-then-throw** — check input conditions and `throw` a descriptive value for each failure, then format a message in `catch`. [S1]
- **Always clean up in `finally`** — use `finally` to reset state (e.g. clear an input field) whether or not an error occurred. [S1]
- **JS + HTML validation combo** — modern browsers often combine JavaScript with built-in HTML validation rules defined in HTML attributes (e.g. `min`, `max`, `step`). [S1]
## 📖 세부 내용 (Details)
**The Try Statement**
The `try` statement handles errors during code execution without stopping the program. It works with `catch`, and optionally with `finally` and `throw`. [S1]
**The Try Block / The Catch Block**
The try block contains code that might throw an error; the catch block is skipped if no error occurs. The catch block executes only if an error occurs, providing error details through an error object: [S1]
```javascript
try {
// Code that may cause an error
} catch (error) {
// Code to handle the error
}
```
**The Finally Block (Optional)**
The finally block executes after try and catch regardless of outcome, typically for cleanup tasks: [S1]
```javascript
try {
// Block of code to try
} catch(err) {
// Block of code to handle errors
} finally {
// Block of code to be executed regardless of the try / catch result
}
```
**JavaScript Throws Errors**
When errors occur, JavaScript creates an Error object with `name` and `message` properties. [S1]
**The Throw Statement**
The `throw` statement allows creation of custom errors and can throw strings, numbers, booleans, or objects. [S1]
**Input Validation Example**
Validates a number between 5 and 10, throwing `"empty"`, `"not a number"`, `"too low"`, or `"too high"` as appropriate: [S1]
```javascript
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
} catch(err) {
message.innerHTML = "Input is " + err;
}
}
```
**HTML Validation**
Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes. [S1]
**Finally Example**
A function that validates input and uses `finally` to clear the input field regardless of validation outcome: [S1]
```javascript
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
} catch(err) {
message.innerHTML = "Error: " + err + ".";
} finally {
document.getElementById("demo").value = "";
}
}
```
## 🛠️ 적용 사례 (Applied in summary)
The two `myFunction` examples are the canonical applied cases — a numeric input validator that throws descriptive strings on bad input, and a variant that additionally clears the field in `finally`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Validate input by throwing descriptive values, then format in `catch` (language: JavaScript):
```javascript
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
} catch(err) {
message.innerHTML = "Input is " + err;
}
```
Guarantee cleanup with `finally`:
```javascript
try {
// risky work
} catch(err) {
// handle
} finally {
document.getElementById("demo").value = "";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Errors Intro]], [[JavaScript Silent Errors]], [[JavaScript Error Object]], [[JavaScript Debugging]]
- **참조 맥락:** The mechanics page for the four error keywords (try/catch/finally/throw) used to build robust input validation.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Error Statements — https://www.w3schools.com/js/js_errors.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Error Statements" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,177 @@
---
id: javascript-errors-intro
title: "JavaScript Errors Intro"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JavaScript errors", "try catch throw", "ReferenceError", "TypeError", "RangeError", "error handling"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "errors", "try-catch"]
raw_sources: ["https://www.w3schools.com/js/js_errors_intro.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Errors Intro]]
## 🎯 한 줄 통찰 (One-line insight)
Errors will happen in running JavaScript code; `try` tests a block for runtime errors and `catch` handles them via an error object whose `name` identifies the error type. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Errors will happen** — many error types can occur during execution: Reference Errors, Type Errors, Range Errors, URI Errors, Syntax Errors, and Eval Errors. [S1]
- **try / catch** — the `try` statement tests a block of code for errors during execution; the `catch` statement handles the error if one occurs. [S1]
- **The error object** — the `catch` block receives an error object; `err.name` returns the type of error. [S1]
- **Syntax errors are special** — a `SyntaxError` happens before runtime, so it is not catchable by ordinary `try...catch`. [S1]
- **EvalError is legacy** — newer JavaScript versions raise `SyntaxError` instead of `EvalError`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Wrap risky code, inspect `err.name`** — put the operation that may fail inside `try`, then read `err.name` in `catch` to discover which error type occurred. [S1]
- **Trigger by error category** — each error type is provoked by a distinct kind of mistake: undefined references → `ReferenceError`; wrong-type operations → `TypeError`; out-of-range values → `RangeError`; illegal URI characters → `URIError`. [S1]
## 📖 세부 내용 (Details)
**Errors Will Happen!**
While executing JavaScript code, different errors can occur, including Reference Errors, Type Errors, Range Errors, URI Errors, Syntax Errors, and Eval Errors. [S1]
**How to Handle JavaScript Errors**
The `try` statement tests a block of code for errors during execution, while `catch` handles errors if they occur. [S1]
**Reference Errors**
A `ReferenceError` occurs when referencing a variable that doesn't exist or accessing a variable before initialization. [S1]
Using a non-existing variable: [S1]
```javascript
let x = 5;
try {
x = y + 1;
} catch(err) {
let text = err.name;
}
```
Accessing a variable before initialization: [S1]
```javascript
try {
let x = y;
let y = 5;
} catch(err) {
let text = err.name;
}
```
**JavaScript Type Errors**
A `TypeError` occurs when a value is the wrong type or an operation is invalid on that type. [S1]
Calling a non-function: [S1]
```javascript
let anna = 5;
try {
anna(5);
} catch(err) {
let text = err.name;
}
```
Invalid method on a number: [S1]
```javascript
let num = 1;
try {
num.toUpperCase();
} catch(err) {
let text = err.name;
}
```
**JavaScript Range Errors**
A `RangeError` occurs when a value falls outside its valid range. [S1]
Invalid array length: [S1]
```javascript
try {
new Array(-1);
} catch(err) {
let text = err.name;
}
```
Invalid precision argument: [S1]
```javascript
let num = 1;
try {
num.toPrecision(500);
} catch(err) {
let text = err.name;
}
```
**JavaScript URI Errors**
A `URIError` occurs with illegal characters in URI functions. [S1]
```javascript
try {
decodeURI("%%%");
} catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
```
**JavaScript Syntax Errors**
A `SyntaxError` occurs when code violates JavaScript grammar rules. Syntax errors are not catchable by `try...catch` because they happen before runtime. [S1]
```javascript
try {
let x = Math.round(4.6;)
} catch(err) {
let text = err.name + " " + err.description;
}
```
**JavaScript Eval Error**
An `EvalError` indicates an error in the `eval()` function. Newer JavaScript versions use `SyntaxError` instead. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — each wraps a deliberate mistake in `try` and reads `err.name` in `catch` to surface the resulting error type. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Wrap risky code and inspect the error type (language: JavaScript):
```javascript
try {
// code that may throw
} catch(err) {
let text = err.name;
}
```
Provoke each error category:
```javascript
x = y + 1; // ReferenceError (y not defined)
anna(5); // TypeError (anna is not a function)
new Array(-1); // RangeError (invalid array length)
decodeURI("%%%"); // URIError (illegal URI characters)
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **EvalError deprecation** — the source notes that newer JavaScript versions raise `SyntaxError` instead of `EvalError`, so `EvalError` is effectively legacy. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Silent Errors]], [[JavaScript Error Statements]], [[JavaScript Error Object]], [[JavaScript Debugging]]
- **참조 맥락:** The starting point for understanding which JavaScript error types exist and how `try...catch` surfaces them.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Errors Intro — https://www.w3schools.com/js/js_errors_intro.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Errors Intro" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,140 @@
---
id: javascript-silent-errors
title: "JavaScript Silent Errors"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["silent errors", "type coercion", "loose equality", "NaN", "weakly typed"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "errors", "coercion"]
raw_sources: ["https://www.w3schools.com/js/js_errors_silent.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Silent Errors]]
## 🎯 한 줄 통찰 (One-line insight)
Silent errors don't stop execution — JavaScript keeps running while producing wrong results from things like `1/0`, accidental assignment in conditions, failed `parseInt`, and type coercion. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Silent errors won't stop the program** — unlike thrown exceptions, silent errors let execution continue while quietly yielding wrong values. [S1]
- **Historical context** — early JavaScript lacked exception handling, contributing to silent-error behavior. [S1]
- **Failed numeric operations produce NaN** — many numeric operations that fail produce `NaN` rather than throwing an exception. [S1]
- **Type coercion** — JavaScript is weakly typed and automatically converts between data types. [S1]
- **String vs numeric coercion** — `+` with any string operand makes everything a string; other arithmetic operators force values to numbers. [S1]
- **Loose equality (`==`)** coerces operands, so `5 == "5"` is `true`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`=` vs `==` trap** — using assignment (`=`) inside an `if` condition silently sets the variable and runs the block instead of comparing. [S1]
- **Operator decides the type** — `'5' + '2'` concatenates to `"52"`; `'5' - '2'` subtracts to `3`. The operator, not the operands, dictates coercion. [S1]
- **Prefer strict equality and explicit conversion** — use `===`, convert types explicitly, and watch for `NaN` results to avoid silent bugs. [S1]
## 📖 세부 내용 (Details)
**Silent Errors**
Silent errors won't stop program execution. Historically, early JavaScript lacked exception handling, which contributed to this behavior. [S1]
Division by zero does not throw — it yields `Infinity` silently: [S1]
```javascript
let x = 1 / 0;
```
Accidental assignment inside a condition — the condition uses assignment (`isActive = true`) rather than comparison, setting the variable to true and executing the block: [S1]
```javascript
let result = "Not Active.";
let isActive = false;
// ❌ Assignment, not comparison
if (isActive = true) {
let result = "Active!";
}
```
Failed parsing produces `NaN`, not an exception. Many numeric operations that fail produce `NaN` (not an exception): [S1]
```javascript
const result = parseInt("abc");
```
Accessing a missing object property yields `undefined` silently: [S1]
```javascript
const user = {};
let result = user.name;
```
**Type Coercion**
JavaScript is weakly typed and automatically converts between data types. [S1]
```javascript
let result1 = ('5' + '2'); // = 52
let result2 = ('5' - '2'); // = 3
```
**String Coercion (+)**
If any part of a `+` operation is a string, JavaScript converts everything to strings: [S1]
```javascript
let x = "5" + 2 // x = "52"
```
**Numeric Coercion**
Other operators force values to numbers: [S1]
```javascript
let x = "5" - 2 // x = 3
```
**Loose Equality (==)**
Loose equality coerces operands before comparing: [S1]
```javascript
let x = (5 == "5") // x = true
```
**Practices to Avoid Bugs**
Three recommendations: use strict equality (`===`), be explicit with conversions, and watch for `NaN` results. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets demonstrate the silent-error patterns directly — `1/0`, the `=` inside `if`, `parseInt("abc")`, missing properties, and coercion under `+`/`-`/`==`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Avoid the assignment-in-condition trap and prefer strict equality (language: JavaScript):
```javascript
// ❌ assignment, always truthy
if (isActive = true) { /* ... */ }
// ✅ strict comparison
if (isActive === true) { /* ... */ }
```
Coercion cheat sheet:
```javascript
'5' + '2' // "52" (string concatenation)
'5' - '2' // 3 (numeric subtraction)
"5" + 2 // "52"
"5" - 2 // 3
5 == "5" // true (loose equality coerces)
parseInt("abc") // NaN (no exception thrown)
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Errors Intro]], [[JavaScript Error Statements]], [[JavaScript Comparisons]], [[JavaScript Type Conversion]]
- **참조 맥락:** Complements the thrown-error pages by covering failures that do not raise exceptions and must be caught by careful coding.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Silent Errors — https://www.w3schools.com/js/js_errors_silent.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Silent Errors" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,143 @@
---
id: javascript-dom-event-listener
title: "JavaScript DOM Event Listener"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["addEventListener", "removeEventListener", "event listener", "event bubbling", "event capturing", "useCapture"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom_eventlistener.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript DOM Event Listener]]
## 🎯 한 줄 통찰 (One-line insight)
`addEventListener()` attaches an event handler to an element without overwriting existing handlers, keeping JavaScript separate from HTML markup. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Attach without overwriting** — `addEventListener()` attaches an event handler to the specified element without overwriting existing handlers. [S1]
- **Multiple handlers allowed** — you can add many handlers of the same type, and handlers for different event types, to one element. [S1]
- **Separation of concerns** — using `addEventListener()` separates the JavaScript from the HTML markup for better readability. [S1]
- **Bubbling vs capturing** — the optional `useCapture` parameter selects event propagation order; `true` means capturing, the default `false` means bubbling. [S1]
- **Removable** — `removeEventListener()` detaches a previously attached handler. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Named handler** — pass a function name to react with reusable logic. [S1]
- **Anonymous handler** — pass an inline function for one-off logic. [S1]
- **Parameter passing** — wrap the call in an anonymous function to pass parameters to a handler. [S1]
## 📖 세부 내용 (Details)
**The addEventListener() method** [S1]
The method attaches an event handler to the specified element without overwriting existing handlers. [S1]
**Syntax** [S1]
```javascript
element.addEventListener(event, function, useCapture);
```
The first parameter is the event type (e.g. `"click"` or `"mousedown"`), the second is the function to call, and the third (`useCapture`) is optional. [S1]
**Add an Event Handler to an Element** [S1]
Attach a named handler: [S1]
```javascript
document.getElementById("myBtn").addEventListener("click", displayDate);
```
Anonymous function handler: [S1]
```javascript
element.addEventListener("click", function(){ alert("Hello World!"); });
```
Named function handler: [S1]
```javascript
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
```
**Add Many Event Handlers to the Same Element** [S1]
Multiple handlers of the same type: [S1]
```javascript
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
```
Handlers for different event types: [S1]
```javascript
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
```
**Add an Event Handler to the window Object** [S1]
The `addEventListener()` method lets you add listeners on any HTML DOM object such as the `window` object. [S1]
**Passing Parameters** [S1]
Wrap the call in an anonymous function to pass parameters: [S1]
```javascript
element.addEventListener("click", function(){ myFunction(p1, p2); });
```
**Event Bubbling or Event Capturing?** [S1]
The `useCapture` parameter controls propagation. Capturing (`true`) handles the outer element first; bubbling (`false`, default) handles the inner element first: [S1]
```javascript
document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);
```
**The removeEventListener() method** [S1]
Removes a handler attached with `addEventListener()`: [S1]
```javascript
element.removeEventListener("mousemove", myFunction);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — attaching `displayDate` to a button click, anonymous and named handlers, multiple/different-type handlers, parameter passing, capturing handlers, and `removeEventListener` — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Attach a handler (language: JavaScript):
```javascript
document.getElementById("myBtn").addEventListener("click", displayDate);
```
Pass parameters:
```javascript
element.addEventListener("click", function(){ myFunction(p1, p2); });
```
Remove a handler:
```javascript
element.removeEventListener("mousemove", myFunction);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- Use a **named handler** when the logic is reusable or you need to `removeEventListener()` it later (the same function reference is required to remove). [S1]
- Use an **anonymous handler** for short one-off logic, or to **pass parameters** by wrapping the real call. [S1]
- Set `useCapture` **`true`** for capturing (outer-to-inner) and leave it **`false`/default** for bubbling (inner-to-outer). [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript HTML Events]], [[JavaScript HTML DOM]], [[JavaScript DOM Methods]], [[JavaScript DOM Changing CSS]]
- **참조 맥락:** The script-side mechanism for wiring behavior to events, extending the inline-handler approach.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript DOM Event Listener — https://www.w3schools.com/js/js_htmldom_eventlistener.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript DOM Event Listener" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,140 @@
---
id: javascript-html-events
title: "JavaScript HTML Events"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["HTML events", "onclick", "onload", "event handlers", "JavaScript events"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_events.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript HTML Events]]
## 🎯 한 줄 통찰 (One-line insight)
HTML events are things that happen to HTML elements, and JavaScript event handlers are the code that runs when those events occur. [S1]
## 🧠 핵심 개념 (Core concepts)
- **An event handler is code that runs on an event** — an event handler is JavaScript code that runs when an event happens. [S1]
- **Events can call a function** — an event attribute can run JavaScript inline or call a named function. [S1]
- **`this` refers to the element** — inside an inline handler, `this` refers to the element that received the event. [S1]
- **addEventListener is the recommended approach** — attaching handlers with `addEventListener()` keeps JavaScript separate from the HTML markup. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Inline handler** — `onclick="..."` runs JavaScript directly in the HTML attribute. [S1]
- **Function call handler** — `onclick="displayDate()"` delegates to a named function. [S1]
- **Listener handler** — `element.addEventListener("click", fn)` attaches behavior from script. [S1]
## 📖 세부 내용 (Details)
**HTML Events** [S1]
An HTML event can be something the browser does, or something a user does. JavaScript lets you execute code when events are detected. [S1]
**JavaScript Events / Calling a JavaScript Function** [S1]
A basic `onclick` handler running JavaScript inline: [S1]
```html
<button onclick="document.getElementById('demo').innerHTML = Date()">
The time is?
</button>
```
Using `this` to refer to the element itself: [S1]
```html
<button onclick="this.innerHTML = Date()">The time is?</button>
```
Calling a named function from the handler: [S1]
```html
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
```
**Common HTML Events** [S1]
| Event | Description |
|-------|-------------|
| `onchange` | An HTML element has been changed |
| `onclick` | The user clicks an HTML element |
| `onmouseover` | The user moves the mouse over an HTML element |
| `onmouseout` | The user moves the mouse away from an HTML element |
| `onkeydown` | The user pushes a keyboard key |
| `onload` | The browser has finished loading the page |
**JavaScript Event Handlers** [S1]
An event handler is JavaScript code that runs when an event happens. [S1]
**Using an Event Listener** [S1]
The recommended way to attach a handler from script is `addEventListener()`: [S1]
```html
<button id="myBtn">Click me</button>
<p id="demo"></p>
<script>
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function () {
document.getElementById("demo").innerHTML = Date();
});
</script>
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — `onclick` writing `Date()`, `this.innerHTML`, a `displayDate()` function, and an `addEventListener("click", ...)` handler — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Inline handler (language: HTML):
```html
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
```
Function-call handler (language: HTML/JavaScript):
```html
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
```
Event listener (language: JavaScript):
```javascript
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function () {
document.getElementById("demo").innerHTML = Date();
});
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- Use **inline `on*` attributes** for quick, simple handlers written directly in the HTML. [S1]
- Use **`addEventListener()`** when you want the JavaScript separated from the HTML markup for better readability and to attach multiple handlers. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript DOM Event Listener]], [[JavaScript DOM Changing CSS]], [[JavaScript DOM Changing HTML]], [[JavaScript HTML DOM]]
- **참조 맥락:** The event layer that triggers DOM content and style changes in response to user/browser actions.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript HTML Events — https://www.w3schools.com/js/js_events.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript HTML Events" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,218 @@
---
id: javascript-function-arguments
title: "JavaScript Function Arguments"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS function arguments", "function parameters", "arguments object", "default parameters", "rest parameter", "pass by value", "pass by reference"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "arguments", "parameters"]
raw_sources: ["https://www.w3schools.com/js/js_function_arguments.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Arguments]]
## 🎯 한 줄 통찰 (One-line insight)
Parameters are the names listed in a function definition; arguments are the real values passed in — and JavaScript never checks their type or count, so missing arguments become `undefined`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Parameters vs. arguments** — parameters are the *names* in the function definition; arguments are the *real values* passed to and received by the function. [S1]
- **Order matters** — arguments are assigned to parameters in the order they appear. [S1]
- **No type or count checking** — JavaScript function definitions do not specify data types, do not perform type checking, and do not check the number of arguments received. [S1]
- **Missing arguments become `undefined`** — calling with fewer arguments than parameters leaves the missing ones `undefined`. [S1]
- **`arguments` object** — every function has a built-in `arguments` object containing an array of the arguments used at call time, reachable even when more arguments are passed than declared. [S1]
- **Pass by value vs. reference** — primitives are passed by value (changes are not reflected outside); objects behave like they are passed by reference (changing an object property changes the original). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Variadic via `arguments`** — loop over `arguments.length` to handle an indefinite number of inputs without declaring parameters. [S1]
- **Default parameter guard** — set a default with `y = 10` in the signature (ES2015), or the older `if (y === undefined) y = 2;` pattern. [S1]
- **Rest parameter collection** — `...args` gathers an indefinite number of arguments into a real array for iteration with `for...of`. [S1]
## 📖 세부 내용 (Details)
**Parameters vs. Arguments**
Function **parameters** are the names listed in the function definition. **Arguments** are the real values passed to, and received by, the function. [S1]
```javascript
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
```
Here `a` and `b` are parameters; `4` and `5` are arguments. The argument `4` is assigned to parameter `a` and `5` to parameter `b`. [S1]
**The Arguments Object**
JavaScript functions have a built-in `arguments` object that contains an array of the arguments used when the function was invoked. This lets a function find, for instance, the highest value in a list of numbers: [S1]
```javascript
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
```
Or sum all input values: [S1]
```javascript
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
```
If a function is called with too many arguments (more than declared), those arguments can still be reached using the `arguments` object. [S1]
**The Order of Arguments Matters**
Arguments are assigned to parameters in the order they appear. [S1]
```javascript
function subtract(a, b) {
return a - b;
}
let x1 = subtract(10, 5);
let x2 = subtract(5, 10);
```
The two calls return different results because the order is different. [S1]
**Arguments Can Be Variables**
Arguments do not have to be values; they can also be variables. [S1]
```javascript
let x = 5;
let y = 6;
function multiply(a, b) {
return a * b;
}
multiply(x, y);
```
**Argument Rules**
JavaScript function definitions do not specify data types for arguments. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received. [S1]
**Incorrect Arguments**
Incorrect arguments can return incorrect answers: [S1]
```javascript
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius("John");
```
**Missing Arguments**
If a function is called with fewer arguments than parameters, the missing values become `undefined`. [S1]
```javascript
function multiply(a, b) {
return a * b;
}
multiply(4);
```
Here `b` is `undefined`, so the result is `NaN`. A JavaScript function does not perform any checking on parameter values. [S1]
**Default Parameters**
If a function is called with missing arguments, the missing values are set to `undefined`. Sometimes it is better to assign a default value to the parameter: [S1]
```javascript
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
}
```
**Default Parameter Values**
ECMAScript 2015 allows function parameters to have default values. The default value is used if no argument is provided. If `y` is not passed or `undefined`, then `y = 10`: [S1]
```javascript
function myFunction(x, y = 10) {
return x + y;
}
myFunction(5);
```
**Function Rest Parameter**
The rest parameter (`...`) allows a function to treat an indefinite number of arguments as an array: [S1]
```javascript
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
```
**Arguments are Passed by Value**
The parameters in a function call are the function's arguments. JavaScript arguments are passed by value: the function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function. [S1]
**Objects are Passed by Reference**
In JavaScript, object references are values. Because of this, objects will behave like they are passed by reference: if a function changes an object property, it changes the original value. Changes to object properties are visible (reflected) outside the function. [S1]
**Common Mistakes**
Confusing parameters and arguments (parameters are names, arguments are values); forgetting the order (arguments are assigned by position); missing arguments (use default values to avoid `undefined`). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `multiply`/`subtract` for parameter binding, `findMax`/`sumAll` for the `arguments` object, and `sum(...args)` for the rest parameter. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Default parameter value (ES2015):
```javascript
function myFunction(x, y = 10) {
return x + y;
}
```
Variadic via rest parameter:
```javascript
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
```
Variadic via the `arguments` object:
```javascript
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The page notes a version distinction: default parameter values are an ECMAScript 2015 feature, contrasted with the older `if (y === undefined)` guard pattern. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Function Expressions]], [[JavaScript Arrow Functions]], [[JavaScript Objects]]
- **참조 맥락:** Referenced whenever defining functions and reasoning about how values reach them, including variadic functions and defaults.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Arguments — https://www.w3schools.com/js/js_function_arguments.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Arguments" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,184 @@
---
id: javascript-function-expressions
title: "JavaScript Function Expressions"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS function expressions", "anonymous functions", "function declaration vs expression", "hoisting", "named function expression", "callbacks"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "expressions", "hoisting"]
raw_sources: ["https://www.w3schools.com/js/js_function_expressions.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Expressions]]
## 🎯 한 줄 통찰 (One-line insight)
A function expression is a function stored in a variable — it behaves like a value (great for callbacks) but, unlike a function declaration, it is not hoisted and cannot be called before it is defined. [S1]
## 🧠 핵심 개념 (Core concepts)
- **A function expression is a function stored in a variable.** [S1]
- **Often anonymous** — functions stored in variables do not need names; the variable name is used to call the function. They can still be named. [S1]
- **It is a statement** — a function expression usually ends with a semicolon. [S1]
- **Used as a value** — because it is stored in a variable, it can be passed to other functions (callbacks). [S1]
- **Hoisting difference** — function declarations are hoisted and can be called before they are defined; function expressions are not hoisted and cannot. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Store-then-call** — assign a function to a `const`, then invoke through the variable name (`sayHello()`). [S1]
- **Callback passing** — pass a function expression as an argument so another function can invoke it (`run(sayHello)`). [S1]
- **Define-before-use ordering** — because expressions are not hoisted, declare them above the point of first call. [S1]
## 📖 세부 내용 (Details)
**What is a Function Expression?**
A function expression is a function stored in a variable. A standard function: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
```
A function expression: [S1]
```javascript
const multiply = function(a, b) {
return a * b;
};
```
After storing in a variable, the variable can be used as a function: [S1]
```javascript
let z = multiply(4, 3);
```
**Anonymous Functions**
Function expressions commonly create anonymous functions. The function is actually a function without a name; functions stored in variables do not need names — the variable name is used to call the function. However, function expressions can also be named: [S1]
```javascript
const add = function add(a, b) {return a + b;};
```
**Function Expressions Use Semicolons**
A function expression is a JavaScript statement. That is why it usually ends with a semicolon. [S1]
```javascript
const add = function(a, b) {
return a + b;
};
```
**Functions Stored in Variables**
Because a function expression is stored in a variable, it can be used like a value. This is useful when passing functions to other functions (callbacks). [S1]
```javascript
function run(fn) {
return fn();
}
const sayHello = function() {
return "Hello";
};
run(sayHello);
```
**Functions vs. Function Expressions**
JavaScript functions are defined with the `function` keyword and can be defined in different ways. They both work the same when you call them; the difference is when they become available in your code. [S1]
**Function Declarations vs Function Expression**
A function declaration uses the `function` keyword, has a function name, parameters in parentheses, and a code block in brackets: [S1]
```javascript
function add(a, b) {return a + b;}
```
A function expression uses the `function` keyword, parameters in parentheses, and a code block in brackets: [S1]
```javascript
const add = function(a, b) {return a + b;};
```
Example: [S1]
```javascript
const sayHello = function() {
return "Hello World";
};
sayHello();
```
The function above is stored in the variable `sayHello`. To run it, you call `sayHello()`. [S1]
**Hoisting**
Function declarations can be called before they are defined. Function expressions can not be called before they are defined. Function declarations are hoisted: [S1]
```javascript
let sum = add(2, 3); // Will work
function add(a, b) {return a + b;}
```
Function expressions are not hoisted: [S1]
```javascript
let sum = add(2, 3); // ⛔ Will generate error
const add = function (a, b) {return a + b;};
```
**Key Differences**
Syntax: function declarations require a name; function expressions can be anonymous. Hoisting: function declarations are hoisted, function expressions are not. Flexibility: function declarations offer more flexibility in how and where they are used. [S1]
**When to Use Each**
Use function declarations for general-purpose functions; use function expressions when assigning functions to variables; use function expressions in callbacks and event handlers. [S1]
**Later in this Tutorial**
Function expressions enable several advanced techniques: arrow functions (modern concise `=>` syntax for function expressions), callbacks (passing functions as arguments), closures (accessing variables from the containing scope), and IIFEs (functions that execute immediately upon definition). [S1]
**Common Mistakes**
Forgetting the semicolon (expressions are statements and should end with semicolons); expecting hoisting (expressions are not hoisted, cannot call before definition); confusing reference and call (`sayHello` is the function, `sayHello()` calls it); confusing function names and variables (in expressions, the variable name provides the function reference). [S1]
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Aspect | Function Declaration | Function Expression |
| --- | --- | --- |
| Name | Required | Can be anonymous | [S1]
| Hoisting | Hoisted (callable before definition) | Not hoisted (must define first) | [S1]
| Flexibility | More flexible in how/where used | Used as a value (callbacks, variables) | [S1]
| When to use | General-purpose functions | Variable assignment, callbacks, event handlers | [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `multiply`/`add` expressions, the `run(sayHello)` callback pattern, and the hoisting error/success comparison. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Function expression stored in a variable:
```javascript
const multiply = function(a, b) {
return a * b;
};
```
Passing a function expression as a callback:
```javascript
function run(fn) {
return fn();
}
const sayHello = function() {
return "Hello";
};
run(sayHello);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Arrow Functions]], [[JavaScript Function Arguments]], [[JavaScript Objects]]
- **참조 맥락:** Referenced when choosing between declaration and expression syntax, and as the foundation for arrow functions, callbacks, and closures.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Expressions — https://www.w3schools.com/js/js_function_expressions.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Expressions" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,152 @@
---
id: javascript-function-definitions
title: "JavaScript Function Definitions"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["function definitions", "function declaration", "function syntax", "defining functions", "local variables", "function intro"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "definitions"]
raw_sources: ["https://www.w3schools.com/js/js_function_intro.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Definitions]]
## 🎯 한 줄 통찰 (One-line insight)
A function is defined with the `function` keyword, a name, a parenthesized parameter list, and a body — once defined it is a reusable block that runs only when called. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Functions are code blocks** — reusable code designed to perform a particular task; they execute when called or invoked. [S1]
- **Definition syntax** — `function name(p1, p2, ...) { ... }`: keyword, name, comma-separated parameters in parentheses, body in braces. [S1]
- **Why define functions** — to reuse code (write once, run many times) and organize code into manageable sections. [S1]
- **Run on call** — the body does not run at definition time; it runs when the function is invoked. [S1]
- **Local variables** — variables declared inside a function are accessible only within it, created when the function starts and deleted when it completes. [S1]
- **Functions as variable values** — a function call can be used wherever a value is expected. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Name → parameters → body** — the standard declaration shape that makes a block callable by name. [S1]
- **Parameterized reuse** — define once with parameters, call repeatedly with different arguments. [S1]
- **Scope by definition** — placing a `let` inside the function body confines it to that function. [S1]
## 📖 세부 내용 (Details)
**Functions are Code Blocks** — functions are reusable code blocks designed to perform a particular task; they execute when they are called or invoked. [S1]
**Why Use Functions?** — functions let you reuse code (write once, run many times) and organize code into manageable sections. [S1]
**JavaScript Function Syntax** — a function is defined with the `function` keyword, a name, parameters in parentheses, and a body in curly braces: [S1]
```javascript
function name( p1, p2, ... ) {
// code to be executed
}
```
**What Does a Function Look Like?** — a basic definition: [S1]
```javascript
function sayHello() {
return "Hello World";
}
```
**Functions Run When You Call Them** — the defined function runs only when invoked, and the returned value can be stored: [S1]
```javascript
function sayHello() {
return "Hello World";
}
let message = sayHello();
```
A definition with parameters: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
```
**A Function Can Be Used Many Times** — the same definition is reused with different arguments: [S1]
```javascript
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
```
**Local Variables** — variables declared inside a function can only be accessed from within the function; they are created when the function starts and deleted when it completes: [S1]
```javascript
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
```
**Functions Used as Variables** — a function call can be used directly inside an expression: [S1]
```javascript
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
```
And inlined directly: [S1]
```javascript
let text = "The temperature is " + toCelsius(77) + " Celsius";
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — defining `sayHello()`, `multiply(a, b)`, the reusable `add(a, b)`, the scoped `myFunction()`, and using `toCelsius(77)` as a value. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Define a function (language: JavaScript):
```javascript
function name( p1, p2, ... ) {
// code to be executed
}
```
Define and reuse with parameters:
```javascript
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
```
Confine a variable to a function:
```javascript
function myFunction() {
let carName = "Volvo";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Functions]], [[JavaScript Function Invocation]], [[JavaScript Function Parameters]], [[JavaScript Function Returns]]
- **참조 맥락:** Referenced when learning how to declare and scope a reusable callable block.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Definitions — https://www.w3schools.com/js/js_function_intro.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Definitions" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,197 @@
---
id: javascript-function-invocation
title: "JavaScript Function Invocation"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["calling a function", "function invocation", "invoke", "() operator", "calling vs referencing", "function call"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "invocation"]
raw_sources: ["https://www.w3schools.com/js/js_function_invocation.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Invocation]]
## 🎯 한 줄 통찰 (One-line insight)
The code inside a function does not run when the function is defined — it runs when something *invokes* it, and the `()` operator is what invokes a function. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Definition vs invocation** — code inside a function is NOT executed when the function is defined; it executes when "something" invokes the function. [S1]
- **Invoke vs call** — the term "invoke" is common because a function can be invoked without being called directly. [S1]
- **The `()` operator invokes a function** — appending parentheses to a function name runs it. [S1]
- **Calling vs referencing** — `sayHello` refers to the function itself (and returns the function); `sayHello()` refers to the function result (and returns the result). [S1]
- **Store the returned value** — when a function returns a value you can store it in a variable. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Invoke with `()`** — `sayHello()` runs the body and yields its return value; omitting `()` yields the function object instead. [S1]
- **Capture the result** — `let greeting = sayHello();` keeps the returned value for reuse. [S1]
- **Invoke on an event** — wire a function to a UI event (e.g. `onclick="showHello()"`) so it runs on interaction. [S1]
## 📖 세부 내용 (Details)
**Calling a Function** — a defined function: [S1]
```javascript
function sayHello() {
return "Hello World";
}
```
The code inside a function is **NOT executed** when the function is **defined**. The code inside a function **will execute** when "something" **invokes** the function. It is common to use the term **invoke**, because a function can be invoked without being called. [S1]
Invoke the function with `()`: [S1]
```javascript
function sayHello() {
return "Hello World";
}
sayHello();
```
**Using the Returned Value** — when a function returns a value, you can store the value in a variable: [S1]
```javascript
function sayHello() {
return "Hello World";
}
let greeting = sayHello();
```
Log the result: [S1]
```javascript
function sayHello() {
return "Hello World";
}
console.log(sayHello());
```
**Displaying the Result** — invoke a function and write its result into the page: [S1]
```javascript
<p id="demo"></p>
<script>
function sayHello() {
return "Hello World";
}
document.getElementById("demo").innerHTML = sayHello();
</script>
```
**Calling a Function Many Times** — the same function can be invoked repeatedly: [S1]
```javascript
function sayHello() {
return "Hello World";
}
let a = sayHello();
let b = sayHello();
let c = sayHello();
```
A converting function invoked with an argument: [S1]
```javascript
// Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
// Call the toCelcius() function
let value = toCelsius(77);
```
**Calling vs Referencing a Function**`() ` invokes; without it you get the function itself: [S1]
```javascript
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius;
```
```javascript
function sayHello() {
return "Hello World";
}
let text = sayHello;
```
This is an important difference: `sayHello` refers to the **function itself** (it returns the function); `sayHello()` refers to the **function result** (it returns the result). The `()` operator invokes a function. [S1]
**Functions Can Be Called from Anywhere** — define one function and invoke it from another (e.g. on a button click): [S1]
```javascript
function sayHello() {
return "Hello World";
}
function showHello() {
document.getElementById("demo").innerHTML = sayHello();
}
```
```javascript
<p id="demo"></p>
<button onclick="showHello()">Click Me</button>
<script>
function sayHello() {
return "Hello World";
}
function showHello() {
document.getElementById("demo").innerHTML = sayHello();
}
</script>
```
**Common Mistakes** — [S1]
- **Forgetting Parentheses `()`** — `sayHello` does not run the function; you must use `sayHello()`.
- **Expecting Return** — some functions do not return a value.
- **Expecting Output** — if a function returns a value, you must display it to see it.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — invoking `sayHello()`, capturing its return, logging it, writing it to `#demo`, calling it many times, and triggering `showHello()` from a button. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Invoke and capture the result (language: JavaScript):
```javascript
let greeting = sayHello();
```
Reference vs invoke:
```javascript
let text = sayHello; // the function itself
let result = sayHello(); // the function's result
```
Invoke on a UI event:
```javascript
function showHello() {
document.getElementById("demo").innerHTML = sayHello();
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Functions]], [[JavaScript Function Definitions]], [[JavaScript Function Parameters]], [[JavaScript Function Returns]]
- **참조 맥락:** Referenced whenever deciding how and when a defined function's body should actually run.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Invocation — https://www.w3schools.com/js/js_function_invocation.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Invocation" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,136 @@
---
id: javascript-function-parameters
title: "JavaScript Function Parameters"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["function parameters", "arguments", "parameters vs arguments", "default parameters", "parameter rules", "function input"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "parameters"]
raw_sources: ["https://www.w3schools.com/js/js_function_parameters.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Parameters]]
## 🎯 한 줄 통찰 (One-line insight)
Parameters are the named inputs a function declares in its parentheses; arguments are the real values passed in when it is called — and JavaScript checks neither their types nor their count. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Parameters pass values in** — parameters allow you to send values to a function and are listed inside the parentheses in the function definition. [S1]
- **Parameters vs arguments** — parameters are the names listed in the function definition; arguments are the real values passed to and received by the function. [S1]
- **No type or count enforcement** — JavaScript function definitions do not specify data types for parameters, do not perform type checking on arguments, and do not check the number of arguments received. [S1]
- **Missing arguments give wrong results** — accessing a function with an incorrect (missing) parameter can return an incorrect answer. [S1]
- **Default parameter values** — ECMAScript 2015 allows function parameters to have default values, used when no argument is provided. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **One or many parameters** — declare a single parameter, or as many as needed separated by commas. [S1]
- **Default fallback** — `function f(x, y = 10)` supplies `10` when the second argument is omitted. [S1]
- **No safety net** — because there is no type/count checking, a missing argument silently flows through (e.g. `toCelsius()` with no input). [S1]
## 📖 세부 내용 (Details)
**Parameters (Function Input)** — parameters allow you to pass (send) values to a function; they are listed inside the parentheses in the function definition. [S1]
**Functions with One Parameter** — a function can have one parameter: [S1]
```javascript
function sayHello(name) {
return "Hello " + name;
}
let greeting = sayHello("John");
```
A single-parameter conversion: [S1]
```javascript
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
let value = toCelsius(77);
```
**Functions with Multiple Parameters** — you can add as many parameters as you want, separated by commas: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
```
```javascript
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
let name = fullName("John", "Doe");
```
**Parameters vs. Arguments** — parameters are the names listed in the function definition; arguments are the real values passed to and received by the function. [S1]
**Parameter Rules** — JavaScript function definitions do not specify data types for parameters; JavaScript functions do not perform type checking on the arguments; JavaScript functions do not check the number of arguments received. [S1]
**Incorrect Parameters** — accessing a function with an incorrect (missing) parameter can return an incorrect answer: [S1]
```javascript
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius();
```
**Default Parameter Values** — ECMAScript 2015 allows function parameters to have default values; the default value is used if no argument is provided: [S1]
```javascript
function myFunction(x, y = 10) {
return x + y;
}
myFunction(5);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — single-parameter `sayHello(name)` and `toCelsius(fahrenheit)`, multi-parameter `multiply(a, b)` and `fullName(firstName, lastName)`, the missing-argument `toCelsius()` case, and the default-parameter `myFunction(x, y = 10)`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Multiple parameters (language: JavaScript):
```javascript
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
let name = fullName("John", "Doe");
```
Default parameter value:
```javascript
function myFunction(x, y = 10) {
return x + y;
}
myFunction(5);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Functions]], [[JavaScript Function Definitions]], [[JavaScript Function Invocation]], [[JavaScript Function Returns]]
- **참조 맥락:** Referenced when designing a function's inputs, defaults, and how callers supply arguments.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Parameters — https://www.w3schools.com/js/js_function_parameters.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Parameters" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,171 @@
---
id: javascript-function-returns
title: "JavaScript Function Returns"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["function return", "return statement", "return value", "returning values", "undefined return", "early return"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions", "return"]
raw_sources: ["https://www.w3schools.com/js/js_function_return.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Function Returns]]
## 🎯 한 줄 통찰 (One-line insight)
The `return` statement sends a value out of a function back to its caller and stops the function's execution — and a function with no `return` yields `undefined`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Return sends a value out** — a function can return a value back to the code that called it using the `return` statement. [S1]
- **Return stops execution** — when a function reaches a `return` statement, the function stops executing and the value after `return` is sent back to the caller. [S1]
- **Any type can be returned** — a function can return any type of value, not only numbers. [S1]
- **Returned values fit into expressions** — the returned value can be used anywhere a value is expected, including inside another expression. [S1]
- **No return → undefined** — if a function does not return a value, the return value is `undefined`. [S1]
- **Early return** — `return` can stop a function early based on a condition. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Calculate and return** — most functions return the result of a calculation or operation. [S1]
- **Inline the call** — use a function call directly inside an expression (`multiply(2, 3) * 10`). [S1]
- **Guard clause** — return early when a condition is met (`if (age < 18) return "Too young";`). [S1]
## 📖 세부 내용 (Details)
**JavaScript Function Return** — a function can return a value back to the code that called it. The `return` statement is used to send a value out of a function. [S1]
```javascript
function sayHello() {
return "Hello World";
}
let message = sayHello();
```
**The `return` Statement / Returning a Calculated Value** — most functions return the result of a calculation or operation. When a function reaches a `return` statement, the function stops executing and the value after the `return` keyword is sent back to the caller: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
```
**Using Return Values in Expressions** — the returned value can be used anywhere a value is expected; a function call can be used inside another expression: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
let total = multiply(2, 3) * 10;
```
**Return Values** — a function can return any type of value (not only numbers): [S1]
```javascript
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
let name = fullName("John", "Doe");
```
**Return Statements Stop Execution** — code written after a `return` statement will NOT be executed: [S1]
```javascript
function multiply(a, b) {
return "Done";
// Next line will never run
return a * b;
}
let result = multiply(4, 3);
```
**Functions Without return** — if a function does not return a value, the return value will be `undefined`: [S1]
```javascript
function multiply(a, b) {
let x = a * b;
}
let result = multiply(4, 3);
```
**Returning Values Early** — you can use `return` to stop a function early, based on a condition: [S1]
```javascript
function checkAge(age) {
if (age < 18) {
return "Too young";
}
return "Access granted";
}
```
**Returning Values to HTML** — returned function values are often used to update HTML content: [S1]
```javascript
<p id="demo"></p>
<script>
function toCelsius(farenheit) {
return (5 / 9) * (farenheit - 32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>
```
**Common Mistakes** — [S1]
- **Forgetting Return** — a function without `return` sends back `undefined`.
- **Expecting Code after Return to Run** — code after `return` is ignored.
- **Confusing `console.log()` with Return** — `console.log()` shows output but does not return a value.
- **Expecting Return** — if your function does not return a value, storing it in a variable will give `undefined`.
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `sayHello()`, the calculating `multiply(a, b)`, inlining `multiply(2, 3) * 10`, the string-returning `fullName(...)`, the unreachable-code case, the no-return `undefined` case, the early-return `checkAge(age)`, and writing `toCelsius(77)` into `#demo`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Return a calculated value (language: JavaScript):
```javascript
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
```
Use a return value inside an expression:
```javascript
let total = multiply(2, 3) * 10;
```
Return early as a guard:
```javascript
function checkAge(age) {
if (age < 18) {
return "Too young";
}
return "Access granted";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Functions]], [[JavaScript Function Definitions]], [[JavaScript Function Invocation]], [[JavaScript Function Parameters]]
- **참조 맥락:** Referenced when deciding what value a function hands back and how that result is consumed.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Function Returns — https://www.w3schools.com/js/js_function_return.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Function Returns" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,152 @@
---
id: javascript-functions
title: "JavaScript Functions"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["functions", "function declaration", "reusable code blocks", "function syntax", "local variables", "functions as variables"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "functions"]
raw_sources: ["https://www.w3schools.com/js/js_functions.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Functions]]
## 🎯 한 줄 통찰 (One-line insight)
A JavaScript function is a reusable block of code designed for a particular task that runs only when it is called — write it once, run it many times. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Functions are reusable code blocks** designed to perform a particular task; they execute when they are called or invoked. [S1]
- **Why use functions** — to reuse code (write once, run many times) and to organize code into manageable sections. [S1]
- **Declaration syntax** — the `function` keyword, a name, a parenthesized parameter list, and a body in curly braces. [S1]
- **Functions run when called** — the code inside runs only when something invokes the function with `()`. [S1]
- **Local variables** — variables declared inside a function can only be accessed from within it; they are created when the function starts and deleted when it completes. [S1]
- **Functions used as variables** — a function call can be used anywhere a value is expected, including inside string concatenation. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Define → call** — declare a named function, then invoke it by name with parentheses to run its body. [S1]
- **Parameterize for reuse** — accept parameters so the same function works on different inputs (`add(5, 5)`, `add(50, 50)`). [S1]
- **Call as a value** — substitute a function call directly into an expression instead of storing it first. [S1]
## 📖 세부 내용 (Details)
**Functions are Code Blocks** — functions are reusable code blocks designed to perform a particular task; they execute when they are called or invoked. [S1]
**Why Use Functions?** — functions let you reuse code (write once, run many times) and organize code into manageable sections. [S1]
**JavaScript Function Syntax** — a function is defined with the `function` keyword, a name, parameters in parentheses, and a body in curly braces: [S1]
```javascript
function name( p1, p2, ... ) {
// code to be executed
}
```
**What Does a Function Look Like?** — a basic function declaration: [S1]
```javascript
function sayHello() {
return "Hello World";
}
```
**Functions Run When You Call Them** — the function body runs when it is invoked, and its returned value can be stored: [S1]
```javascript
function sayHello() {
return "Hello World";
}
let message = sayHello();
```
A function with parameters: [S1]
```javascript
function multiply(a, b) {
return a * b;
}
```
**A Function Can Be Used Many Times** — the same definition is reused with different arguments: [S1]
```javascript
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
```
**Local Variables** — variables declared inside a function can only be accessed from within the function; they are created when the function starts and deleted when it completes: [S1]
```javascript
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
```
**Functions Used as Variables** — a function call can be used directly inside an expression: [S1]
```javascript
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
```
And the call can be inlined directly: [S1]
```javascript
let text = "The temperature is " + toCelsius(77) + " Celsius";
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `sayHello()`, `multiply(a, b)`, the reusable `add(a, b)`, the local-variable `myFunction()`, and the `toCelsius(77)` usage inside a string. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Declare and call a function (language: JavaScript):
```javascript
function sayHello() {
return "Hello World";
}
let message = sayHello();
```
Reuse with parameters:
```javascript
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
```
Use a function call as a value:
```javascript
let text = "The temperature is " + toCelsius(77) + " Celsius";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Function Definitions]], [[JavaScript Function Invocation]], [[JavaScript Function Parameters]], [[JavaScript Function Returns]]
- **참조 맥락:** The entry point referenced whenever packaging reusable behavior into named, callable blocks.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Functions — https://www.w3schools.com/js/js_functions.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,111 @@
---
id: javascript-generators
title: "JavaScript Generators"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS generators", "function*", "yield", "generator object", "generator function"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "generators", "yield", "iterators"]
raw_sources: ["https://www.w3schools.com/js/js_generators.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Generators]]
## 🎯 한 줄 통찰 (One-line insight)
A JavaScript generator, declared with `function*`, can return multiple values one by one and can be paused and resumed using the `yield` keyword, returning a Generator Object that follows both the iterable and iterator protocols. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`function*` defines a generator** — generator functions use the `function*` syntax and, when invoked, return a Generator Object rather than a single value. [S1]
- **Returns multiple values, one by one** — a generator can return (yield) a stream of multiple values, one at a time. [S1]
- **Pausable and resumable** — generators can be paused and resumed; the `yield` keyword pauses execution and yields a value back to the caller while preserving internal state. [S1]
- **Both iterable and iterator** — Generator Objects follow both the iterable and iterator protocols, so they work with `for...of` loops. [S1]
- **`next()` shape** — calling `next()` returns an object of the form `{value: value, done: true|false}`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Yield a sequence** — use multiple `yield` statements inside a `function*` to emit values one at a time on each `next()` call. [S1]
- **`yield` vs `return`** — `yield` produces a value and pauses; `return` ends the generator. [S1]
- **Consume with `for...of`** — because a generator is iterable, you can loop over its yielded values directly. [S1]
## 📖 세부 내용 (Details)
**JavaScript Generators**
Generators are functions that can return multiple values, one by one. A JavaScript Generator can yield a stream of data. Generators can be paused and resumed. [S1]
**Generator Functions**
Generator functions are defined with the `function*` syntax. When called, a generator function does not run its body immediately — instead it returns a Generator Object structured as `{value:1, done:false}`. [S1]
**Example — a generator with `yield` and `return`** [S1]
```javascript
function* myStream() {
yield 1;
yield 2;
return 3;
}
let myGenerator = myStream();
for (let value of myGenerator) { }
```
**The `yield` Keyword**
The `yield` keyword pauses execution and yields a value back to the caller. Generators maintain their internal state between `yield` calls, enabling resumption from the previous stopping point. [S1]
**Generator Object Methods** [S1]
| Method | Description |
|--------|-------------|
| `next()` | Resumes execution of the generator function |
| `return()` | Finishes execution and returns the given value |
| `throw()` | Throws an exception in execution |
The `next()` method resumes execution of the generator function and returns `{ value: value, done: true|false}`. [S1]
**Use Cases**
Generators simplify creating custom iterators for complex data structures, enable efficient on-demand value generation including potentially infinite data streams, and historically were used to manage asynchronous operations before `async/await` became standard. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's `myStream` generator (two `yield`s and a `return`, consumed via `for...of`) is the canonical applied example. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Define and consume a generator (language: JavaScript):
```javascript
function* myStream() {
yield 1;
yield 2;
return 3;
}
let myGenerator = myStream();
for (let value of myGenerator) { }
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
The page notes that generators were historically used to manage asynchronous operations before `async/await` became the standard approach. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Iterators]], [[JavaScript Iterables]], [[JavaScript Symbols]]
- **참조 맥락:** Referenced when building custom iterators or producing lazy/on-demand value streams.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Generators — https://www.w3schools.com/js/js_generators.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Generators" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,90 @@
---
id: javascript-html-dom
title: "JavaScript HTML DOM"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["HTML DOM", "Document Object Model", "DOM tree", "DOM nodes", "HTML Document Object Model"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "dom"]
raw_sources: ["https://www.w3schools.com/js/js_htmldom.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript HTML DOM]]
## 🎯 한 줄 통찰 (One-line insight)
The HTML DOM is an object model that represents an HTML page as a tree of nodes, giving JavaScript a standardized way to access and change every element on the page. [S1]
## 🧠 핵심 개념 (Core concepts)
- **The HTML DOM is an Object Model for HTML Documents** — it represents an HTML page as a tree of nodes. [S1]
- **The browser builds the tree on load** — when a webpage loads, the browser creates a tree-like representation of the document made of nodes: Document, Element nodes (such as `<html>`, `<body>`, `<a>`), Attribute nodes, and Text nodes. [S1]
- **Three roles in one access expression** — `id="demo"` is an HTML property, `getElementById()` is a DOM method, and `innerHTML` is a DOM property. [S1]
- **The DOM is a W3C Standard** — defined by the World Wide Web Consortium in three parts: Core DOM, XML DOM, and HTML DOM. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Access then modify** — get a node reference with a DOM method, then read or write a DOM property on it. [S1]
- **Tree traversal mindset** — because the page is a tree of nodes, navigation and manipulation are expressed in terms of elements, attributes, and text nodes. [S1]
## 📖 세부 내용 (Details)
**The HTML DOM** [S1]
The HTML DOM (HTML Document Object Model) is an Object Model for HTML Documents. It represents an HTML page as a tree of nodes. [S1]
**The DOM Tree** [S1]
When a webpage loads, the browser creates a tree-like representation of the document. This tree is made of nodes for the different parts of the document: the Document node, Element nodes (for example `<html>`, `<body>`, `<a>`), Attribute nodes, and Text nodes. [S1]
**Accessing HTML Elements** [S1]
HTML elements are accessed through the document. The following example accesses a paragraph element by its id and changes its content: [S1]
```javascript
// Access a paragraph Element
const myPara = document.getElementById("demo");
// Change the content of the Element
myPara.innerHTML = "Hello World!";
```
In this example, `id="demo"` is an HTML property, `getElementById()` is a DOM method, and `innerHTML` is a DOM property. [S1]
**What You Will Learn** [S1]
The tutorial covers how to: change the content of HTML elements, change the style (CSS) of HTML elements, add and delete HTML elements, and react to HTML events. [S1]
**The World Wide Web Consortium** [S1]
The DOM is a W3C Standard (World Wide Web Consortium). The W3C DOM standard is separated into three parts: Core DOM, XML DOM, and HTML DOM. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippet — selecting `#demo` with `getElementById()` and assigning to `innerHTML` — is the canonical applied example. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Access an element by id and change its content (language: JavaScript):
```javascript
const myPara = document.getElementById("demo");
myPara.innerHTML = "Hello World!";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript DOM Methods]], [[JavaScript DOM Elements]], [[JavaScript DOM Changing HTML]], [[JavaScript Introduction]]
- **참조 맥락:** The foundational model referenced by every DOM manipulation, styling, and event topic.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript HTML DOM — https://www.w3schools.com/js/js_htmldom.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript HTML DOM" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,127 @@
---
id: javascript-hoisting
title: "JavaScript Hoisting"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["hoisting", "variable hoisting", "temporal dead zone", "declaration hoisting", "var hoisting"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "hoisting", "var", "let", "const", "scope"]
raw_sources: ["https://www.w3schools.com/js/js_hoisting.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Hoisting]]
## 🎯 한 줄 통찰 (One-line insight)
Hoisting is JavaScript's default behavior of moving all *declarations* (not initializations) to the top of the current scope — so a `var` can be used before it is declared, but `let`/`const` cannot. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Hoisting moves declarations up** — JavaScript moves all declarations to the top of the current scope (the top of the current script or the current function). [S1]
- **`var` is hoisted and usable early** — a `var` variable can be referenced before its declaration line without error. [S1]
- **`let` and `const` are hoisted but not initialized** — using them before declaration throws a `ReferenceError` because of the "temporal dead zone"; using `const` before declaration is a syntax error. [S1]
- **Only declarations hoist, not initializations** — the assignment (`= value`) stays where it is written, so an early-referenced variable reads as `undefined`. [S1]
- **Best practice** — always declare all variables at the beginning of every scope; strict mode does not allow undeclared variables. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Declare at the top of scope** — to avoid hoisting-related bugs, put all declarations first. [S1]
- **Never rely on `let`/`const` before declaration** — they live in the temporal dead zone until their declaration line runs. [S1]
- **Remember: declaration ≠ initialization** — an early read returns `undefined`, not the assigned value. [S1]
## 📖 세부 내용 (Details)
**What is Hoisting?**
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). [S1]
**`var` Declarations are Hoisted**
A variable can be used before it has been declared. The following example gives the same result as declaring `x` first: [S1]
```javascript
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
```
This is equivalent to: [S1]
```javascript
var x; // Declare x
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
```
**`let` and `const` Hoisting**
Variables defined with `let` and `const` are hoisted to the top of the block, but they are *not* initialized. Using a `let` variable before it is declared results in a `ReferenceError`: [S1]
```javascript
carName = "Volvo";
let carName;
```
Using a `const` variable before it is declared is a syntax error, so the code will not run: [S1]
```javascript
carName = "Volvo";
const carName;
```
**JavaScript Initializations are Not Hoisted**
JavaScript hoists *declarations*, not *initializations*. Because only the declaration of `y` is hoisted (and not its assignment), `y` is `undefined` when it is first used: [S1]
```javascript
var x = 5; // Initialize x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
var y = 7; // Initialize y
```
**Declare Your Variables At the Top**
To avoid bugs, always declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is a good rule. JavaScript in strict mode does not allow variables to be used if they are not declared. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's examples are the applied cases: showing `var x` usable before its declaration line, the `let`/`const` `ReferenceError`/syntax-error cases, and the `y` value reading as `undefined` because its initialization did not hoist. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
`var` is hoisted (usable before declaration) (language: JavaScript):
```javascript
x = 5;
var x; // Declaration hoisted to top of scope
```
`let` before declaration throws:
```javascript
carName = "Volvo";
let carName; // ReferenceError
```
Initialization is not hoisted (reads undefined):
```javascript
elem.innerHTML = x + " " + y; // y is undefined here
var y = 7;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript var let const]], [[JavaScript Scope]], [[JavaScript Strict Mode]], [[JavaScript Code Blocks]]
- **참조 맥락:** Explains why variable order matters and motivates declaring variables at the top of each scope.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Hoisting — https://www.w3schools.com/js/js_hoisting.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Hoisting" page (Astra wiki-curation, P-Reinforce v3.1 format).
+142
View File
@@ -0,0 +1,142 @@
---
id: javascript-if
title: "JavaScript If"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS if statement", "if statement", "nested if", "conditional execution", "logical AND in if", "if syntax"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "if", "control-flow"]
raw_sources: ["https://www.w3schools.com/js/js_if.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript If]]
## 🎯 한 줄 통찰 (One-line insight)
Use the JavaScript `if` statement to execute a block of code when a condition is `true` — and `if` must be lowercase, since `If`/`IF` raise an error. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`if` runs code when true** — use the `if` statement to execute a block of code when a condition is `true`. [S1]
- **Lowercase only** — `if` must be in lowercase; uppercase `If` or `IF` will generate a JavaScript error. [S1]
- **Braced block** — the code to run conditionally goes inside `{ ... }` after the parenthesized condition. [S1]
- **Nesting works but adds complexity** — `if` statements can be nested, but nesting makes code more complex. [S1]
- **Prefer logical AND over nesting** — a better solution than nesting two `if`s is to combine conditions with the logical AND operator `&&`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Default-then-override** — set a default value, then override it inside an `if` when the condition holds. [S1]
- **Flatten nesting with `&&`** — replace `if (A) { if (B) {...} }` with `if (A && B) {...}`. [S1]
## 📖 세부 내용 (Details)
**The JavaScript if Statement** [S1]
Use the JavaScript `if` statement to execute a block of code when a condition is `true`.
**Syntax** [S1]
```
if (condition) {
// block of code to be executed if the condition is true
}
```
**Note** [S1]
Note that `if` is in lowercase letters. Uppercase letters (`If` or `IF`) will generate a JavaScript error.
A basic `if` setting a greeting: [S1]
```javascript
if (hour < 18) {
greeting = "Good day";
}
```
A default-then-override example where the condition is true: [S1]
```javascript
let age = 18;
let text = "You can Not drive";
if (age >= 18) {
text = "You can drive";
}
```
The same pattern where the condition is false (the default is kept): [S1]
```javascript
let age = 16;
let text = "You can Not drive";
if (age >= 18) {
text = "You can drive";
}
```
**Nested if** [S1]
Nested if statements can make your code more complex:
```javascript
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA") {
if (age >= 16) {
text = "You can drive!";
}
}
```
A better solution is to use the logical AND operator:
```javascript
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA" && age >= 16) {
text = "You can drive!";
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — greeting based on `hour`, a driving-eligibility check with default-then-override, and flattening a nested `if` into a single `&&` condition. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Default then override on a true condition:
```javascript
let age = 18;
let text = "You can Not drive";
if (age >= 18) {
text = "You can drive";
}
```
Combine conditions with logical AND instead of nesting:
```javascript
if (country == "USA" && age >= 16) {
text = "You can drive!";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript If Else]], [[JavaScript Conditional Operators]], [[JavaScript Comparisons]], [[JavaScript Operators]]
- **참조 맥락:** The foundational branching statement, referenced before adding `else`/`else if` or a `switch`.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript If — https://www.w3schools.com/js/js_if.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript If" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,138 @@
---
id: javascript-if-else
title: "JavaScript If Else"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS if else", "else statement", "else if statement", "if else if chain", "if else syntax", "branching"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "if-else", "control-flow"]
raw_sources: ["https://www.w3schools.com/js/js_if_else.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript If Else]]
## 🎯 한 줄 통찰 (One-line insight)
Use `else` to run a block when the condition is `false`, and `else if` to test a new condition when the first is `false`, forming a multi-branch decision chain. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`else` handles the false case** — use the `else` statement to specify a block of code to be executed if a condition is `false`. [S1]
- **`else if` chains a new test** — use the `else if` statement to specify a new condition if the first is `false`. [S1]
- **First-true-wins** — in an `if / else if / else` chain, the first branch whose condition is `true` runs, and the trailing `else` is the fallback when all conditions are `false`. [S1]
- **Builds on `if`** — `else` and `else if` extend the basic `if` statement rather than replacing it. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Two-way branch** — `if (...) { ... } else { ... }` to pick exactly one of two blocks. [S1]
- **Multi-way ladder** — chain `else if` for graduated thresholds (e.g. time-of-day greeting). [S1]
- **Branch then render** — compute a value in branches, then write it to the DOM (`innerHTML`). [S1]
## 📖 세부 내용 (Details)
**The else Statement** [S1]
Use the `else` statement to specify a block of code to be executed if a condition is `false`.
Syntax: [S1]
```
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
```
Example — time-of-day greeting: [S1]
```javascript
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
```
**The else if Statement** [S1]
Use the `else if` statement to specify a new condition if the first is `false`.
Syntax: [S1]
```
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
```
Example — three-way greeting: [S1]
```javascript
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
```
Example — branch then render to the page: [S1]
```javascript
let text;
if (Math.random() < 0.5) {
text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — a two-way greeting, a three-way `else if` greeting ladder, and a random-link example that branches then writes the result into `#demo` via `innerHTML`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Two-way branch:
```javascript
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
```
Multi-way ladder with `else if`:
```javascript
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript If]], [[JavaScript Conditional Operators]], [[JavaScript Comparisons]], [[JavaScript Introduction]]
- **참조 맥락:** Referenced whenever a decision needs more than a single true-only branch.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript If Else — https://www.w3schools.com/js/js_if_else.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript If Else" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,120 @@
---
id: javascript-introduction
title: "JavaScript Introduction"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JavaScript", "JS", "JS intro", "ECMAScript", "client-side scripting"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools"]
raw_sources: ["https://www.w3schools.com/js/js_intro.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Introduction]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript is the programming language of the web — it programs the *behavior* of web pages, able to read and dynamically change both HTML content and CSS styles. [S1]
## 🧠 핵심 개념 (Core concepts)
- **JavaScript is the programming language of the web** — it lets you calculate, manipulate, and validate data, and update/change both HTML and CSS. [S1]
- **The three web layers** — HTML defines the content, CSS specifies the layout, and JavaScript programs the behavior. [S1]
- **The DOM entry point** — JavaScript reaches HTML elements through the document, most commonly with `document.getElementById()`, then reads/writes their content, attributes, and style. [S1]
- **Quotes are interchangeable** — JavaScript accepts both single `'` and double `"` quotes for strings. [S1]
- **Standardized** — JavaScript became an ECMA standard in 1997; the official standard is ECMA-262 and the official language name is ECMAScript. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Select → mutate pattern** — get a reference to an element (`document.getElementById("id")`), then assign to a property (`.innerHTML`, `.style.*`, an attribute) to change the page. [S1]
- **Style via `.style` object** — CSS properties are set in JS using camelCase property names on `element.style` (e.g. `fontSize`, not `font-size`). [S1]
- **Show/hide via display** — toggling `style.display` between `"none"` and `"block"` hides or reveals an element. [S1]
## 📖 세부 내용 (Details)
**What is JavaScript?**
JavaScript is the programming language of the web. It can calculate, manipulate, and validate data, and it can update and change both HTML and CSS. [S1]
**JavaScript, HTML and CSS**
The three layers of standard web technology: HTML to define the content of web pages, CSS to specify the layout of web pages, and JavaScript to program the behavior of web pages. [S1]
**JavaScript Can Change HTML Content**
One of many JavaScript HTML methods is `getElementById()`. It finds an HTML element (by id) and changes the element content (`innerHTML`): [S1]
```javascript
document.getElementById("demo").innerHTML = "Hello JavaScript";
```
JavaScript accepts both double and single quotes:
```javascript
document.getElementById('demo').innerHTML = 'Hello JavaScript';
```
**JavaScript Can Change HTML Attribute Values**
JavaScript can change attribute values dynamically — for example, changing the `src` (source) attribute of an `<img>` tag in response to user interaction (e.g. a light bulb turning on/off). [S1]
**JavaScript Can Change HTML Styles (CSS)**
Changing the style of an HTML element is a variant of changing an HTML attribute: [S1]
```javascript
document.getElementById("demo").style.fontSize = "35px";
```
**JavaScript Can Hide HTML Elements**
Hiding HTML elements can be done by changing the `display` style: [S1]
```javascript
document.getElementById("demo").style.display = "none";
```
**JavaScript Can Show HTML Elements**
Showing hidden HTML elements can also be done by changing the `display` style: [S1]
```javascript
document.getElementById("demo").style.display = "block";
```
**Why study JavaScript?**
JavaScript is one of the three languages all web developers must learn, alongside HTML and CSS. [S1]
**History**
JavaScript was invented by Brendan Eich in 1995 and became an ECMA standard in 1997. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — selecting `#demo` and mutating its `innerHTML`, `style.fontSize`, and `style.display`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Select an element and change its content (language: JavaScript):
```javascript
document.getElementById("demo").innerHTML = "Hello JavaScript";
```
Change a style:
```javascript
document.getElementById("demo").style.fontSize = "35px";
```
Hide / show:
```javascript
document.getElementById("demo").style.display = "none";
document.getElementById("demo").style.display = "block";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Where To]], [[JavaScript Output]], [[JavaScript HTML DOM]], [[HTML JavaScript]]
- **참조 맥락:** The entry point referenced whenever adding interactive behavior to an HTML/CSS page.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Introduction — https://www.w3schools.com/js/js_intro.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Introduction" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,145 @@
---
id: javascript-iterables
title: "JavaScript Iterables"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS iterables", "iterable protocol", "for...of", "Symbol.iterator", "iterable objects"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "iterables", "for-of", "symbol-iterator"]
raw_sources: ["https://www.w3schools.com/js/js_iterables.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Iterables]]
## 🎯 한 줄 통찰 (One-line insight)
Iterables are objects that can be looped over with the `for...of` statement; in JavaScript, Strings, Arrays, Typed Arrays, Sets, and Maps are all iterable because their prototypes carry a `Symbol.iterator` method. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Iterable = loopable with `for...of`** — an iterable is an object that can be iterated (looped) over with the `for...of` statement. [S1]
- **Built-in iterables** — in JavaScript the following are iterables: Strings, Arrays, Typed Arrays, Sets, and Maps, because their prototypes have a `Symbol.iterator` method. [S1]
- **The iterator protocol** — an object becomes an iterator by implementing a `next()` method that returns an object with `value` (the next value) and `done` (a boolean indicating completion). [S1]
- **`Symbol.iterator` is the hook** — an object is made iterable by defining a `Symbol.iterator` method that returns an iterator. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`for...of` over any iterable** — the same `for (variable of iterable)` loop works uniformly across strings, arrays, sets, and maps. [S1]
- **Custom iterable via `Symbol.iterator`** — attach a `Symbol.iterator` function to a plain object so it can be used in `for...of`, giving you custom iteration logic for your own data structures. [S1]
## 📖 세부 내용 (Details)
**Iterables**
Iterables are iterable objects (like Arrays). Iterables can be accessed with simple and efficient code. Iterables can be iterated over with `for...of` loops. [S1]
**The `for...of` Loop**
The `for...of` statement loops through the elements of an iterable object. Its syntax is: [S1]
```javascript
for (variable of iterable) {
// code block to be executed
}
```
**Iterating over a String**
You can use a `for...of` loop to iterate over the elements of a string: [S1]
```javascript
const name = "W3Schools";
for (const x of name) {
// code block to be executed
}
```
**Iterating over an Array**
You can use a `for...of` loop to iterate over the elements of an array: [S1]
```javascript
const letters = ["a","b","c"];
for (const x of letters) {
// code block to be executed
}
```
**Iterating over Sets and Maps**
`for...of` can also iterate over the elements of a Set and over the key/value pairs of a Map. [S1]
**JavaScript Iterators**
The `for...of` loop relies on an iterator. The iterable must implement a method named `Symbol.iterator`. The `Symbol.iterator` method is called automatically by `for...of`. It returns an iterator object with a `next()` method. The `next()` method returns an object with a `value` property (the next value) and a `done` property (`true` or `false`). [S1]
**Built-in Iterables**
In JavaScript the following are iterables: Strings, Arrays, Typed Arrays, Sets, and Maps. They are iterable because their prototype objects all have a `Symbol.iterator` method. [S1]
**A User-Defined (Home-Made) Iterable**
You can make an object iterable by giving it a `Symbol.iterator` method. The example below creates an object that returns values 10, 20, 30, 40 ... and stops at 100: [S1]
```javascript
myNumbers = {};
myNumbers[Symbol.iterator] = function() {
let n = 0;
done = false;
return {
next() {
n += 10;
if (n == 100) {done = true}
return {value:n, done:done};
}
};
}
for (const num of myNumbers) {
// Any Code Here
}
```
The `next()` method returns an object with two properties: `value` (the next value) and `done` (`true` when iteration is finished). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — looping over the string `"W3Schools"`, the array `["a","b","c"]`, and the home-made `myNumbers` iterable built with `Symbol.iterator`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Loop over any iterable (language: JavaScript):
```javascript
for (const x of "W3Schools") {
// code block to be executed
}
```
Make a plain object iterable:
```javascript
myNumbers[Symbol.iterator] = function() {
let n = 0;
done = false;
return {
next() {
n += 10;
if (n == 100) {done = true}
return {value:n, done:done};
}
};
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Iterators]], [[JavaScript Generators]], [[JavaScript Symbols]]
- **참조 맥락:** Referenced whenever using `for...of` loops or building custom data structures that should be loopable.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Iterables — https://www.w3schools.com/js/js_iterables.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Iterables" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,170 @@
---
id: javascript-iterators
title: "JavaScript Iterators"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS iterators", "iterator protocol", "next()", "Iterator helpers", "Iterator.from"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.87
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "iterators", "iterator-helpers", "es2025"]
raw_sources: ["https://www.w3schools.com/js/js_iterators.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Iterators]]
## 🎯 한 줄 통찰 (One-line insight)
An iterator is an object that provides a standard way to access elements sequentially through a `next()` method; ES2025 adds iterator helper methods (`map`, `filter`, `reduce`, `take`, `drop`, etc.) and `Iterator.from()` that bring iteration directly into the core language. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Iterator = sequential access object** — an iterator is an object that provides a standard way to access elements one after another. [S1]
- **The iterator protocol** — an iterator must implement a `next()` method that returns an object with `value` (the next value) and `done` (`false` while more elements exist, otherwise `true`). [S1]
- **`for...of` consumes iterables** — the `for...of` statement loops through the elements of an iterable object; iterables must implement `Symbol.iterator`. Built-in iterables are Strings, Arrays, Typed Arrays, Sets, and Maps. [S1]
- **Iterator helper methods (ES2025)** — new helpers let you transform and consume iterators lazily: `drop`, `every`, `filter`, `find`, `flatMap`, `forEach`, `from`, `map`, `reduce`, `some`, `take`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`Iterator.from(iterable)`** — wrap any iterable into an iterator object so the helper methods become available. [S1]
- **Lazy chaining** — methods like `filter`, `map`, `take`, and `drop` return a new iterator (not an array), enabling pipeline-style transformation of sequences. [S1]
- **Terminal reducers** — `every`, `some`, `find`, `reduce`, and `forEach` consume the iterator to produce a single value or side effect. [S1]
## 📖 세부 내용 (Details)
**JavaScript Iterators**
An iterator is an object that provides a standard way to access elements sequentially. Iterators must adhere to the iterator protocol by implementing a `next()` method. [S1]
**The `next()` Method**
The `next()` method returns an object with two properties: `value` holds the next value in the iteration sequence, and `done` returns `false` if there are more elements, otherwise `true`. [S1]
**The `for...of` Loop**
The JavaScript `for...of` statement loops through the elements of an iterable object. Iterables must implement the `Symbol.iterator` method. In JavaScript the following are iterables: Strings, Arrays, Typed Arrays, Sets, and Maps — their prototypes have a `Symbol.iterator` method. [S1]
**`Iterator.from()`** — creates an iterator object from an iterable: [S1]
```javascript
const myIterator = Iterator.from([1, 2, 3]);
let text = "";
for (const x of myIterator) {
text += x;
}
```
**`drop()`** — returns an iterator that skips a specified number of elements before yielding the rest: [S1]
```javascript
const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]);
const firstFive = myIterator.drop(5);
```
**`every()`** — returns `true` if all elements satisfy a test function: [S1]
```javascript
const myIterator = Iterator.from("123456789");
let result = myIterator.every(x => x > 7);
```
**`filter()`** — returns an iterator containing elements that satisfy a filter function: [S1]
```javascript
const myIterator = Iterator.from([32, 33, 16, 40]);
const filteredIterator = myIterator.filter(x => x > 18);
```
**`find()`** — returns the first element that satisfies a test function: [S1]
```javascript
const myIterator = Iterator.from([3, 10, 18, 30, 20]);
let result = myIterator.find(x => x > 18);
```
**`flatMap()`** — returns an iterator by mapping each element and then flattening the results: [S1]
```javascript
const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]);
const mappedIterator = myIterator.flatMap(x => [x, x * 10]);
```
**`forEach()`** — executes a function once for each element in the iterator: [S1]
```javascript
const myIterator = Iterator.from("123456789");
let text = "";
myIterator.forEach (x => text += x);
```
**`map()`** — returns an iterator with all elements transformed by a map function: [S1]
```javascript
const myIterator = Iterator.from("123456789");
const mappedIterator = myIterator.map(x => x * 2);
```
**`reduce()`** — applies a reducer function against each element to reduce it to a single value: [S1]
```javascript
const myIterator = Iterator.from([175, 50, 25]);
let result = myIterator.reduce(myFunc);
```
**`some()`** — returns `true` if at least one element satisfies a test function: [S1]
```javascript
const myIterator = Iterator.from("123456789");
let result = myIterator.some(x => x > 7);
```
**`take()`** — returns an iterator that yields a specified number of elements: [S1]
```javascript
const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]);
const firstFive = myIterator.take(5);
```
**Iterator Helper Methods (ES2025)** [S1]
| Function | Description |
|----------|-------------|
| `drop()` | Returns an iterator that skips a specified number of elements before yielding the rest |
| `every()` | Returns `true` if all elements satisfy a test function |
| `filter()` | Returns an iterator containing elements that satisfy a filter function |
| `find()` | Returns the first element that satisfies a test function |
| `flatMap()` | Returns an iterator by mapping each element and then flattening the results |
| `forEach()` | Executes a function once for each element in the iterator |
| `from()` | Creates an iterator object from an iterable |
| `map()` | Returns an iterator with all elements transformed by a map function |
| `reduce()` | Applies a reducer function against each element to reduce it to a single value |
| `some()` | Returns `true` if at least one element satisfies a test function |
| `take()` | Returns an iterator that yields a specified number of elements |
Iterators bring the iteration concept directly into the core JavaScript language and provide a mechanism for customizing the behavior of `for...of`. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own `Iterator.from(...)` snippets are the canonical applied examples — wrapping arrays and strings into iterators and applying `filter`, `map`, `reduce`, `take`, `drop`, and the predicate helpers. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Wrap an iterable, then transform it (language: JavaScript):
```javascript
const myIterator = Iterator.from([32, 33, 16, 40]);
const filteredIterator = myIterator.filter(x => x > 18);
```
Reduce to a single value:
```javascript
const myIterator = Iterator.from([175, 50, 25]);
let result = myIterator.reduce(myFunc);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
The iterator helper methods (`map`, `filter`, `reduce`, `take`, `drop`, etc.) and `Iterator.from()` are an ES2025 addition; availability depends on the runtime supporting that version. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.87
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Iterables]], [[JavaScript Generators]], [[JavaScript Symbols]]
- **참조 맥락:** Referenced when consuming sequences with `for...of` or composing lazy data pipelines with the ES2025 iterator helpers.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Iterators — https://www.w3schools.com/js/js_iterators.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Iterators" page (Astra wiki-curation, P-Reinforce v3.1 format).
+157
View File
@@ -0,0 +1,157 @@
---
id: javascript-json
title: "JavaScript JSON"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON", "JavaScript Object Notation", "JSON intro", "JS JSON", "data interchange format"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json"]
raw_sources: ["https://www.w3schools.com/js/js_json.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript JSON]]
## 🎯 한 줄 통찰 (One-line insight)
JSON (JavaScript Object Notation) is a plain text, language-independent format for storing and transporting data, syntactically identical to JavaScript object code so a JS program can convert it to native objects with no complicated parsing. [S1]
## 🧠 핵심 개념 (Core concepts)
- **JSON = JavaScript Object Notation** — a plain text format for storing and transporting data, used to send, receive and store data. [S1]
- **Language independent** — JSON is text only; although its syntax is derived from JavaScript object syntax, code for reading and generating JSON can be written in any programming language. [S1]
- **Syntactically identical to JS objects** — because the JSON format matches JavaScript object creation, a JavaScript program can easily convert JSON data into native JavaScript objects. [S1]
- **Two built-in functions** — `JSON.parse()` converts JSON strings into JavaScript objects; `JSON.stringify()` converts an object into a JSON string. [S1]
- **Text as the universal storage format** — text is always one of the legal formats for storing data, and JSON makes it possible to store JavaScript objects as text. [S1]
- **Specified by Douglas Crockford** — the JSON format was originally specified by Douglas Crockford. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Name/value pairs** — JSON data is written as name/value pairs: a field name in double quotes, a colon, then a value (`"firstName":"John"`). JSON names require double quotes; JavaScript names do not. [S1]
- **Objects in curly braces** — `{"firstName":"John", "lastName":"Doe"}`. [S1]
- **Arrays in square brackets** — an array can contain objects, each a record (e.g. a person with first and last name). [S1]
- **Receive text → parse → use as object** — read text from a server, `JSON.parse()` it, then access fields like any object. [S1]
## 📖 세부 내용 (Details)
**What is JSON?**
JSON stands for JavaScript Object Notation. It is a plain text format for storing and transporting data, and it is similar to the syntax for creating JavaScript objects. JSON is used to send, receive and store data. [S1]
A simple JSON example string: [S1]
```json
{"name":"John", "age":30, "car":null}
```
The example above defines an object with 3 properties — `"name"`, `"age"`, `"car"` — whose values are `"John"`, `30`, and `null` respectively. [S1]
**Why JSON?**
JSON makes it easy to send and store data between computers, and it is text only and language independent. The syntax is derived from JavaScript object syntax, but JSON is text only, so code for reading and generating JSON data can be written in any programming language. The JSON format was originally specified by Douglas Crockford. [S1]
**JSON and JavaScript**
The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this, a JavaScript program can easily convert JSON data into native JavaScript objects. JavaScript has a built-in function for converting JSON strings into JavaScript objects (`JSON.parse()`) and a built-in function for converting an object into a JSON string (`JSON.stringify()`). You can receive pure text from a server and use it as a JavaScript object, send a JavaScript object to a server in pure text format, and work with data as JavaScript objects with no complicated parsing and translations. [S1]
**Storing data**
When storing data, the data has to be a certain format, and regardless of where you store it, text is always one of the legal formats. JSON makes it possible to store JavaScript objects as text. [S1]
Text that defines an `employees` object with an array of 3 employee objects: [S1]
```json
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
```
If you parse the JSON string with a JavaScript program, you can access the data as an object: [S1]
```javascript
let personName = obj.name;
let personAge = obj.age;
```
**JSON data — a name and a value**
JSON data is written as name/value pairs, just like JavaScript object properties. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: [S1]
```json
"firstName":"John"
```
JSON names require double quotes; JavaScript names do not. [S1]
**JSON objects**
JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/value pairs: [S1]
```json
{"firstName":"John", "lastName":"Doe"}
```
**JSON arrays**
JSON arrays are written inside square brackets. Just like in JavaScript, an array can contain objects: [S1]
```json
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
```
In the example above, the object `"employees"` is an array containing three objects. Each object is a record of a person (with a first name and a last name). [S1]
**Converting a JSON text to a JavaScript object**
A common use of JSON is to read data from a web server and display it in a web page. For simplicity this can be demonstrated using a string as input. First, create a JavaScript string containing JSON syntax: [S1]
```javascript
let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
```
Then, use the JavaScript built-in function `JSON.parse()` to convert the string into a JavaScript object: [S1]
```javascript
const obj = JSON.parse(text);
```
Finally, use the new JavaScript object in your page: [S1]
```javascript
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
```
## 🛠️ 적용 사례 (Applied in summary)
The canonical applied example on the page is reading server data: build/receive a JSON string, `JSON.parse()` it into an object, then render a field (e.g. `obj.employees[1].firstName`) into `#demo`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Parse a JSON string into an object and read a nested field:
```javascript
const obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
```
Access top-level fields after parsing:
```javascript
let personName = obj.name;
let personAge = obj.age;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Syntax]], [[JavaScript JSON Parse]], [[JavaScript JSON Stringify]], [[JavaScript JSON vs XML]]
- **참조 맥락:** The entry point for the JSON section, referenced whenever exchanging or storing structured data with a web server.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript JSON — https://www.w3schools.com/js/js_json.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript JSON" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,138 @@
---
id: json-arrays
title: "JSON Arrays"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON arrays", "JSON array literal", "array in JSON", "arrays in objects", "loop JSON array"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "arrays"]
raw_sources: ["https://www.w3schools.com/js/js_json_arrays.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Arrays]]
## 🎯 한 줄 통찰 (One-line insight)
JSON arrays are square-bracket literals almost identical to JavaScript arrays — but their values are restricted to string, number, object, array, boolean, or null — accessed by index and commonly nested inside objects. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Array literals live inside JSON strings** — a JSON string can hold a JSON array literal such as `["Ford", "BMW", "Fiat"]`. [S1]
- **Almost the same as JS arrays** — arrays in JSON are almost the same as arrays in JavaScript. [S1]
- **Restricted value types** — in JSON, array values must be of type string, number, object, array, boolean, or null; in JavaScript they can additionally be any valid JS expression, including functions, dates, and undefined. [S1]
- **Index access** — you access array values by index (`myArray[0]`). [S1]
- **Arrays nest in objects** — objects can contain arrays, accessed like `myObj.cars[0]`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Literal or parse** — `myArray = [...]` or `myArray = JSON.parse(myJSON)`. [S1]
- **Index access** — `myArray[0]`, `myObj.cars[0]`. [S1]
- **Two loop forms** — `for...in` over indices, or a classic counting `for` loop using `.length`. [S1]
## 📖 세부 내용 (Details)
**JSON array literals**
This is a JSON string: [S1]
```json
["Ford", "BMW", "Fiat"]
```
Inside the JSON string there is a JSON array literal: [S1]
```json
["Ford", "BMW", "Fiat"]
```
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. [S1]
**JavaScript arrays**
You can create a JavaScript array from a literal: [S1]
```javascript
myArray = ["Ford", "BMW", "Fiat"];
```
You can create a JavaScript array by parsing a JSON string: [S1]
```javascript
myJSON = '["Ford", "BMW", "Fiat"]';
myArray = JSON.parse(myJSON);
```
**Accessing array values**
You access array values by index: [S1]
```javascript
myArray[0];
```
**Arrays in objects**
Objects can contain arrays: [S1]
```json
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
```
You access array values inside an object by index: [S1]
```javascript
myObj.cars[0];
```
**Looping through an array**
You can access array values by using a for-in loop: [S1]
```javascript
for (let i in myObj.cars) {
x += myObj.cars[i];
}
```
Or you can use a for loop: [S1]
```javascript
for (let i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];
}
```
## 🛠️ 적용 사례 (Applied in summary)
Applied examples on the page: create an array from a literal and from `JSON.parse()`; access by index; embed an array in an object and read `myObj.cars[0]`; and iterate with both for-in and a counting for loop. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Parse a JSON array and index it:
```javascript
myJSON = '["Ford", "BMW", "Fiat"]';
myArray = JSON.parse(myJSON);
myArray[0];
```
Loop an array nested in an object:
```javascript
for (let i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
JSON array values vs JavaScript array values: [S1]
- **JSON** — values restricted to string, number, object, array, boolean, or null.
- **JavaScript** — all of the above plus any valid JS expression, including functions, dates, and undefined.
- **Loop choice** — `for...in` iterates indices succinctly; a counting `for` loop with `.length` gives explicit index control. The source presents both as valid alternatives without preferring one.
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Objects]], [[JavaScript JSON Parse]], [[JavaScript JSON Data Types]], [[JavaScript JSON]]
- **참조 맥락:** Referenced whenever reading or iterating array data within parsed JSON.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Arrays — https://www.w3schools.com/js/js_json_arrays.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,123 @@
---
id: json-data-types
title: "JSON Data Types"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON data types", "JSON values", "JSON valid types", "JSON string number boolean null", "JSON type rules"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "data-types"]
raw_sources: ["https://www.w3schools.com/js/js_json_datatypes.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Data Types]]
## 🎯 한 줄 통찰 (One-line insight)
A JSON value must be one of exactly six data types — string, number, object, array, boolean, or null — and cannot be a function, a date, or undefined. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Six valid value types** — a string, a number, an object (JSON object), an array, a boolean, or null. [S1]
- **Three invalid value types** — JSON values cannot be a function, a date, or undefined. [S1]
- **Strings need double quotes** — strings in JSON must be written in double quotes. [S1]
- **Numbers are integer or float** — numbers in JSON must be an integer or a floating point. [S1]
- **Nested objects must follow JSON syntax** — objects used as values must themselves be valid JSON. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Type-per-value pattern** — each value in a name/value pair is constrained to the six legal types. [S1]
- **Double-quoted strings** — `{"name":"John"}`. [S1]
- **Composite values** — values may themselves be objects or arrays, enabling nesting. [S1]
## 📖 세부 내용 (Details)
**Valid data types**
In JSON, values must be one of the following data types: a string, a number, an object (JSON object), an array, a boolean, or null. JSON values cannot be one of the following data types: a function, a date, or undefined. [S1]
**JSON strings**
Strings in JSON must be written in double quotes. [S1]
```json
{"name":"John"}
```
**JSON numbers**
Numbers in JSON must be an integer or a floating point. [S1]
```json
{"age":30}
```
**JSON objects**
Values in JSON can be objects. [S1]
```json
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
```
Objects as values in JSON must follow the JSON syntax. [S1]
**JSON arrays**
Values in JSON can be arrays. [S1]
```json
{
"employees":["John", "Anna", "Peter"]
}
```
**JSON booleans**
Values in JSON can be true/false. [S1]
```json
{"sale":true}
```
**JSON null**
Values in JSON can be null. [S1]
```json
{"middlename":null}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets each demonstrate one legal value type in a name/value pair (string, number, nested object, array, boolean, null). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
One name/value pair per legal type:
```json
{"name":"John"}
{"age":30}
{"employee":{"name":"John", "age":30, "city":"New York"}}
{"employees":["John", "Anna", "Peter"]}
{"sale":true}
{"middlename":null}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
What JSON allows vs forbids as a value: [S1]
- **Allowed** — string, number (integer or floating point), object, array, boolean, null.
- **Forbidden** — function, date, undefined.
- **Implication** — to carry a date or function in JSON you must encode it as a string and reconstruct it at the receiver (handled on the Parse/Stringify pages).
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Syntax]], [[JavaScript JSON Objects]], [[JavaScript JSON Arrays]], [[JavaScript JSON Stringify]]
- **참조 맥락:** Referenced when validating that a value is legal JSON before serializing or transmitting.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Data Types — https://www.w3schools.com/js/js_json_datatypes.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,128 @@
---
id: json-objects
title: "JSON Objects"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON objects", "JSON object literal", "access JSON object", "loop JSON object", "JSON dot bracket notation"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "objects"]
raw_sources: ["https://www.w3schools.com/js/js_json_objects.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Objects]]
## 🎯 한 줄 통찰 (One-line insight)
A JSON object literal is curly-brace text of key/value pairs; once parsed into a JavaScript object you read its members by dot or bracket notation and iterate them with a for-in loop — but the literal itself is a string format, not "a JSON object." [S1]
## 🧠 핵심 개념 (Core concepts)
- **JSON object literals are surrounded by curly braces `{}`** and contain key/value pairs. [S1]
- **Keys and values rules** — keys must be strings, and values must be a valid JSON data type. [S1]
- **Terminology caution** — it is a common mistake to call a JSON object literal "a JSON object." JSON cannot be an object; JSON is a string format. [S1]
- **Two ways to obtain an object** — write a JavaScript object directly from a literal, or parse a JSON string with `JSON.parse()`. [S1]
- **Two ways to access members** — dot notation (`myObj.name`) or bracket notation (`myObj["name"]`). [S1]
- **Iterate with for-in** — loop over keys, and access each value via `myObj[x]`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Literal → object** — `myObj = {...}` or `myObj = JSON.parse(myJSON)`. [S1]
- **Dot vs bracket access** — `myObj.name` equals `myObj["name"]`. [S1]
- **For-in over keys** — `for (const x in myObj)` yields keys; index with `myObj[x]` for values. [S1]
## 📖 세부 내용 (Details)
**JSON object literals**
JSON object literals are surrounded by curly braces `{}`. JSON object literals contains key/value pairs. Keys must be strings, and values must be a valid JSON data type. It is a common mistake to call a JSON object literal "a JSON object." JSON cannot be an object. JSON is a string format. [S1]
This is a JSON string: [S1]
```json
{"name":"John", "age":30, "car":null}
```
**Creating a JavaScript object**
You can create a JavaScript object directly from a JSON object literal: [S1]
```javascript
myObj = {"name":"John", "age":30, "car":null};
```
Normally you create a JavaScript object by parsing a JSON string: [S1]
```javascript
myObj = JSON.parse(myJSON);
```
**Accessing object values**
You can access object values by using dot (`.`) notation: [S1]
```javascript
x = myObj.name;
```
You can also access object values by using bracket (`[]`) notation: [S1]
```javascript
x = myObj["name"];
```
**Looping an object**
You can loop through object properties with a for-in loop. Loop printing the keys: [S1]
```javascript
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
```
In a for-in loop, use the bracket notation to access the values: [S1]
```javascript
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += myObj[x] + ", ";
}
```
## 🛠️ 적용 사례 (Applied in summary)
Applied examples on the page: build `myObj` from a literal and from `JSON.parse()`; read values via dot and bracket notation; and iterate with for-in (keys, then values via `myObj[x]`). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Parse then access:
```javascript
const myObj = JSON.parse('{"name":"John", "age":30, "car":null}');
x = myObj.name; // dot notation
x = myObj["name"]; // bracket notation
```
Iterate values:
```javascript
let text = "";
for (const x in myObj) {
text += myObj[x] + ", ";
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Arrays]], [[JavaScript JSON Parse]], [[JavaScript JSON Data Types]], [[JavaScript JSON Syntax]]
- **참조 맥락:** Referenced whenever reading or iterating the members of a parsed JSON object.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Objects — https://www.w3schools.com/js/js_json_objects.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Objects" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,132 @@
---
id: json-parse
title: "JSON Parse"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON.parse", "JSON parse", "parse JSON", "JSON to object", "reviver function"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "parse"]
raw_sources: ["https://www.w3schools.com/js/js_json_parse.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Parse]]
## 🎯 한 줄 통찰 (One-line insight)
When data arrives from a web server it is always a string; `JSON.parse()` turns that JSON string into a usable JavaScript object (or array), and dates and functions — which JSON cannot carry — must be reconstructed by hand or via a reviver. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Server data is always a string** — a common use of JSON is to exchange data to/from a web server; when receiving it, parse with `JSON.parse()` and the data becomes a JavaScript object. [S1]
- **Text must be valid JSON** — make sure the text is in JSON format, or you will get a syntax error. [S1]
- **Arrays parse to arrays** — using `JSON.parse()` on JSON derived from an array returns a JavaScript array, not an object. [S1]
- **Dates are not allowed in JSON** — store a date as a string, then convert it back to a Date object later (directly or with a reviver function). [S1]
- **Functions are not allowed in JSON** — avoid them; reconstructing requires `eval()`, and functions lose their scope. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Receive → parse → render** — `JSON.parse(text)` then read fields into the page. [S1]
- **Reviver pattern** — pass a function as the second argument to `JSON.parse()` to transform values (e.g. convert a `"birth"` string into a Date) during parsing. [S1]
- **Manual rehydration** — after parsing, replace a string field with a real object: `obj.birth = new Date(obj.birth)`. [S1]
## 📖 세부 내용 (Details)
A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with `JSON.parse()`, and the data becomes a JavaScript object. [S1]
**Example — parsing JSON**
Imagine we received this text from a web server: `'{"name":"John", "age":30, "city":"New York"}'`. Use `JSON.parse()` to convert the text into a JavaScript object: [S1]
```javascript
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
```
Make sure the text is in JSON format, or else you will get a syntax error. Then use the object in your page: [S1]
```javascript
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = obj.name;
</script>
```
**Array as JSON**
When using `JSON.parse()` on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object: [S1]
```javascript
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);
```
**Exceptions — parsing dates**
Date objects are not allowed in JSON. If you need to include a date, write it as a string. You can convert it back into a date object later. Convert directly after parsing: [S1]
```javascript
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
```
Or use the second parameter of `JSON.parse()`, called the reviver function, which is called on each value before returning it: [S1]
```javascript
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
```
**Exceptions — parsing functions**
Functions are not allowed in JSON. If you need to include a function, write it as a string and convert it back into a function later: [S1]
```javascript
const text = '{"name":"John", "age":"function () {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
```
You should avoid using functions in JSON; the functions will lose their scope, and you would have to use `eval()` to convert them back into functions. [S1]
## 🛠️ 적용 사례 (Applied in summary)
Applied examples on the page: parse server text into `obj` and render `obj.name` into `#demo`; parse a JSON array into a real array; rehydrate a date both manually and via a reviver; and (discouraged) rebuild a function with `eval()`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Parse server text into an object:
```javascript
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name;
```
Reviver to reconstruct a date during parse:
```javascript
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Stringify]], [[JavaScript JSON]], [[JavaScript JSON Data Types]], [[JavaScript JSON Objects]]
- **참조 맥락:** Referenced whenever consuming JSON received from a server or storage and turning it into usable objects.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Parse — https://www.w3schools.com/js/js_json_parse.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Parse" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,137 @@
---
id: json-stringify
title: "JSON Stringify"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON.stringify", "JSON stringify", "object to JSON", "serialize JSON", "stringify object"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "stringify"]
raw_sources: ["https://www.w3schools.com/js/js_json_stringify.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Stringify]]
## 🎯 한 줄 통찰 (One-line insight)
When sending data to a web server the data has to be a string; `JSON.stringify()` converts any JavaScript datatype into a JSON-notation string — converting dates to strings and removing functions, since JSON allows neither. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Sending data needs a string** — when sending data to a web server, the data has to be a string; convert any JavaScript datatype with `JSON.stringify()`. [S1]
- **Works on objects and arrays** — the result is a string following JSON notation, ready to be sent to a server. [S1]
- **Text storage** — text is always a legal storage format; combined with `localStorage`, JSON lets you store and reload JavaScript objects. [S1]
- **Dates become strings** — in JSON, date objects are not allowed; `JSON.stringify()` converts any Date objects into strings (convert back at the receiver). [S1]
- **Functions are removed** — in JSON, functions are not allowed as object values; `JSON.stringify()` removes any functions (both the key and the value). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Serialize-then-send** — `JSON.stringify(obj)` produces a transmittable string. [S1]
- **Round-trip storage** — `JSON.stringify` to save in `localStorage`, `JSON.parse` to read it back. [S1]
- **Pre-stringify a function to keep it** — call `obj.fn = obj.fn.toString()` before stringifying so the function survives as a string. [S1]
## 📖 세부 내용 (Details)
A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string. You can convert any JavaScript datatype into a string with `JSON.stringify()`. [S1]
**Stringify a JavaScript object**
```javascript
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
```
The result will be a string following the JSON notation. `myJSON` is now a string, and ready to be sent to a server. [S1]
**Stringify a JavaScript array**
```javascript
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
```
The result will be a string following the JSON notation. `myJSON` is now a string, and ready to be sent to a server. [S1]
**Storing data**
When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats. JSON makes it possible to store JavaScript objects as text. Example storing and retrieving data in local storage: [S1]
```javascript
const myObj = {name: "John", age: 31, city: "New York"};
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
```
**Stringify a number** [S1]
```javascript
const num = 123e-5;
const myJSON = JSON.stringify(num);
```
**Stringify a boolean** [S1]
```javascript
let bool = new Boolean(1);
const myJSON = JSON.stringify(bool);
```
**Stringify a date**
In JSON, date objects are not allowed. The `JSON.stringify()` function will convert any Date objects into strings. [S1]
```javascript
const obj = {name: "John", today: new Date(), city : "New York"};
const myJSON = JSON.stringify(obj);
```
You can convert the string back into a date object at the receiver. [S1]
**Stringify a function**
In JSON, functions are not allowed as object values. The `JSON.stringify()` function will remove any functions from a JavaScript object, both the key and the value. [S1]
```javascript
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj);
```
You can preserve a function by converting it to a string before stringifying: [S1]
```javascript
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);
```
If you send functions using JSON, the functions will lose their scope, and the receiver would have to use `eval()` to convert them back into functions. [S1]
## 🛠️ 적용 사례 (Applied in summary)
Applied examples on the page: serialize an object and an array for sending to a server; round-trip an object through `localStorage`; stringify numbers, booleans, dates, and functions, including the `.toString()` trick to keep a function. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Serialize an object to send to a server:
```javascript
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
```
Round-trip an object through local storage:
```javascript
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
let obj = JSON.parse(localStorage.getItem("testJSON"));
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON Parse]], [[JavaScript JSON]], [[JavaScript JSON Data Types]], [[JavaScript JSON Objects]]
- **참조 맥락:** Referenced whenever serializing JavaScript data for transmission to a server or storage.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Stringify — https://www.w3schools.com/js/js_json_stringify.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Stringify" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,142 @@
---
id: json-syntax
title: "JSON Syntax"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON syntax", "JSON rules", "name/value pairs", "JSON keys", "JSON files"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "syntax"]
raw_sources: ["https://www.w3schools.com/js/js_json_syntax.asp"]
applied_in: []
github_commit: ""
---
# [[JSON Syntax]]
## 🎯 한 줄 통찰 (One-line insight)
JSON syntax is derived from JavaScript object notation — name/value pairs separated by commas, objects in curly braces, arrays in square brackets — but it is stricter than JavaScript: keys and string values must always use double quotes. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Four syntax rules** — data is in name/value pairs; data is separated by commas; curly braces hold objects; square brackets hold arrays. [S1]
- **JSON keys must be strings in double quotes** — `{"name":"John"}`, whereas JavaScript keys can be strings, numbers, or identifier names (`{name:"John"}`). [S1]
- **JSON string values require double quotes** — `{"name":"John"}`; JavaScript allows double or single quotes (`{name:'John'}`). [S1]
- **JSON is almost identical to JavaScript objects** — and JavaScript arrays can also be written as JSON. [S1]
- **File facts** — the file type for JSON files is `.json`; the MIME type for JSON text is `application/json`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Name/value (key/value) pair** — a field name in double quotes, a colon, then a value: `"name":"John"`. [S1]
- **Stricter-than-JS rule** — JSON is a subset: it forbids the looser key/quote forms JavaScript allows. [S1]
- **Object access patterns carry over** — a JavaScript object can be read/modified via dot or bracket notation. [S1]
## 📖 세부 내용 (Details)
**JSON syntax rules**
JSON syntax is derived from JavaScript object notation syntax: data is in name/value pairs; data is separated by commas; curly braces hold objects; square brackets hold arrays. [S1]
**JSON data — a name and a value**
JSON data is written as name/value pairs (aka key/value pairs). A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: [S1]
```json
"name":"John"
```
JSON names require double quotes. [S1]
**JSON evaluates to JavaScript objects**
The JSON format is almost identical to JavaScript objects. In JSON, keys must be strings, written with double quotes — JSON: [S1]
```json
{"name":"John"}
```
In JavaScript, keys can be strings, numbers, or identifier names — JavaScript: [S1]
```javascript
{name:"John"}
```
**JSON values**
In JSON, values must be one of the following data types: a string, a number, an object, an array, a boolean, or null. In JavaScript, values can be all of the above, plus any other valid JavaScript expression, including a function, a date, or undefined. [S1]
In JSON, string values must be written with double quotes — JSON: [S1]
```json
{"name":"John"}
```
In JavaScript, you can write string values with double or single quotes — JavaScript: [S1]
```javascript
{name:'John'}
```
**JavaScript objects**
With JavaScript you can create an object and assign data to it: [S1]
```javascript
person = {name:"John", age:31, city:"New York"};
```
You can access a JavaScript object like this: [S1]
```javascript
// returns John
person.name;
```
It can also be accessed like this: [S1]
```javascript
// returns John
person["name"];
```
Data can be modified like this: [S1]
```javascript
person.name = "Gilbert";
```
It can also be modified like this: [S1]
```javascript
person["name"] = "Gilbert";
```
You will learn how to convert JavaScript objects into JSON later in this tutorial. [S1]
**JavaScript arrays as JSON**
The same way JavaScript objects can be written as JSON, JavaScript arrays can also be written as JSON. You will learn more about objects and arrays later in this tutorial. [S1]
**JSON files**
The file type for JSON files is `.json`. The MIME type for JSON text is `application/json`. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The applied examples on the page are object creation, access (dot and bracket), and modification (dot and bracket) on a `person` object. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Create, access, and modify a JavaScript object:
```javascript
person = {name:"John", age:31, city:"New York"};
person.name; // returns John
person["name"]; // returns John
person.name = "Gilbert";
person["name"] = "Gilbert";
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
JSON vs JavaScript object literals — JSON is the stricter subset: [S1]
- **Keys** — JSON requires string keys in double quotes; JavaScript allows strings, numbers, or identifier names.
- **String values** — JSON requires double quotes; JavaScript allows double or single quotes.
- **Value types** — JSON values must be string, number, object, array, boolean, or null; JavaScript additionally allows functions, dates, undefined, and any valid JS expression.
- **When to use which** — use JSON's stricter form for any data meant to be transported or stored as text; use full JS object syntax for in-program objects.
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON]], [[JavaScript JSON Data Types]], [[JavaScript JSON Objects]], [[JavaScript JSON Arrays]]
- **참조 맥락:** The rules referenced whenever hand-writing or validating a JSON document.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON Syntax — https://www.w3schools.com/js/js_json_syntax.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON Syntax" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,134 @@
---
id: json-vs-xml
title: "JSON vs XML"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JSON vs XML", "JSON XML comparison", "JSON or XML", "data format comparison", "XML alternative"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "json", "xml"]
raw_sources: ["https://www.w3schools.com/js/js_json_xml.asp"]
applied_in: []
github_commit: ""
---
# [[JSON vs XML]]
## 🎯 한 줄 통찰 (One-line insight)
JSON and XML are both self-describing, hierarchical, language-portable data formats, but JSON is shorter, uses no end tags, supports arrays, and can be parsed by a standard JavaScript function into a ready-to-use object — whereas XML needs an XML parser. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Both formats serve the same role** — representing the same hierarchical data (e.g. an `employees` list) in text. [S1]
- **JSON is like XML** — both are self-describing (human readable), both are hierarchical (values within values), both can be parsed and used by lots of programming languages, and both can be fetched with an `XMLHttpRequest`. [S1]
- **JSON is unlike XML** — JSON doesn't use end tags, JSON is shorter, JSON is quicker to read and write, and JSON can use arrays. [S1]
- **Parsing is the key difference** — XML has to be parsed with an XML parser; JSON can be parsed by a standard JavaScript function. [S1]
- **Why JSON is better than XML** — XML is much more difficult to parse than JSON; JSON is parsed into a ready-to-use JavaScript object. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Same data, two encodings** — compare the JSON array-of-objects against the equivalent nested XML element tree. [S1]
- **Parse-to-object pattern (JSON)** — fetch a JSON string, then `JSON.parse` it. [S1]
- **Parse-and-walk pattern (XML)** — fetch an XML document, loop through it with the XML DOM, extract values, and store them in variables. [S1]
## 📖 세부 내용 (Details)
The following examples both define an employees object/structure with 3 employees. [S1]
**JSON example:** [S1]
```json
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
```
**XML example:** [S1]
```xml
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
```
**JSON is like XML because** [S1]
- Both JSON and XML are "self describing" (human readable).
- Both JSON and XML are hierarchical (values within values).
- Both JSON and XML can be parsed and used by lots of programming languages.
- Both JSON and XML can be fetched with an `XMLHttpRequest`.
**JSON is unlike XML because** [S1]
- JSON doesn't use end tag.
- JSON is shorter.
- JSON is quicker to read and write.
- JSON can use arrays.
The biggest difference is: XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function. [S1]
**Why JSON is better than XML**
XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object. [S1]
Using XML: fetch an XML document, use the XML DOM to loop through the document, extract values and store them in variables. [S1]
Using JSON: fetch a JSON string, then `JSON.Parse` the JSON string. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page contrasts two real workflows: the XML path (fetch document → walk the XML DOM → extract into variables) versus the JSON path (fetch string → `JSON.parse`). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
The JSON encoding of the comparison data set:
```json
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
```
The equivalent XML encoding:
```xml
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
</employees>
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
JSON vs XML, per the source: [S1]
- **Similarities** — both self-describing/human readable, hierarchical, multi-language parseable, and fetchable via `XMLHttpRequest`.
- **JSON advantages** — no end tags, shorter, quicker to read and write, supports arrays, and parses directly into a ready-to-use JavaScript object with a standard JS function.
- **XML cost** — must be parsed with an XML parser, then walked via the XML DOM to extract values into variables — "much more difficult to parse than JSON."
- **Decision** — the page recommends JSON because it is parsed into a ready-to-use JavaScript object, making it the lower-effort choice for JavaScript-driven web pages.
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript JSON]], [[JavaScript JSON Syntax]], [[JavaScript JSON Parse]], [[JavaScript JSON Arrays]]
- **참조 맥락:** Referenced when choosing a data interchange format for a web application or API.
## 📚 출처 (Sources)
- [S1] W3Schools — JSON vs XML — https://www.w3schools.com/js/js_json_xml.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JSON vs XML" page (Astra wiki-curation, P-Reinforce v3.1 format).
+179
View File
@@ -0,0 +1,179 @@
---
id: javascript-let
title: "JavaScript Let"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["let keyword", "block scope", "let vs var", "let hoisting", "ES6 let"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "let", "block-scope"]
raw_sources: ["https://www.w3schools.com/js/js_let.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Let]]
## 🎯 한 줄 통찰 (One-line insight)
The `let` keyword (ES6, 2015) introduced block scope to JavaScript — `let` variables are confined to their `{ }` block, cannot be redeclared in the same scope, and are hoisted but not initialized. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Block scope (new in ES6)** — before ES6 (2015) JavaScript had no block scope; variables declared with `let` inside a `{ }` block cannot be accessed outside it. [S1]
- **Function scope** — variables declared with `var`, `let`, or `const` inside a function cannot be accessed outside it. [S1]
- **`var` is global/function scoped** — a `var` declared inside a block can still be used outside the block. [S1]
- **Cannot be redeclared in the same scope** — `let` variables cannot be redeclared in the same scope (whereas `var` can). [S1]
- **Hoisted but not initialized** — `let` variables are hoisted to the top of their block but not initialized; using one before its declaration causes a `ReferenceError`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Block-local shadowing** — declaring `let x` inside a block shadows an outer `x` without altering it, unlike `var` which leaks back out. [S1]
- **Redeclare across different blocks** — the same `let` name may be redeclared in different blocks, just not twice in the same scope. [S1]
- **Declare-before-use discipline** — because `let` is not initialized when hoisted, always declare before using. [S1]
## 📖 세부 내용 (Details)
**Block Scope** — Before ES6 (2015), JavaScript had only Global Scope and Function Scope. ES6 introduced two new JavaScript keywords: `let` and `const`. These two keywords provided Block Scope in JavaScript. Variables declared inside a `{ }` block cannot be accessed from outside the block: [S1]
```javascript
{
let x = 2;
}
// x can NOT be used here
```
**Function Scope** — Variables declared with `var`, `let`, and `const` are quite similar when declared inside a function — they all have Function Scope: [S1]
```javascript
function myfunction() {
var x = 1;
let y = 2;
const z = 3;
}
//x can NOT be used here
//y can NOT be used here
//z can NOT be used here
```
**Global Scope (var)** — Variables declared with `var` inside a block can be accessed from outside the block: [S1]
```javascript
{
var x = 2;
}
// x CAN be used here
```
**Cannot be Redeclared** — Variables defined with `let` can not be redeclared. You can not accidentally redeclare a variable declared with `let`: [S1]
```javascript
let x = "John Doe";
let x = 0; // Error
```
Variables defined with `var` can be redeclared: [S1]
```javascript
var x = "John Doe";
var x = 0; // Allowed
```
**Redeclaring Variables** — Redeclaring a variable using the `var` keyword can impose problems. Redeclaring a variable inside a block will also redeclare the variable outside the block: [S1]
```javascript
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
```
Redeclaring a variable using the `let` keyword can solve this problem. Redeclaring a variable inside a block will not redeclare the variable outside the block: [S1]
```javascript
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
```
**Redeclaring (across different blocks)** — Redeclaring a `let` variable in different blocks is allowed: [S1]
```javascript
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
```
**Let Hoisting** — Variables defined with `let` are hoisted to the top of the block, but not initialized. Using a `let` variable before it is declared will result in a `ReferenceError`: [S1]
```javascript
carName = "Saab";
let carName = "Volvo"; // ReferenceError
```
By contrast, variables defined with `var` are hoisted to the top and can be used before declaration: [S1]
```javascript
carName = "Volvo";
var carName; // OK
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — block-scoped `let x`, the `var`-leaks vs `let`-contained redeclaration pair, redeclaring `let` across separate blocks, and the hoisting `ReferenceError` contrast. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Block-scoped variable:
```javascript
{
let x = 2;
}
// x can NOT be used here
```
Safe shadowing:
```javascript
let x = 10;
{
let x = 2;
}
// Here x is 10
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
The source compares the three declaration keywords: [S1]
| Feature | var | let | const |
|---------|-----|-----|-------|
| Scope | Function or global | Block-scope `{ }` | Block-scope `{ }` |
| Reassignment | Can be updated | Can be updated | Cannot be updated |
| Redeclaration | Can be redeclared | Cannot be redeclared | Cannot be redeclared |
| Hoisting | Initialized as `undefined` | Hoisted, not initialized | Hoisted, not initialized |
Choose `let` when you need a reassignable variable scoped to a block; choose `const` when the value will not change; avoid `var` to prevent unintentional global/function-scope leakage. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. (The page frames `let`/`const` as a 2015 update over the older `var`-only model — an evolution, not a contradiction.)
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Variables]], [[JavaScript Const]], [[JavaScript Statements]]
- **참조 맥락:** The block-scoped declaration keyword, contrasted against `var` and paired with `const`.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Let — https://www.w3schools.com/js/js_let.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Let" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,125 @@
---
id: javascript-logical-operators
title: "JavaScript Logical Operators"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["logical operators", "AND OR NOT", "&& || !", "nullish coalescing", "JS logic"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "logical-operators", "nullish-coalescing", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_logical.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Logical Operators]]
## 🎯 한 줄 통찰 (One-line insight)
Logical operators (`&&`, `||`, `!`) combine boolean expressions into more complex logic, while `??` returns a fallback only when the left operand is nullish (`null` or `undefined`). [S1]
## 🧠 핵심 개념 (Core concepts)
- **Combine boolean expressions** — logical operators are used to combine boolean expressions and to modify the results of comparisons. [S1]
- **`&&` (AND)** — true only when both operands are true. [S1]
- **`||` (OR)** — true when at least one operand is true. [S1]
- **`!` (NOT)** — inverts a boolean result. [S1]
- **`??` (Nullish coalescing)** — returns the right operand when the left operand is nullish (`null` or `undefined`); otherwise returns the left operand. [S1]
- **Nullish ≠ falsy** — `??` checks specifically for `null`/`undefined`, so values like `0`, `""`, and `false` are preserved. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Condition + combinator** — use a comparison operator to check a condition and a logical operator to combine conditions into more complex logic. [S1]
- **Nullish-safe default** — use `??` when an empty string or `false` is an acceptable value and only `null`/`undefined` should trigger the fallback. [S1]
## 📖 세부 내용 (Details)
**Logical operators** [S1]
Logical operators are used to combine boolean expressions. Logical operators can be used to modify the results of comparisons. Typically, you will use a comparison operator to check a condition, and a logical operator to combine conditions into more complex logic. Logical operators are used to determine the logic between variables or values.
Given `x = 6` and `y = 3`:
| Operator | Name | Example |
|----------|------|---------|
| && | AND | (x < 10 && y > 1) is true |
| \|\| | OR | (x === 5 \|\| y === 5) is false |
| ! | NOT | !(x === y) is true |
**AND (`&&`) example** [S1]
```javascript
let x = 6;
let y = 3;
let z = (x < 10 && y > 1)
```
**OR (`||`) example** [S1]
```javascript
let x = 6;
let y = -3;
let z = (x > 0 || y > 0)
```
**NOT (`!`) example** [S1]
```javascript
let x = (5 == 8);
let y = !(5 == 8)
```
**The Nullish Coalescing Operator (`??`)** [S1]
The `??` operator returns the right operand when the left operand is nullish (`null` or `undefined`), otherwise it returns the left operand.
```javascript
let name = null;
let text = "missing";
let result = name ?? text;
```
When programming, a lot of values can be falsy (like `0`, empty strings, `false`, `undefined`, `null`, `NaN`). However, sometimes you want to check if a variable is nullish (either `undefined` or `null`), like when it is okay for a variable to be an empty string or a false value. Then you can use the nullish coalescing operator.
**Browser support** [S1]
`??` is an ES2020 feature. ES2020 is fully supported in all modern browsers since September 2020 (Chrome 85, Edge 85, Firefox 79, Safari 14, Opera 71).
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — combining comparisons with `&&` and `||`, negating with `!`, and supplying a nullish-safe default with `??`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Combine conditions with AND / OR:
```javascript
let z = (x < 10 && y > 1)
let w = (x > 0 || y > 0)
```
Negate a result:
```javascript
let y = !(5 == 8)
```
Nullish-safe default:
```javascript
let name = null;
let text = "missing";
let result = name ?? text;
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`??` vs `||` for defaults** — `||` falls back on any falsy value (`0`, `""`, `false`, `null`, `undefined`, `NaN`), whereas `??` falls back only on nullish values (`null`/`undefined`). Choose `??` when an empty string or `false` is a valid value that should be preserved. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The `??` operator is noted as an ES2020 addition relative to the older `&&`/`||`/`!` operators.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Booleans]], [[JavaScript Comparisons]], [[JavaScript If Else]], [[JavaScript Ternary]]
- **참조 맥락:** Used to build compound conditions in `if`/`while`/ternary expressions and to supply safe default values.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Logical Operators — https://www.w3schools.com/js/js_logical.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Logical Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,147 @@
---
id: javascript-for-loop
title: "JavaScript For Loop"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["for loop", "JS for loop", "for statement", "loop expressions", "for loop scope"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "for-loop", "loops", "iteration"]
raw_sources: ["https://www.w3schools.com/js/js_loop_for.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript For Loop]]
## 🎯 한 줄 통찰 (One-line insight)
The `for` statement creates a loop with three optional expressions — initialize, test, update — letting a code block run a controlled number of times. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Three optional expressions** — the `for` statement creates a loop with three optional expressions. [S1]
- **exp1 — initializer** — sets a variable before the loop starts (`let i = 0`), and can be omitted if initialization happens beforehand. [S1]
- **exp2 — condition** — defines the condition for the loop to run; it is optional, but if omitted you must `break` inside the loop or it runs forever. [S1]
- **exp3 — update** — increases a value (`i++`) after the code block executes; it is optional and can do other operations. [S1]
- **Loop scope matters** — `let` scopes the counter to the loop; `var` redeclares the outer variable. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Index-driven array traversal** — cache `cars.length` once, then iterate `i` from 0 to that length. [S1]
- **Omit-and-supply elsewhere** — any of the three expressions can be moved out of the `for(...)` header (initialize before, update inside the body). [S1]
- **Prefer `let` for the counter** — keeps `i` private to the loop. [S1]
## 📖 세부 내용 (Details)
**The `for` statement** [S1]
The `for` statement creates a loop with 3 optional expressions, allowing the code block to execute multiple times.
- **exp1** sets a variable before the loop starts (`let i = 0`).
- **exp2** defines the condition for the loop to run (`i` must be less than 5).
- **exp3** increases a value (`i++`) after the code block has been executed.
The first expression can be omitted if initialization occurs before the loop. The second expression is optional but requires a `break` statement inside the loop to prevent infinite execution. The third expression is optional and can perform various operations like negative increment or custom calculations.
**Basic for loop** [S1]
```javascript
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
```
**Iterating through an array** [S1]
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let len = cars.length;
let text = "";
for (let i = 0; i < len; i++) {
text += cars[i];
}
```
**Omitting exp1** [S1]
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let len = cars.length;
let i = 2;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
```
**Omitting exp3** [S1]
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let len = cars.length;
let i = 0;
let text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
```
**Loop scope** [S1]
Using `var` in a loop, the loop variable redeclares the outer variable:
```javascript
var i = 5;
for (var i = 0; i < 10; i++) {
// some code
}
// Here i is 10
```
Using `let` in a loop, the variable is scoped only within the loop. When `let` is used to declare the `i` variable, the `i` variable will only be visible within the loop:
```javascript
let i = 5;
for (let i = 0; i < 10; i++) {
// some code
}
// Here i is 5
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — counting 04, traversing a `cars` array (with `len` cached), and demonstrating exp1/exp3 omission and `let`/`var` scoping. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Standard counted loop:
```javascript
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
```
Array traversal with cached length:
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let len = cars.length;
for (let i = 0; i < len; i++) {
text += cars[i];
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`let` vs `var` for the counter** — `let` keeps `i` visible only inside the loop (`i` is 5 afterward in the example); `var` leaks/redeclares it to the outer scope (`i` is 10 afterward). Prefer `let`. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Loops]], [[JavaScript While Loop]], [[JavaScript Break]], [[JavaScript For In]]
- **참조 맥락:** The primary counted-iteration construct; detailed expansion of the `for` loop introduced in [[JavaScript Loops]].
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript For Loop — https://www.w3schools.com/js/js_loop_for.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript For Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,149 @@
---
id: javascript-while-loop
title: "JavaScript While Loop"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["while loop", "do while", "JS while loop", "condition loop", "do while loop"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "while-loop", "do-while", "loops", "iteration"]
raw_sources: ["https://www.w3schools.com/js/js_loop_while.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript While Loop]]
## 🎯 한 줄 통찰 (One-line insight)
A `while` loop runs a block of code as long as a condition is true; its `do/while` variant guarantees the block runs at least once before the condition is checked. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Condition-driven repetition** — the `while` loop loops through a block of code as long as a specified condition is true. [S1]
- **Two while forms** — JavaScript offers the `while` loop and the `do/while` loop. [S1]
- **`do/while` runs once first** — it executes the code block once before checking the condition, then repeats while the condition is true. [S1]
- **Runs at least once** — `do/while` runs at least once, even if the condition is false from the start. [S1]
- **Infinite-loop hazard** — forgetting to increase the condition variable means the loop never ends and crashes the browser. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Advance the counter inside the body** — increment the loop variable (`i++`) within the block so the condition eventually fails. [S1]
- **Truthy-element traversal** — loop while `cars[i]` is truthy to walk an array until it runs out of elements. [S1]
- **`for``while` equivalence** — a `for (;cars[i];)` loop and a `while (cars[i])` loop express the same iteration. [S1]
## 📖 세부 내용 (Details)
**Introduction** [S1]
While loops execute a block of code as long as a specified condition is true. JavaScript offers two while loop types: the `while` loop and the `do/while` loop.
**The while loop** [S1]
The `while` loop loops through a block of code as long as a specified condition is true.
```javascript
while (condition) {
// code block to be executed
}
```
```javascript
while (i < 10) {
text += "The number is " + i;
i++;
}
```
Warning: If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
**The do/while loop** [S1]
The `do/while` loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
```javascript
do {
// code block to be executed
}
while (condition);
```
```javascript
do {
text += "The number is " + i;
i++;
}
while (i < 10);
```
The `do while` runs at least once, even if the condition is false from the start.
**Comparing for and while** [S1]
Using a `for` loop to traverse a cars array:
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
for (;cars[i];) {
text += cars[i];
i++;
}
```
The same loop expressed as a `while` loop:
```javascript
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
while (cars[i]) {
text += cars[i];
i++;
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — accumulating numbers while `i < 10` in both `while` and `do/while` forms, and traversing a `cars` array while `cars[i]` is truthy. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Standard while loop:
```javascript
while (i < 10) {
text += "The number is " + i;
i++;
}
```
Do-while (runs at least once):
```javascript
do {
text += "The number is " + i;
i++;
}
while (i < 10);
```
Truthy-element array traversal:
```javascript
while (cars[i]) {
text += cars[i];
i++;
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`while` vs `do/while`** — use `do/while` when the block must run at least once regardless of the initial condition; use `while` when the block should be skipped entirely if the condition is false at the start. [S1]
- **`for` vs `while`** — the two are interchangeable for condition-only iteration (`for (;cars[i];)` equals `while (cars[i])`); choose based on whether you want the init/update folded into the header. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Loops]], [[JavaScript For Loop]], [[JavaScript Break]], [[JavaScript Booleans]]
- **참조 맥락:** The condition-driven iteration construct; companion to the counted [[JavaScript For Loop]].
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript While Loop — https://www.w3schools.com/js/js_loop_while.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript While Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,162 @@
---
id: javascript-loops
title: "JavaScript Loops"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["loops", "JS loops", "for loop", "while loop", "do while", "iteration"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "loops", "iteration", "control-flow"]
raw_sources: ["https://www.w3schools.com/js/js_loops.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Loops]]
## 🎯 한 줄 통찰 (One-line insight)
Loops let you run the same block of code many times, each time with a different value — replacing long repetitive sequences with a compact iteration. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Loops repeat a block of code** — they execute a code block multiple times, often with a different value each pass. [S1]
- **`for` loop** — uses three expressions: an initializer, a condition, and an update run after each iteration. [S1]
- **`while` loop** — runs as long as a specified condition is true. [S1]
- **`do/while` loop** — a variant that runs the block at least once before checking the condition. [S1]
- **Loop scope** — variables declared with `let` inside a loop are visible only within the loop, unlike `var`. [S1]
- **Infinite-loop hazard** — forgetting to update the condition variable means the loop never ends and crashes the browser. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Replace repetition with iteration** — instead of writing the same statement for each array index, loop over `cars.length`. [S1]
- **Index accumulation** — append each iteration's value into a result string (`text += ...`). [S1]
- **Always advance the condition variable** — increment (e.g. `i++`) so the condition eventually becomes false. [S1]
## 📖 세부 내용 (Details)
**Why loops** [S1]
Loops are handy if you want to run the same code over and over again, each time with a different value. Instead of writing the same statement many times:
```javascript
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
```
You can write:
```javascript
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
```
**The `for` loop** [S1]
The `for` loop has the syntax `for (expr1; expr2; expr3) { // code block to be executed }`.
```javascript
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
```
**Loop scope — `var` vs `let`** [S1]
Using `var` in a loop, the loop variable redeclares the outer variable:
```javascript
let i = 5;
for (i = 0; i < 10; i++) {
// some code
}
// Here i is 10
```
Using `let` in a loop, the loop variable is scoped only to the loop:
```javascript
let i = 5;
for (let i = 0; i < 10; i++) {
// some code
}
// Here i is 5
```
**The `while` loop** [S1]
The `while` loop has the syntax `while (condition) { // code block to be executed }`.
```javascript
while (i < 10) {
text += "The number is " + i;
i++;
}
```
Note: If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
**The `do/while` loop** [S1]
The `do/while` loop has the syntax `do { // code block to be executed } while (condition);`.
```javascript
do {
text += "The number is " + i;
i++;
}
while (i < 10);
```
Note: The `do while` runs at least once, even if the condition is false from the start.
**Different kinds of loops** [S1]
JavaScript supports the `for` loop (loops through a block of code a number of times), the `for/in` loop (loops through the properties of an object), the `for/of` loop (loops through the values of an iterable object), the `while` loop (loops through a block of code while a condition is true), and the `do/while` loop (also loops while a condition is true).
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — replacing repeated `text += cars[n]` statements with a `for` loop over `cars.length`, and accumulating numbers in `for`/`while`/`do-while` loops. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Iterate an array:
```javascript
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
```
While loop with advancing counter:
```javascript
while (i < 10) {
text += "The number is " + i;
i++;
}
```
Do-while (runs at least once):
```javascript
do {
text += "The number is " + i;
i++;
}
while (i < 10);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`for` vs `while`** — use `for` when the number of iterations / the counter is known up front (init, condition, update in one place); use `while` when looping purely on a condition. [S1]
- **`while` vs `do/while`** — use `do/while` when the block must run at least once even if the condition is initially false. [S1]
- **`let` vs `var` for the loop variable** — `let` keeps the counter scoped to the loop; `var` leaks it to the surrounding scope. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript For Loop]], [[JavaScript While Loop]], [[JavaScript Break]], [[JavaScript Booleans]]
- **참조 맥락:** The overview entry point for all iteration constructs; specific loop types are detailed in their own pages.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Loops — https://www.w3schools.com/js/js_loops.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Loops" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,228 @@
---
id: javascript-map-methods
title: "JavaScript Map Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Map methods", "Map.set", "Map.get", "Map.has", "Map.size", "Map.groupBy", "objects as keys"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "map", "methods"]
raw_sources: ["https://www.w3schools.com/js/js_map_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Map Methods]]
## 🎯 한 줄 통찰 (One-line insight)
Map methods — `set`, `get`, `has`, `delete`, `clear`, `forEach`, `entries`, `keys`, `values`, plus `size` — manage and iterate key-value pairs, and crucially Maps can use objects as keys; ES2024 also adds the static `Map.groupBy()`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`get()` retrieves**, **`set()` adds or updates** a key's value, **`has()` tests** key existence, **`delete()` removes** one element, **`clear()` empties** the Map, **`size`** returns the count. [S1]
- **Three iteration methods** — `forEach()` (callback per pair), `entries()` (`[key, value]` iterator), `keys()` and `values()` (key/value iterators). [S1]
- **Objects can be Map keys** — an important Map feature; a string key won't match an object key, so `get("apples")` returns `undefined` when the key is an object. [S1]
- **`Map.groupBy()` (ES2024)** groups elements of an iterable by a callback's return value, producing a Map. (`Object.groupBy()` groups into an object; `Map.groupBy()` groups into a Map.) [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Iterate-and-accumulate** — `for...of` over `entries()`, `keys()`, or `values()` to build text or sum totals. [S1]
- **delete-then-check** — `delete()` followed by `has()` to confirm removal. [S1]
- **Object keys for identity** — store per-object data by using the object itself as the key. [S1]
- **Group by predicate** — `Map.groupBy(iterable, callback)` to bucket items. [S1]
## 📖 세부 내용 (Details)
**The get() Method** — gets the value of a key in a Map: [S1]
```javascript
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
```
```javascript
fruits.get("apples");
```
**The set() Method** — adds or changes the value of a key: [S1]
```javascript
// Create a Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
```
```javascript
fruits.set("apples", 500);
```
**The size Property** — returns the number of elements: [S1]
```javascript
fruits.size;
```
**The delete() Method** — removes a Map element specified by a key: [S1]
```javascript
fruits.delete("apples");
```
**The clear() Method** — removes all elements: [S1]
```javascript
fruits.clear();
```
**The has() Method** — returns `true` if a key exists: [S1]
```javascript
fruits.has("apples");
```
```javascript
fruits.delete("apples");
fruits.has("apples");
```
**The forEach() Method** — invokes a callback for each key/value pair: [S1]
```javascript
// List all entries
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
})
```
**The entries() Method** — returns an iterator with the `[key, value]` pairs: [S1]
```javascript
// List all entries
let text = "";
for (const x of fruits.entries()) {
text += x;
}
```
**The keys() Method** — returns an iterator with the keys: [S1]
```javascript
// List all keys
let text = "";
for (const x of fruits.keys()) {
text += x;
}
```
**The values() Method** — returns an iterator with the values: [S1]
```javascript
// List all values
let text = "";
for (const x of fruits.values()) {
text += x;
}
```
You can use the `values()` method to sum the values in a Map: [S1]
```javascript
// Sum all values
let total = 0;
for (const x of fruits.values()) {
total += x;
}
```
**Objects as Keys** — being able to use objects as keys is an important Map feature: [S1]
```javascript
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
```
Remember: the key is an object (`apples`), not a string (`"apples"`): [S1]
```javascript
fruits.get("apples"); // Returns undefined
```
**JavaScript Map.groupBy()** — the ES2024 `Map.groupBy()` method groups elements of an iterable into a Map according to a callback's return value. The difference between `Object.groupBy()` and `Map.groupBy()` is output type: the former groups elements into a JavaScript object, the latter into a Map object: [S1]
```javascript
// Create an Array
const fruits = [
{name:"apples", quantity:300},
{name:"bananas", quantity:500},
{name:"oranges", quantity:200},
{name:"kiwi", quantity:150}
];
// Callback function to Group Elements
function myCallback({ quantity }) {
return quantity > 200 ? "ok" : "low";
}
// Group by Quantity
const result = Map.groupBy(fruits, myCallback);
```
**Map Methods and Properties** [S1]
| Method | Description |
|--------|-------------|
| new Map() | Creates a new Map |
| set() | Sets the value for a key in a Map |
| get() | Gets the value for a key in a Map |
| has() | Returns true if a key exists in a Map |
| delete() | Removes a Map element specified by a key |
| clear() | Removes all the elements from a Map |
| forEach() | Calls a function for each key/value pair in a Map |
| entries() | Returns an iterator object with the [key, value] pairs in a Map |
| keys() | Returns an iterator object with the keys in a Map |
| values() | Returns an iterator object of the values in a Map |
| size | Returns the number of elements in a Map |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — building a `fruits` Map, reading `size`, removing/checking with `delete()`+`has()`, iterating via `forEach()`/`entries()`/`keys()`/`values()`, summing values, using objects as keys, and grouping an array with `Map.groupBy()`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Sum all values in a Map (language: JavaScript):
```javascript
let total = 0;
for (const x of fruits.values()) {
total += x;
}
```
Group an array into a Map by a callback:
```javascript
const result = Map.groupBy(fruits, myCallback);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
Both `Object.groupBy()` and `Map.groupBy()` group an iterable by a callback's return value; choose by desired output type: `Object.groupBy()` produces a plain JavaScript object, while `Map.groupBy()` produces a Map object. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
`Map.groupBy()` is an ECMAScript 2024 addition, so older environments may need a polyfill. A common pitfall noted by the source: object keys are matched by identity, so `get("apples")` (a string) returns `undefined` when the key was the object `apples`. No contradictions found in the source. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Maps]], [[JavaScript Set Methods]], [[JavaScript Sets]]
- **참조 맥락:** Referenced whenever managing, iterating, or grouping the contents of a Map.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Map Methods — https://www.w3schools.com/js/js_map_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Map Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
+154
View File
@@ -0,0 +1,154 @@
---
id: javascript-maps
title: "JavaScript Maps"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Map", "new Map", "key-value pairs", "ES6 Map", "Map.set", "Map.get", "dictionary"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "map", "collection", "es6"]
raw_sources: ["https://www.w3schools.com/js/js_maps.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Maps]]
## 🎯 한 줄 통찰 (One-line insight)
A JavaScript Map stores key-value pairs like a dictionary, but unlike plain objects its keys can be of any data type, it remembers insertion order, and it exposes a `size` property. [S1]
## 🧠 핵심 개념 (Core concepts)
- **A Map is an object that stores key-value pairs**, similar to a dictionary in other languages; keys can be of any data type. [S1]
- **Maps are most similar to Objects** (a unique key/value collection), but with stronger guarantees. [S1]
- **Six characteristics** — keys can be any type; original insertion order is remembered; item count is easy via `size`; optimized for frequent additions/removals; directly iterable with `for...of` or `forEach()`; original order preserved during iteration. [S1]
- **Two ways to create a Map** — `new Map()` then `set()` calls, or `new Map([...])` with an array of `[key, value]` pairs. [S1]
- **`set()` adds or updates** — calling `set()` with an existing key changes its value. [S1]
- **`get()` retrieves a value** by its key. [S1]
- **Type identity** — `typeof` a Map returns `"object"`, and `instanceof Map` returns `true`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **set-chain construction** — create empty, then `set()` each pair. [S1]
- **Array-literal construction** — pass `[[k, v], ...]` to `new Map()`. [S1]
- **Upsert by key** — `set()` doubles as insert (new key) and update (existing key). [S1]
## 📖 세부 내용 (Details)
A JavaScript Map is an object that can store collections of key-value pairs, similar to a dictionary in other programming languages. Maps differ from standard objects in that keys can be of any data type. Maps are similar to both Objects (unique key/value collection) and Arrays (ordered values collection), but Maps are most similar to Objects. [S1]
**Map characteristics:** keys can be any type; the original insertion order is remembered; the number of items is easily retrieved via the `size` property; optimized for frequent additions and removals; directly iterable with `for...of` loops or `forEach()`; original order preserved during iteration. [S1]
**How to Create a Map** — you can create a Map by passing an Array to `new Map()`, or by creating a Map and using `set()`. [S1]
**Using set()** — create an empty Map and set values: [S1]
```javascript
// Create an empty Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
```
**Using an Array** — pass an array of `[key, value]` pairs to the constructor: [S1]
```javascript
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
```
**Adding Elements** — the `set()` method can also be used to add new elements: [S1]
```javascript
fruits.set("mangos", 100);
```
**Changing Values**`set()` will also change existing values: [S1]
```javascript
fruits.set("apples", 200);
```
**The get() Method** — gets the value of a key: [S1]
```javascript
fruits.get("apples"); // Returns 500
```
**A JavaScript Map is an Object** [S1]
```javascript
// Returns object:
typeof fruits;
```
```javascript
// Returns true:
fruits instanceof Map;
```
**JavaScript Objects vs Maps** [S1]
| | Object | Map |
|---|--------|-----|
| Iterable | Not directly iterable | Directly iterable |
| Size property | Do not have a size property | Have a size property |
| Key types | Keys must be Strings (or Symbols) | Keys can be any datatype |
| Key ordering | Keys are not well ordered | Keys are ordered by insertion |
| Default keys | Have default keys | Do not have default keys |
**Browser Support** — Map is an ES6 feature (JavaScript 2015), fully supported in all modern browsers since June 2017. [S1]
| Browser | Version | Release |
|---------|---------|---------|
| Chrome | 51 | May 2016 |
| Edge | 15 | Apr 2017 |
| Firefox | 54 | Jun 2017 |
| Safari | 10 | Sep 2016 |
| Opera | 38 | Jun 2016 |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — building a `fruits` Map by `set()` calls or array literal, adding `mangos`, updating `apples`, and reading back with `get()`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Create a Map from an array of pairs (language: JavaScript):
```javascript
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
```
Upsert and read:
```javascript
fruits.set("apples", 200);
fruits.get("apples");
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
Per the source's Objects-vs-Maps table, prefer a Map over a plain Object when you need: direct iterability (`for...of`), a built-in `size`, keys of any data type (not just strings/symbols), reliable insertion ordering, or no inherited default keys. Use a plain Object for simple string-keyed records where those guarantees are not required. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Map Methods]], [[JavaScript Sets]], [[JavaScript Set Methods]]
- **참조 맥락:** The base concept referenced whenever an ordered, any-key key-value collection is needed.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Maps — https://www.w3schools.com/js/js_maps.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Maps" page (Astra wiki-curation, P-Reinforce v3.1 format).
+148
View File
@@ -0,0 +1,148 @@
---
id: javascript-math
title: "JavaScript Math"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Math object", "Math.round", "Math.PI", "Math methods", "Math.pow", "Math.random"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "math", "numbers"]
raw_sources: ["https://www.w3schools.com/js/js_math.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Math]]
## 🎯 한 줄 통찰 (One-line insight)
The JavaScript `Math` object provides mathematical constants (like `Math.PI`, `Math.E`) and methods (rounding, powers, roots, trig, min/max, random) that operate on numbers without needing to be instantiated. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`Math` is a static object** — it exposes constants and methods directly (e.g. `Math.PI`, `Math.round(x)`), not via instances. [S1]
- **Rounding family** — `round` (nearest integer), `ceil` (up), `floor` (down), and `trunc` (integer part). [S1]
- **`Math.sign(x)`** returns whether `x` is negative, null, or positive. [S1]
- **Powers and roots** — `Math.pow(x, y)` is x to the power y; `Math.sqrt(x)` is the square root. [S1]
- **`Math.abs(x)`** returns the absolute (positive) value. [S1]
- **Trig** — `Math.sin(x)` / `Math.cos(x)` take an angle in radians (convert from degrees with `* Math.PI / 180`). [S1]
- **`Math.min()` / `Math.max()`** find the lowest / highest value in a list of arguments. [S1]
- **`Math.random()`** returns a random number between 0 (inclusive) and 1 (exclusive). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Degrees → radians** — multiply by `Math.PI / 180` before passing to `Math.sin`/`Math.cos`. [S1]
- **Rounding choice** — pick `round`/`ceil`/`floor`/`trunc` per the rounding behavior you need. [S1]
- **Min/max over a list** — call `Math.min(...)`/`Math.max(...)` with multiple numeric arguments. [S1]
## 📖 세부 내용 (Details)
**The Math Object** — The `Math` object allows you to perform mathematical tasks on numbers. Unlike other objects, the `Math` object has no constructor; it is static and its methods and properties are accessed directly. [S1]
**Math Properties (constants)** — [S1]
| Property | Description |
|----------|-------------|
| `Math.E` | Returns Euler's number |
| `Math.PI` | Returns PI |
| `Math.SQRT2` | Returns the square root of 2 |
| `Math.SQRT1_2` | Returns the square root of 1/2 |
| `Math.LN2` | Returns the natural logarithm of 2 |
| `Math.LN10` | Returns the natural logarithm of 10 |
| `Math.LOG2E` | Returns base 2 logarithm of E |
| `Math.LOG10E` | Returns base 10 logarithm of E |
**Math Methods** — selected methods documented on the page: [S1]
| Method | Description |
|--------|-------------|
| `Math.round(x)` | Returns x rounded to its nearest integer |
| `Math.ceil(x)` | Returns x rounded up to its nearest integer |
| `Math.floor(x)` | Returns x rounded down to its nearest integer |
| `Math.trunc(x)` | Returns the integer part of x |
| `Math.sign(x)` | Returns if x is negative, null or positive |
| `Math.pow(x, y)` | Returns the value of x to the power of y |
| `Math.sqrt(x)` | Returns the square root of x |
| `Math.abs(x)` | Returns the absolute (positive) value of x |
| `Math.sin(x)` | Returns the sine of the angle x |
| `Math.cos(x)` | Returns the cosine of the angle x |
| `Math.min()` | Can be used to find the lowest value in a list |
| `Math.max()` | Can be used to find the highest value in a list |
| `Math.random()` | Returns a random number between 0 (inclusive), and 1 (exclusive) |
| `Math.log(x)` | Returns the natural logarithm of x |
| `Math.log2(x)` | Returns the base 2 logarithm of x |
| `Math.log10(x)` | Returns the base 10 logarithm of x |
**Example expressions and their results** — as shown on the page: [S1]
| Expression | Result |
|------------|--------|
| `Math.round(4.6)` | 5 |
| `Math.round(4.5)` | 4 |
| `Math.round(4.4)` | 4 |
| `Math.ceil(4.9)` | 5 |
| `Math.floor(4.9)` | 4 |
| `Math.trunc(4.9)` | 4 |
| `Math.sign(-4)` | -1 |
| `Math.pow(8, 2)` | 64 |
| `Math.sqrt(64)` | 8 |
| `Math.abs(-4.7)` | 4.7 |
| `Math.sin(90 * Math.PI / 180)` | 1 |
| `Math.cos(0 * Math.PI / 180)` | 1 |
| `Math.min(0, 150, 30, 20, -8, -200)` | -200 |
| `Math.max(0, 150, 30, 20, -8, -200)` | 150 |
| `Math.random()` | A number between 0 (inclusive) and 1 (exclusive) |
> Note: The full source presents these expressions inside interactive "Try it Yourself" Example boxes. The expressions and results above are reproduced from the page; any code that exists only inside the Try-it editor without a printed expression is "Not found in source".
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — rounding 4.x values, computing `Math.pow(8, 2)`, taking `Math.sqrt(64)`, converting degrees to radians for `Math.sin`/`Math.cos`, and finding min/max over a list. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Round to nearest / up / down / truncate:
```javascript
Math.round(4.6); // 5
Math.ceil(4.9); // 5
Math.floor(4.9); // 4
Math.trunc(4.9); // 4
```
Power, square root, absolute value:
```javascript
Math.pow(8, 2); // 64
Math.sqrt(64); // 8
Math.abs(-4.7); // 4.7
```
Degrees to radians for trig:
```javascript
Math.sin(90 * Math.PI / 180); // 1
Math.cos(0 * Math.PI / 180); // 1
```
Min / max over a list:
```javascript
Math.min(0, 150, 30, 20, -8, -200); // -200
Math.max(0, 150, 30, 20, -8, -200); // 150
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Random]], [[JavaScript Numbers]], [[JavaScript Array Sort]]
- **참조 맥락:** Referenced whenever numeric computation, rounding, or randomness is needed.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Math — https://www.w3schools.com/js/js_math.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Math" page (Astra wiki-curation, P-Reinforce v3.1 format).
+136
View File
@@ -0,0 +1,136 @@
---
id: javascript-nan
title: "JavaScript NaN"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["NaN", "Not a Number", "JS NaN", "isNaN", "invalid number"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "nan", "numbers"]
raw_sources: ["https://www.w3schools.com/js/js_nan.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript NaN]]
## 🎯 한 줄 통찰 (One-line insight)
`NaN` ("Not a Number") is a JavaScript number-type value produced when a calculation cannot yield a valid number, and it is the only JavaScript value that is not equal to itself. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Produced by invalid math** — You get `NaN` when JavaScript cannot calculate a number (e.g. `100 / "Apple"`). [S1]
- **Its type is `number`** — The type of `NaN` is `number`; though it means "not a number," it belongs to the JavaScript number type. [S1]
- **Numeric strings convert** — JavaScript tries to convert numeric strings to numbers in arithmetic operations, so `100 / "10"` is `10`. [S1]
- **Non-numeric strings yield NaN** — A non-numeric string cannot be converted to a number, so the result is `NaN`. [S1]
- **`isNaN()` detects it** — Use the `isNaN()` function to find out if a value is not a number. [S1]
- **Not equal to itself** — `NaN` is the only JavaScript value that is not equal to itself; `NaN == NaN` is `false`. [S1]
- **Propagates through math** — If you use `NaN` in a mathematical operation, the result will also be `NaN`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Never compare with `==`** — Because `NaN != NaN`, test for it with `isNaN()` rather than equality. [S1]
- **Coerce-then-compute** — Arithmetic implicitly coerces string operands to numbers; convertible strings work, non-convertible ones poison the result with `NaN`. [S1]
- **NaN contamination** — Any arithmetic involving `NaN` returns `NaN`, so a single bad value can spread through a calculation chain. [S1]
## 📖 세부 내용 (Details)
**Invalid Number Operations**
You get `NaN` when JavaScript cannot calculate a number. [S1]
```javascript
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = x;
```
**NaN is a Number**
The type of `NaN` is `number`. This may look strange, but `NaN` belongs to the JavaScript number type. [S1]
```javascript
let x = NaN;
document.getElementById("demo").innerHTML = typeof x;
```
**Numeric Strings**
JavaScript tries to convert numeric strings to numbers in arithmetic operations. The result is `10`, because `"10"` is converted to the number `10`. [S1]
```javascript
let x = 100 / "10";
document.getElementById("demo").innerHTML = x;
```
**Non-Numeric Strings**
A non-numeric string cannot be converted to a number. The result is `NaN`, because `"Apple"` cannot be converted to a number. [S1]
```javascript
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = x;
```
**Using isNaN()**
You can use the JavaScript function `isNaN()` to find out if a value is not a number. [S1]
```javascript
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
```
**NaN is Not Equal to Itself**
`NaN` is the only JavaScript value that is not equal to itself. To test for `NaN`, use `isNaN()`. [S1]
```javascript
let x = NaN;
document.getElementById("demo").innerHTML = x == x;
```
**NaN in Math**
If you use `NaN` in a mathematical operation, the result will also be `NaN`. [S1]
```javascript
let x = NaN;
let y = 5;
document.getElementById("demo").innerHTML = x + y;
```
**Note**
`NaN` means "Not a Number." However, the type of `NaN` is `number`. Use `isNaN()` to check if a value is `NaN`. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `100 / "Apple"` producing `NaN`, `typeof NaN` returning `"number"`, and `isNaN(x)` testing the result. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Test whether a value is NaN (language: JavaScript):
```javascript
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
```
Observe that NaN is not equal to itself:
```javascript
let x = NaN;
document.getElementById("demo").innerHTML = x == x;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. (Note the deliberate counter-intuitive facts the page calls out: `typeof NaN` is `"number"`, and `NaN == NaN` is `false`.)
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript undefined]], [[JavaScript Type Coercion]], [[JavaScript Type Conversion]], [[JavaScript Introduction]]
- **참조 맥락:** Referenced whenever validating numeric input or guarding arithmetic against invalid values.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript NaN — https://www.w3schools.com/js/js_nan.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript NaN" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,238 @@
---
id: javascript-number-methods
title: "JavaScript Number Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["number methods", "toFixed", "toPrecision", "Number()", "parseInt", "parseFloat"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "numbers", "number-methods", "parsing"]
raw_sources: ["https://www.w3schools.com/js/js_number_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Number Methods]]
## 🎯 한 줄 통찰 (One-line insight)
Basic number methods (`toString`, `toExponential`, `toFixed`, `toPrecision`, `valueOf`) work on any number, while static `Number.*` methods (`isInteger`, `isFinite`, `isNaN`, `isSafeInteger`, `parseInt`, `parseFloat`) can only be used on `Number` itself. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Basic methods work on any number** — `toString()`, `toExponential()`, `toFixed()`, `toPrecision()`, `valueOf()`. [S1]
- **Static methods only on `Number`** — `Number.isFinite()`, `Number.isInteger()`, `Number.isNaN()`, `Number.isSafeInteger()`, `Number.parseInt()`, `Number.parseFloat()`. [S1]
- **`toString()`** — returns a number as a string; accepts a radix. [S1]
- **`toFixed()`** — returns a string with a specified number of decimals; perfect for working with money. [S1]
- **`toPrecision()`** — returns a string with a number written to a specified length. [S1]
- **Conversion functions** — `Number()`, `parseInt()`, `parseFloat()` convert variables to numbers; `NaN` is returned when conversion fails. [S1]
- **Methods cannot be used on variables for statics** — `Number.isInteger()` etc. must be called on `Number`; calling on a variable throws a TypeError. [S1]
- **Safe integers** — range is -(2⁵³ - 1) to +(2⁵³ - 1); `9007199254740991` is safe, `9007199254740992` is not. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Format money** — `value.toFixed(2)` to render two decimal places. [S1]
- **Parse leading number from text** — `parseInt("10 years")` / `parseFloat("10.33")` extract a number from the front of a string. [S1]
- **Validate before use** — `Number.isInteger()` / `Number.isSafeInteger()` / `Number.isNaN()` to check values. [S1]
## 📖 세부 내용 (Details)
**Basic Methods** can be used on any number: `toString()`, `toExponential()`, `toFixed()`, `toPrecision()`, `valueOf()`. **Static Methods** can only be used on `Number`: `Number.isFinite()`, `Number.isInteger()`, `Number.isNaN()`, `Number.isSafeInteger()`, `Number.parseInt()`, `Number.parseFloat()`. [S1]
**toString()** — returns a number as a string; can take a radix. [S1]
```javascript
let x = 123;
x.toString();
(123).toString();
(100 + 23).toString();
```
```javascript
let x = 123;
let text = x.toString(2);
```
**toExponential()** — returns a string with a number rounded and written using exponential notation. [S1]
```javascript
let x = 9.656;
x.toExponential(2);
x.toExponential(4);
x.toExponential(6);
```
**toFixed()** — returns a string with the number written with a specified number of decimals; perfect for working with money. [S1]
```javascript
let x = 9.656;
x.toFixed(0);
x.toFixed(2);
x.toFixed(4);
x.toFixed(6);
```
**toPrecision()** — returns a string with a number written with a specified length. [S1]
```javascript
let x = 9.656;
x.toPrecision();
x.toPrecision(2);
x.toPrecision(4);
x.toPrecision(6);
```
**valueOf()** — returns a number as a number; used internally in JavaScript to convert Number objects to primitive values. [S1]
```javascript
let x = 123;
x.valueOf();
(123).valueOf();
(100 + 23).valueOf();
```
**Converting Variables to Numbers** — three methods are available: [S1]
| Method | Description |
|--------|-------------|
| Number() | Converts argument to number |
| parseFloat() | Parses argument, returns floating point |
| parseInt() | Parses argument, returns whole number |
**Number()** — converts its argument to a number. [S1]
```javascript
Number(true);
Number(false);
Number("10");
Number(" 10");
Number("10 ");
Number(" 10 ");
Number("10.33");
Number("10,33");
Number("10 33");
Number("John");
```
**Number() Used on Dates** — converts a date to milliseconds. [S1]
```javascript
Number(new Date("1970-01-01"))
```
```javascript
Number(new Date("1970-01-02"))
```
```javascript
Number(new Date("2017-09-30"))
```
**parseInt()** — parses and returns a whole number. [S1]
```javascript
parseInt("-10");
parseInt("-10.33");
parseInt("10");
parseInt("10.33");
parseInt("10 20 30");
parseInt("10 years");
parseInt("years 10");
```
**parseFloat()** — parses and returns a floating point number. [S1]
```javascript
parseFloat("10");
parseFloat("10.33");
parseFloat("10 20 30");
parseFloat("10 years");
parseFloat("years 10");
```
**Number Object Methods** (static): [S1]
| Method | Description |
|--------|-------------|
| Number.isInteger() | Returns true if argument is integer |
| Number.isNaN() | Returns true if argument is NaN |
| Number.isFinite() | Returns true if not Infinity or NaN |
| Number.isSafeInteger() | Returns true if safe integer |
| Number.parseFloat() | Converts string to number |
| Number.parseInt() | Converts string to whole number |
Number methods can only be accessed like `Number.isInteger()`; calling them on a variable produces a TypeError ("X.isInteger is not a function"). `Number.isNaN()` is the preferred way to check for equality with NaN. [S1]
**Number.isInteger()** [S1]
```javascript
Number.isInteger(10);
Number.isInteger(10.5);
```
**Number.isFinite()** [S1]
```javascript
Number.isFinite(123);
```
**Number.isNaN()** [S1]
```javascript
Number.isNaN(123);
```
**Number.isSafeInteger()** — safe integer range is -(2⁵³ - 1) to +(2⁵³ - 1). [S1]
```javascript
Number.isSafeInteger(10);
Number.isSafeInteger(12345678901234567890);
```
**Number.parseFloat()** [S1]
```javascript
Number.parseFloat("10");
Number.parseFloat("10.33");
Number.parseFloat("10 20 30");
Number.parseFloat("10 years");
Number.parseFloat("years 10");
```
**Number.parseInt()** [S1]
```javascript
Number.parseInt("-10");
Number.parseInt("-10.33");
Number.parseInt("10");
Number.parseInt("10.33");
Number.parseInt("10 20 30");
Number.parseInt("10 years");
Number.parseInt("years 10");
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — formatting `9.656` with `toFixed`/`toPrecision`/`toExponential`, converting strings and dates with `Number()`, parsing with `parseInt`/`parseFloat`, and validating with the static `Number.*` methods. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Format for money:
```javascript
let x = 9.656;
x.toFixed(2);
```
Parse a number from text:
```javascript
parseInt("10 years");
parseFloat("10.33");
```
Validate a value:
```javascript
Number.isInteger(10);
Number.isSafeInteger(9007199254740991);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`Number()` vs `parseInt()` vs `parseFloat()`** — `Number()` converts the whole argument (returns NaN if it is not fully numeric, e.g. `"10 33"`); `parseInt()` returns a whole number from the leading numeric portion; `parseFloat()` returns a floating point from the leading numeric portion. [S1]
- **Basic vs static methods** — basic methods (`toFixed`, etc.) are called on a number value; static methods (`Number.isInteger`, etc.) must be called on `Number` itself or they throw a TypeError. [S1]
- **`Number.isNaN()` is preferred** for checking equality with NaN. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Numbers]], [[JavaScript Number Properties]], [[JavaScript Data Types]], [[JavaScript Operators]]
- **참조 맥락:** Referenced whenever formatting numbers for display or converting strings/dates into numeric values.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Number Methods — https://www.w3schools.com/js/js_number_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Number Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,155 @@
---
id: javascript-number-properties
title: "JavaScript Number Properties"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Number properties", "Number.MAX_VALUE", "Number.EPSILON", "MAX_SAFE_INTEGER", "POSITIVE_INFINITY", "Number.NaN"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "number", "constants"]
raw_sources: ["https://www.w3schools.com/js/js_number_properties.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Number Properties]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript Number properties are static constants on the `Number` object that expose the limits of the language's numeric type — its largest, smallest, safe-integer bounds, infinities, and the not-a-number value. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Number properties are static** — they belong to the `Number` object itself and can only be accessed as `Number.PROPERTY` (for example `Number.MAX_VALUE`), never through a number variable or instance. [S1]
- **EPSILON** is the difference between 1 and the smallest floating-point number greater than 1. [S1]
- **MAX_VALUE / MIN_VALUE** are the largest and lowest possible numbers in JavaScript. [S1]
- **MAX_SAFE_INTEGER / MIN_SAFE_INTEGER** are `2⁵³ 1` and `(2⁵³ 1)` — the bounds of integers that can be represented exactly. [S1]
- **POSITIVE_INFINITY / NEGATIVE_INFINITY** are returned on numeric overflow (for example `1 / 0` and `-1 / 0`). [S1]
- **NaN** ("Not a Number") is returned by invalid arithmetic such as dividing a number by a non-numeric string. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Static access only** — reach a property as `Number.MAX_VALUE`; reading the same name off a variable (`x.MAX_VALUE`) yields `undefined`. [S1]
- **Overflow → Infinity** — operations that exceed the representable range produce `Infinity` rather than throwing an error. [S1]
- **Invalid arithmetic → NaN** — mixing a number with a non-numeric string in arithmetic produces `NaN`. [S1]
## 📖 세부 내용 (Details)
Number properties belong to the JavaScript `Number` object. These properties can only be accessed as `Number.MAX_VALUE` (statically), not on a variable. [S1]
**JavaScript EPSILON** — the difference between 1 and the smallest floating-point number greater than 1: [S1]
```javascript
let x = Number.EPSILON;
```
**JavaScript MAX_VALUE** — the largest possible number in JavaScript: [S1]
```javascript
let x = Number.MAX_VALUE;
```
**Number Properties Cannot be Used on Variables** — accessing a property name on a number variable returns `undefined`: [S1]
```javascript
let x = 6;
x.MAX_VALUE
```
**JavaScript MIN_VALUE** — the lowest possible number in JavaScript: [S1]
```javascript
let x = Number.MIN_VALUE;
```
**JavaScript MIN_SAFE_INTEGER**`(2⁵³ 1)`: [S1]
```javascript
let x = Number.MIN_SAFE_INTEGER;
```
**JavaScript MAX_SAFE_INTEGER**`2⁵³ 1`: [S1]
```javascript
let x = Number.MAX_SAFE_INTEGER;
```
**JavaScript POSITIVE_INFINITY** — accessed as a property: [S1]
```javascript
let x = Number.POSITIVE_INFINITY;
```
`POSITIVE_INFINITY` is returned on overflow: [S1]
```javascript
let x = 1 / 0;
```
**JavaScript NEGATIVE_INFINITY** — accessed as a property: [S1]
```javascript
let x = Number.NEGATIVE_INFINITY;
```
`NEGATIVE_INFINITY` is returned on overflow: [S1]
```javascript
let x = -1 / 0;
```
**JavaScript NaN — Not a Number** — accessed as a property: [S1]
```javascript
let x = Number.NaN;
```
`NaN` also results from invalid arithmetic, such as dividing by a non-numeric string: [S1]
```javascript
let x = 100 / "Apple";
```
**Property summary table** [S1]
| Property | Description |
|----------|-------------|
| `Number.EPSILON` | The difference between 1 and the smallest floating-point number greater than 1 |
| `Number.MAX_VALUE` | The largest possible number in JavaScript |
| `Number.MIN_VALUE` | The lowest possible number in JavaScript |
| `Number.MAX_SAFE_INTEGER` | The maximum safe integer (`2⁵³ 1`) |
| `Number.MIN_SAFE_INTEGER` | The minimum safe integer (`(2⁵³ 1)`) |
| `Number.POSITIVE_INFINITY` | Returned on overflow (e.g. `1 / 0`) |
| `Number.NEGATIVE_INFINITY` | Returned on negative overflow (e.g. `-1 / 0`) |
| `Number.NaN` | Not a Number (e.g. `100 / "Apple"`) |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — accessing each constant via `Number.*` and demonstrating overflow (`1 / 0`) and invalid arithmetic (`100 / "Apple"`). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Access a static Number property (language: JavaScript):
```javascript
let x = Number.MAX_VALUE;
let y = Number.MAX_SAFE_INTEGER;
```
Trigger Infinity through overflow:
```javascript
let x = 1 / 0;
let y = -1 / 0;
```
Produce NaN through invalid arithmetic:
```javascript
let x = 100 / "Apple";
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Numbers]], [[JavaScript Number Methods]], [[JavaScript BigInt]], [[JavaScript Bitwise]]
- **참조 맥락:** Referenced when checking numeric limits, detecting overflow, or guarding against unsafe integers.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Number Properties — https://www.w3schools.com/js/js_number_properties.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Number Properties" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,270 @@
---
id: javascript-numbers
title: "JavaScript Numbers"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["numbers", "JS numbers", "floating point", "NaN", "Infinity", "IEEE 754"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "numbers", "floating-point", "nan"]
raw_sources: ["https://www.w3schools.com/js/js_numbers.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Numbers]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript has only one number type — a 64-bit IEEE 754 double — so integers are precise only to 15 digits, floating-point arithmetic can be imprecise, and special values `NaN` and `Infinity` are themselves of type `number`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **One number type** — JavaScript has only one type of number; numbers can be written with or without decimals, and scientific notation (`123e5`) is allowed. [S1]
- **Always 64-bit floating point** — JavaScript numbers are always stored as double precision floating point following the IEEE 754 standard (fraction in bits 0-51, exponent in 52-62, sign in bit 63). [S1]
- **Integer precision** — integers are accurate up to 15 digits; the maximum number of decimals is 17. [S1]
- **Floating precision** — floating point arithmetic is not always 100% accurate (e.g. `0.2 + 0.1`). [S1]
- **`+` is addition AND concatenation** — numbers are added; strings are concatenated; mixing them concatenates left-to-right. [S1]
- **`NaN`** — a reserved word meaning "not a legal number"; `typeof NaN` returns `number`; use `isNaN()` to test. [S1]
- **`Infinity`** — returned when a value exceeds the largest possible number, or on division by 0; `typeof Infinity` returns `number`. [S1]
- **Hexadecimal** — constants prefixed with `0x` are interpreted as hexadecimal; `toString()` can output base 2 to base 36. [S1]
- **Numbers as objects** — `new Number()` creates an object; the page warns not to create Number objects. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Fix floating drift** — multiply and divide (`(0.2 * 10 + 0.1 * 10) / 10`) to work around floating-point imprecision. [S1]
- **Guard against NaN** — test inputs with `isNaN()` before using them in arithmetic, since `NaN` propagates through operations. [S1]
- **Force numeric addition** — beware that `"10" + 20` concatenates; ensure operands are numbers when you intend addition. [S1]
- **Base conversion** — use `number.toString(radix)` to render in binary, octal, hex, or any base 2-36. [S1]
## 📖 세부 내용 (Details)
**Number Types**
JavaScript has only one type of number. Numbers can be written with or without decimals. [S1]
```javascript
let x = 3.14; // A number with decimals
let y = 3; // A number without decimals
```
Extra large or extra small numbers can be written with scientific (exponent) notation: [S1]
```javascript
let x = 123e5; // 12300000
let y = 123e-5; // 0.00123
```
**JavaScript Numbers are Always 64-bit Floating Point**
Unlike many other languages, JavaScript does not define different number types (integers, short, long, float, etc.). Numbers are always stored as double precision floating point following IEEE 754, in 64 bits: the fraction in bits 0-51, the exponent in bits 52-62, and the sign in bit 63. [S1]
| Value (aka Fraction/Mantissa) | Exponent | Sign |
|---|---|---|
| 52 bits (0 - 51) | 11 bits (52 - 62) | 1 bit (63) |
JavaScript numbers are always double (64-bit floating point). [S1]
**Integer Precision**
Integers (numbers without a period or exponent notation) are accurate up to 15 digits. The maximum number of decimals is 17. [S1]
```javascript
let x = 999999999999999; // x will be 999999999999999
let y = 9999999999999999; // y will be 10000000000000000
```
**Floating Precision**
Floating point arithmetic is not always 100% accurate: [S1]
```javascript
let x = 0.2 + 0.1;
```
To solve the problem above, it helps to multiply and divide: [S1]
```javascript
let x = (0.2 * 10 + 0.1 * 10) / 10;
```
**Adding Numbers and Strings**
> Warning: JavaScript uses the `+` operator for both addition and concatenation. Numbers are added. Strings are concatenated. [S1]
Adding two numbers gives a number: [S1]
```javascript
let x = 10;
let y = 20;
let z = x + y;
```
Adding two strings gives a concatenation: [S1]
```javascript
let x = "10";
let y = "20";
let z = x + y;
```
Adding a number and a string gives a concatenation: [S1]
```javascript
let x = 10;
let y = "20";
let z = x + y;
```
Adding a string and a number gives a concatenation: [S1]
```javascript
let x = "10";
let y = 20;
let z = x + y;
```
A common mistake is to expect this to be 30: [S1]
```javascript
let x = 10;
let y = 20;
let z = "The result is: " + x + y;
```
A common mistake is to expect this to be 102030: [S1]
```javascript
let x = 10;
let y = 20;
let z = "30";
let result = x + y + z;
```
The JavaScript interpreter works from left to right. First `10 + 20` is added because `x` and `y` are both numbers; then `30 + "30"` is concatenated because `z` is a string. [S1]
**Numeric Strings**
JavaScript will try to convert strings to numbers in numeric operations. Division, multiplication, and subtraction work; addition concatenates. [S1]
```javascript
let x = "100";
let y = "10";
let z = x / y;
```
```javascript
let x = "100";
let y = "10";
let z = x * y;
```
```javascript
let x = "100";
let y = "10";
let z = x - y;
```
This will NOT work (it concatenates): [S1]
```javascript
let x = "100";
let y = "10";
let z = x + y;
```
**NaN - Not a Number**
`NaN` is a JavaScript reserved word indicating that a number is not a legal number. Arithmetic with a non-numeric string yields `NaN`: [S1]
```javascript
let x = 100 / "Apple";
```
If the string is numeric, the result is a number: [S1]
```javascript
let x = 100 / "10";
```
Use `isNaN()` to test: [S1]
```javascript
let x = 100 / "Apple";
isNaN(x);
```
`NaN` propagates through math: [S1]
```javascript
let x = NaN;
let y = 5;
let z = x + y;
```
Or it concatenates like `NaN5`: [S1]
```javascript
let x = NaN;
let y = "5";
let z = x + y;
```
`typeof NaN` returns `number`: [S1]
```javascript
typeof NaN;
```
**Infinity**
`Infinity` (or `-Infinity`) is returned for a number outside the largest possible number. [S1]
```javascript
let myNumber = 2;
// Execute until Infinity
while (myNumber != Infinity) {
myNumber = myNumber * myNumber;
}
```
Division by 0 also generates `Infinity`: [S1]
```javascript
let x = 2 / 0;
let y = -2 / 0;
```
`typeof Infinity` returns `number`: [S1]
```javascript
typeof Infinity;
```
**Hexadecimal**
JavaScript interprets numeric constants as hexadecimal if they are preceded by `0x`. [S1]
```javascript
let x = 0xFF;
```
Never write a number with a leading zero (like `07`); some versions interpret it as octal. By default JavaScript displays numbers as base 10, but `toString()` can output base 2 to base 36 (hex = base 16, decimal = base 10, octal = base 8, binary = base 2): [S1]
```javascript
let myNumber = 32;
myNumber.toString(32);
myNumber.toString(16);
myNumber.toString(12);
myNumber.toString(10);
myNumber.toString(8);
myNumber.toString(2);
```
**JavaScript Numbers as Objects**
Numbers are normally primitive values from literals, but can be defined as objects with `new`: [S1]
```javascript
let x = 123;
let y = new Number(123);
```
> Warning: Do not create Number objects. The `new` keyword complicates the code and slows down execution speed. [S1]
With `==`, a primitive and a Number object are equal; with `===` they are not equal; and comparing two Number objects always returns false: [S1]
```javascript
let x = 500;
let y = new Number(500);
```
```javascript
let x = new Number(500);
let y = new Number(500);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — demonstrating integer precision limits, the `0.2 + 0.1` floating drift fix, `+` concatenation pitfalls, `isNaN()` checks, the `Infinity` loop, and `toString(radix)` base conversions. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Work around floating drift:
```javascript
let x = (0.2 * 10 + 0.1 * 10) / 10;
```
Detect a non-number:
```javascript
isNaN(100 / "Apple");
```
Convert to another base:
```javascript
(32).toString(2); // binary
(32).toString(16); // hexadecimal
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
Note that `0.2 + 0.1` does not produce exactly `0.3` due to IEEE 754 floating point; the page presents the multiply/divide workaround. No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Number Methods]], [[JavaScript Data Types]], [[JavaScript Operators]], [[JavaScript BigInt]]
- **참조 맥락:** The foundation for all numeric computation and the precision pitfalls behind money/financial calculations.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Numbers — https://www.w3schools.com/js/js_numbers.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Numbers" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,161 @@
---
id: javascript-object-constructors
title: "JavaScript Object Constructors"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Object constructor function", "constructor function", "new keyword", "Person constructor", "prototype property"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "constructors", "prototype"]
raw_sources: ["https://www.w3schools.com/js/js_object_constructors.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object Constructors]]
## 🎯 한 줄 통찰 (One-line insight)
A constructor function is a reusable "object type" blueprint: call it with `new` to stamp out many objects of the same kind, where `this` becomes each new object. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Constructor functions are object blueprints** — when you need many objects of the same type, define a constructor function and create instances with the `new` keyword. [S1]
- **Naming convention** — it is considered good practice to name constructor functions with an upper-case first letter (e.g. `Person`). [S1]
- **`this` inside a constructor** — `this` has no value of its own; it becomes the new object being created when the function is invoked with `new`. [S1]
- **Prototype changes affect all instances** — a property or method added to `Constructor.prototype` is shared by every object created from that constructor, whereas a property added to one object affects only that object. [S1]
- **Use literals over built-in constructors** — JavaScript has built-in constructors (`new Object()`, `new Array()`, etc.), but the recommended best practice is to use the literal forms instead. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Capitalized constructor + `new`** — define `function Person(...) { this.x = ... }` and instantiate with `const p = new Person(...)`. [S1]
- **Default property in the constructor** — assign a constant property inside the constructor body (`this.nationality = "English";`) so every instance gets it. [S1]
- **Per-object vs. shared** — `obj.prop = value` adds to one object; `Constructor.prototype.prop = value` adds to all. [S1]
- **Method as a property** — attach a function expression to `this` (`this.fullName = function() {...}`) to give instances a method. [S1]
## 📖 세부 내용 (Details)
**Object Type (constructor function)**
When you want to create many objects of the same type, you can use an object constructor function. It is considered good practice to name constructor functions with an upper-case first letter. The example below defines a `Person` object type: [S1]
```javascript
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
```
**Creating objects with `new`**
Once the object type exists, you create new objects of that type with the `new` keyword: [S1]
```javascript
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
const mySelf = new Person("Johnny", "Rally", 22, "green");
```
**Property Default Values**
A value assigned to a property inside the constructor becomes a default value for all objects created from it: [S1]
```javascript
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
```
**Adding a Property to an Object**
Adding a property to a created object is easy, but it is added only to that single object — not to other objects of the same type: [S1]
```javascript
myFather.nationality = "English";
```
**Adding a Property via Prototype**
Adding a property to the constructor's prototype adds it to all objects created from the constructor: [S1]
```javascript
Person.prototype.nationality = "English";
```
**Constructor Method**
A method is a function defined as a property of the object. Methods can be defined inside the constructor: [S1]
```javascript
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
```
**Built-in JavaScript Constructors**
JavaScript has built-in constructors for native objects: [S1]
```javascript
new Object(); // A new Object object
new Array(); // A new Array object
new Map(); // A new Map object
new Set(); // A new Set object
new Date(); // A new Date object
new RegExp(); // A new RegExp object
new Function(); // A new Function object
```
Best practice: there is no reason to use these built-in constructors. Use the literal equivalents instead — `{}` for `new Object()`, `[]` for `new Array()`, `/()/` for `new RegExp()`, and `function (){}` for `new Function()`. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's `Person` examples are the canonical applied use: defining an object type once and creating multiple instances (`myFather`, `myMother`, `mySister`, `mySelf`) from it, then extending them with default properties, prototype properties, and methods. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Define a constructor and instantiate (language: JavaScript):
```javascript
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
const myFather = new Person("John", "Doe", 50, "blue");
```
Share across all instances via prototype:
```javascript
Person.prototype.nationality = "English";
```
Add a method:
```javascript
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Constructor vs. object literal** — use a constructor function when you need *many* objects of the same type; for a one-off object, a literal `{}` is simpler. [S1]
- **Per-object property vs. prototype property** — add to the object directly for an instance-specific value; add to the prototype to share across all instances. [S1]
- **Built-in constructor vs. literal** — prefer literals (`{}`, `[]`, `/()/`, `function(){}`) over `new Object()`, `new Array()`, etc. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Objects]], [[JavaScript Object Properties]], [[JavaScript Object Methods]], [[JavaScript Object Prototypes]]
- **참조 맥락:** Referenced whenever you need a reusable object template instead of a single object literal.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object Constructors — https://www.w3schools.com/js/js_object_constructors.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object Constructors" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,114 @@
---
id: javascript-object-data-types
title: "JavaScript Object Data Types"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS object types", "built-in objects", "object literal", "Array Map Set Date", "non-primitive types"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "data-types", "built-in-objects"]
raw_sources: ["https://www.w3schools.com/js/js_datatypes_objects.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object Data Types]]
## 🎯 한 줄 통찰 (One-line insight)
The Object is JavaScript's single non-primitive type — written with curly braces as comma-separated name:value pairs — and underlies many built-in object types such as Array, Map, Set, Date, RegExp, and Promise. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Object = the non-primitive type** — JavaScript variables are either primitive or object types; objects hold complex data structures and functionality beyond the primitives. [S1]
- **Name:value pairs** — objects are written with curly braces `{}` containing name:value pairs separated by commas. [S1]
- **Arrays and Dates are objects** — arrays (`["Saab","Volvo","BMW"]`) and dates (`new Date(...)`) are object types. [S1]
- **Many built-in object types** — JavaScript provides built-in object types including Array, Map, Set, WeakMap, WeakSet, Math, Date, RegExp, Error, JSON, Promise, and various typed arrays. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Object literal** — declare structured data inline with `{ key: value, ... }`. [S1]
- **`typeof` collapses object types** — `typeof` returns `"string"` / `"number"` for primitives but treats arrays, dates, etc. uniformly as objects (see [[JavaScript typeof]] for distinguishing them). [S1]
## 📖 세부 내용 (Details)
JavaScript variables can be either primitive types or object types. Objects represent complex data structures and functionalities beyond the primitive data types. [S1]
**Object, Array, and Date** [S1]
```javascript
// Object
const person = {firstName:"John", lastName:"Doe"};
// Array Object
const cars = ["Saab", "Volvo", "BMW"];
// Date Object
const date = new Date("2022-03-25");
```
**Object literals with multiple properties**
Objects are written with curly braces, with properties as name:value pairs separated by commas: [S1]
```javascript
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
```
**Array example** [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
```
**`typeof` of primitives (for contrast)**
The `typeof` operator returns the same primitive labels regardless of the object context: [S1]
```javascript
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
```
```javascript
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
```
**Built-In Object Types**
The page lists built-in object types including Array, Map, Set, WeakMap, WeakSet, Math, Date, RegExp, Error, JSON, Promise, and various typed arrays (Int8Array through BigInt64Array). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own object/array/date literals (`person`, `cars`, `date`) are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Object literal with name:value pairs (language: JavaScript):
```javascript
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
```
Array and Date objects:
```javascript
const cars = ["Saab", "Volvo", "BMW"];
const date = new Date("2022-03-25");
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Data Types]], [[JavaScript Primitive Data Types]], [[JavaScript typeof]], [[JavaScript Symbols]]
- **참조 맥락:** Referenced whenever working with structured data — objects, arrays, dates, maps, and sets.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object Data Types — https://www.w3schools.com/js/js_datatypes_objects.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,184 @@
---
id: javascript-object-display
title: "JavaScript Object Display"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS object display", "object Object", "JSON.stringify", "Object.values", "Object.entries", "for in loop", "display object"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "display", "json"]
raw_sources: ["https://www.w3schools.com/js/js_object_display.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object Display]]
## 🎯 한 줄 통찰 (One-line insight)
Displaying a JavaScript object directly outputs `[object Object]`; to show its data, name the properties, loop over them, or convert the object with `Object.values()`/`Object.entries()`/`JSON.stringify()`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Direct display gives `[object Object]`** — this appears when you insert an object where a string is expected. [S1]
- **Name the properties** — properties can be concatenated into a string by name. [S1]
- **Loop with `for...in`** — collect property values in a loop, using `person[x]` (not `person.x`). [S1]
- **`Object.values()`** — creates an array from the property values. [S1]
- **`Object.entries()`** — makes it simple to use objects in loops as `[key, value]` pairs. [S1]
- **`JSON.stringify()`** — converts an object to a JSON-notation string; built in and supported in all browsers. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`for...in` with bracket access** — `text += person[x]` works because `x` is the loop variable holding the key. [S1]
- **Values-to-string** — `Object.values(person).toString()` flattens values into a comma-joined string. [S1]
- **Destructured entries loop** — `for (let [fruit, value] of Object.entries(fruits))` iterates key/value pairs. [S1]
## 📖 세부 내용 (Details)
**How to Display JavaScript Objects?**
Displaying a JavaScript object will output `[object Object]`. [S1]
```javascript
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
let text = person;
```
**Why do I See [object Object]?**
`[object Object]` appears when you attempt to insert an object (a data structure containing properties) into a context where a string is expected; it represents how JavaScript handles this situation. Solutions include displaying the object properties by name, in a loop, via `Object.values()`, or via `JSON.stringify()`. [S1]
**Displaying Object Properties**
The properties of an object can be added in a string: [S1]
```javascript
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Add Properties
let text = person.name + "," + person.age + "," + person.city;
```
**Using a For .. In Loop**
The properties of an object can be collected in a loop: [S1]
```javascript
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Build a Text
let text = "";
for (let x in person) {
text += person[x] + " ";
};
```
You must use `person[x]` in the loop. `person.x` will not work, because `x` is the loop variable. [S1]
**Using Object.values()**
`Object.values()` creates an array from the property values: [S1]
```javascript
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Create an Array
const myArray = Object.values(person);
// Stringify the Array
let text = myArray.toString();
```
**Using Object.entries()**
`Object.entries()` makes it simple to use objects in loops: [S1]
```javascript
const fruits = {Bananas:300, Oranges:200, Apples:500};
let text = "";
for (let [fruit, value] of Object.entries(fruits)) {
text += fruit + ": " + value + "<br>";
}
```
**Using JSON.stringify()**
JavaScript objects can be converted to a string with the JSON method `JSON.stringify()`. `JSON.stringify()` is included in JavaScript and supported in all browsers. The result is a string written in JSON notation: [S1]
```javascript
{"name":"John","age":50,"city":"New York"}
```
```javascript
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Stringify Object
let text = JSON.stringify(person);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Technique | Output shape | Use when |
| --- | --- | --- |
| Property by name | Hand-built string | You know the exact properties [S1] |
| `for...in` loop | Concatenated values | Iterate all properties generically [S1] |
| `Object.values()` | Array of values | You only need the values [S1] |
| `Object.entries()` | `[key, value]` pairs | You need both keys and values in a loop [S1] |
| `JSON.stringify()` | JSON-notation string | Serialize the whole object [S1] |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — the `[object Object]` pitfall, property-by-name concatenation, the `for...in` loop, `Object.values().toString()`, the `Object.entries()` destructured loop, and `JSON.stringify(person)`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
For...in loop (note bracket access):
```javascript
let text = "";
for (let x in person) {
text += person[x] + " ";
};
```
Entries loop with destructuring:
```javascript
for (let [fruit, value] of Object.entries(fruits)) {
text += fruit + ": " + value + "<br>";
}
```
Serialize to JSON:
```javascript
let text = JSON.stringify(person);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Objects]], [[JavaScript Object Properties]], [[JavaScript Object Methods]]
- **참조 맥락:** Referenced whenever rendering object data to the page or serializing it for transport.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object Display — https://www.w3schools.com/js/js_object_display.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object Display" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,164 @@
---
id: javascript-object-methods
title: "JavaScript Object Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS object methods", "object method", "this keyword", "method call parentheses", "fullName", "function as property"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "methods", "this"]
raw_sources: ["https://www.w3schools.com/js/js_object_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object Methods]]
## 🎯 한 줄 통찰 (One-line insight)
Methods are functions stored as object property values; call them with parentheses, and inside them `this` refers to the owning object. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Methods are actions on objects** — they are functions stored as property values. [S1]
- **`this` is the object** — in an object method, `this` refers to the object that owns the method. [S1]
- **Parentheses execute the method** — `person.fullName()` runs the function; `person.fullName` returns the function definition. [S1]
- **Add methods by assignment** — assign a function to a property to add a method. [S1]
- **Built-in methods compose** — a method can call JavaScript built-ins such as `toUpperCase()`. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **`this`-based accessor method** — `fullName: function() { return this.firstName + " " + this.lastName; }` combines own properties. [S1]
- **Late method attachment** — `person.name = function () { ... }` adds behavior to an existing object. [S1]
- **Method + built-in chaining** — wrap the result and call a built-in: `(this.firstName + " " + this.lastName).toUpperCase()`. [S1]
## 📖 세부 내용 (Details)
**What are Object Methods?**
Methods are actions that can be performed on objects. Methods are functions stored as property values. [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
```
| Property | Value |
| --- | --- |
| firstName | John |
| lastName | Doe |
| age | 50 |
| **fullName** | **function() { return this.firstName + " " + this.lastName; }** |
**The this Keyword**
In an object method, `this` refers to the object. [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
getId: function() {
return this.id;
}
};
let number = person.getId();
```
Here `this` refers to the person object; `this.id` means the `id` property of the person object. [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
```
Here `this` refers to the person object; `this.firstName` means the `firstName` property and `this.lastName` the `lastName` property. [S1]
**Accessing Object Methods**
To call an object method, add parentheses `()`. Without parentheses you get the function itself. Syntax: [S1]
```javascript
objectName.methodName()
```
If you call a method with parentheses, it executes as a function: [S1]
```javascript
name = person.fullName();
```
If you call a method without parentheses, it returns the function definition: [S1]
```javascript
name = person.fullName;
```
**Adding a Method to an Object**
You can add a method to an object by assigning a function to a property: [S1]
```javascript
// Assign person.name to a function
person.name = function () {
return this.firstName + " " + this.lastName;
};
```
Here `person.name` is a property with a function assigned to it. [S1]
**Adding a JavaScript Method**
This example uses the JavaScript `toUpperCase()` method to convert a text to uppercase: [S1]
```javascript
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
```
**Summary**
Methods are functions stored as object properties; call a method with parentheses (`person.fullName()`); in methods, `this` refers to the object; you can add methods to objects by assigning a function to a property. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — the `fullName`/`getId` methods using `this`, the parentheses-vs-no-parentheses call comparison, and late attachment of `person.name`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Method using `this`:
```javascript
fullName: function() {
return this.firstName + " " + this.lastName;
}
```
Add a method by assignment:
```javascript
person.name = function () {
return this.firstName + " " + this.lastName;
};
```
Compose with a built-in:
```javascript
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Objects]], [[JavaScript Object Properties]], [[JavaScript Object this]]
- **참조 맥락:** Referenced whenever attaching behavior to objects and reasoning about `this` inside methods.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object Methods — https://www.w3schools.com/js/js_object_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,191 @@
---
id: javascript-object-properties
title: "JavaScript Object Properties"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS object properties", "dot notation", "bracket notation", "delete property", "in operator", "nested objects", "key value pairs"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "properties", "dot-notation"]
raw_sources: ["https://www.w3schools.com/js/js_object_properties.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object Properties]]
## 🎯 한 줄 통찰 (One-line insight)
An object is a collection of `key:value` properties that can be changed, added, and deleted — accessed by dot notation, bracket notation, or an expression. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Properties are key:value pairs** — a JavaScript object is a collection of properties that can be changed, added, and deleted. [S1]
- **Three access ways** — dot notation, bracket notation, and expression (a name stored in a variable). [S1]
- **Dot notation preferred** — it is generally preferred for readability and simplicity. [S1]
- **Bracket notation when needed** — required when the property name is in a variable or is not a valid identifier (e.g. `"last-name"`). [S1]
- **`delete` removes value and property** — after deletion, accessing the property returns `undefined`. [S1]
- **`in` operator** — checks whether a property exists in an object. [S1]
- **Nested objects** — property values can be other objects, reachable by chaining dot/bracket notation. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Dynamic property access** — `person[myVariable]` resolves a property whose name is held in a variable. [S1]
- **Add-by-assignment** — assigning to a non-existent property (`person.nationality = "English"`) creates it. [S1]
- **Existence check before use** — `("firstName" in person)` guards access to optional properties. [S1]
## 📖 세부 내용 (Details)
**Properties are key:value Pairs**
A JavaScript object is a collection of properties. Properties can be changed, added, and deleted. [S1]
**Accessing JavaScript Properties**
You can access object properties by dot notation, bracket notation, or expression: [S1]
```javascript
// objectName.property
let age = person.age;
// objectName["property"]
let age = person["age"];
// objectName[expression]
let age = person[x];
```
**Dot Notation**`objectName.propertyName`: [S1]
```javascript
person.firstname + " is " + person.age;
```
**Bracket Notation**`objectName["propertyName"]`: [S1]
```javascript
person["firstname"] + " is " + person["age"];
```
In general, dot notation is preferred for readability and simplicity. Bracket notation is necessary in some cases: when the property name is stored in a variable (`person[myVariable]`), or when the property name is not a valid identifier (`person["last-name"]`). Bracket notation is useful when the property name is stored in a variable: [S1]
```javascript
let n1 = "firstName";
let n2 = "lastName";
let name = person[n2] + " " + person[n2];
```
**Changing Properties** — you can change the value of a property: [S1]
```javascript
person.age = 10;
```
**Adding New Properties** — add a new property by simply giving it a value: [S1]
```javascript
person.nationality = "English";
```
**Deleting Properties** — the `delete` keyword deletes a property from an object: [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
};
delete person.age;
```
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
};
delete person["age"];
```
The `delete` keyword deletes both the value and the property. After deleting, the property is removed; accessing it will return `undefined`. [S1]
**Check if a Property Exists** — use the `in` operator: [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe"
};
let result = ("firstName" in person);
```
**Nested Objects** — property values in an object can be other objects: [S1]
```javascript
myObj = {
name:"John",
age:30,
myCars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
```
You can access nested objects using dot notation or bracket notation: [S1]
```javascript
myObj.myCars.car2;
```
```javascript
myObj.myCars["car2"];
```
```javascript
myObj["myCars"]["car2"];
```
```javascript
let p1 = "myCars";
let p2 = "car2";
myObj[p1][p2];
```
**Summary**
Object properties are key:value pairs; access properties with dot notation or bracket notation; add, change, and delete properties using assignment and `delete`; use the `in` operator to check if a property exists. [S1]
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Access style | Use when | Note |
| --- | --- | --- |
| Dot notation `obj.prop` | Default | Preferred for readability and simplicity [S1] |
| Bracket notation `obj["prop"]` | Name in a variable, or not a valid identifier | e.g. `obj[myVar]`, `obj["last-name"]` [S1] |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — accessing `person.firstname`/`person["firstname"]`, dynamic access via variables, `delete person.age`, the `in` check, and nested `myObj.myCars.car2` access. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Dynamic property access via a variable:
```javascript
let n2 = "lastName";
let name = person[n2];
```
Add then delete a property:
```javascript
person.nationality = "English";
delete person.age;
```
Existence check:
```javascript
let result = ("firstName" in person);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Objects]], [[JavaScript Object Methods]], [[JavaScript Object Display]]
- **참조 맥락:** Referenced whenever reading, writing, adding, or removing data on an object.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object Properties — https://www.w3schools.com/js/js_object_properties.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object Properties" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,136 @@
---
id: javascript-object-this
title: "JavaScript Object this"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS this keyword", "this in objects", "this alone", "this in a function", "global object", "window object"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "this", "context"]
raw_sources: ["https://www.w3schools.com/js/js_object_this.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Object this]]
## 🎯 한 줄 통찰 (One-line insight)
`this` refers to the object calling a method — inside an object method it is that object, but used alone or in a regular function it refers to the global object. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`this` refers to an object** — it is used to access the object that is calling a method. [S1]
- **In an object method, `this` is the object** — it lets the method access the object's properties. [S1]
- **Reusable methods** — `this` makes it possible to use the same method with different objects. [S1]
- **`this` alone is the global object** — in a browser that is the `window` object; in strict mode it is `undefined`. [S1]
- **In a regular function, `this` is the global object** too. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Shared-method pattern** — define the same `hello()` method on multiple objects so each resolves `this.name` to its own value. [S1]
- **Property access via `this`** — `this.firstName` / `this.lastName` reach own properties from within a method. [S1]
## 📖 세부 내용 (Details)
**this in Objects**
The `this` keyword refers to an object. In JavaScript, `this` is used to access the object that is calling a method. [S1]
**this in an Object Method**
When used inside an object method, `this` refers to the object. [S1]
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
```
Here `this.firstName` refers to the `firstName` property of the person object, and `this.lastName` refers to the `lastName` property. [S1]
**Why Use this?**
The `this` keyword makes it possible to use the same method with different objects. [S1]
```javascript
const person1 = {
name: "John",
hello: function() {
return "Hello " + this.name;
}
};
const person2 = {
name: "Anna",
hello: function() {
return "Hello " + this.name;
}
};
document.getElementById("demo").innerHTML = person1.hello();
```
**this Alone**
When used alone, `this` refers to the global object. In a browser, the global object is the `window` object. In strict mode, `this` is `undefined` when used alone. [S1]
```javascript
let x = this;
document.getElementById("demo").innerHTML = x;
```
**this in a Function**
In a regular function, `this` also refers to the global object. [S1]
```javascript
function myFunction() {
return this;
}
document.getElementById("demo").innerHTML = myFunction();
```
**Summary**
In an object method, `this` refers to the object; `this` lets methods access object properties; used alone, `this` refers to the global object. [S1]
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Context | What `this` refers to |
| --- | --- |
| Inside an object method | The owning object [S1] |
| Used alone | The global object (`window` in a browser); `undefined` in strict mode [S1] |
| Inside a regular function | The global object [S1] |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — `person.fullName` using `this`, the shared `hello()` method across `person1`/`person2`, and `this` returned alone and from a regular function. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Same method, different objects:
```javascript
const person1 = { name: "John", hello: function() { return "Hello " + this.name; } };
const person2 = { name: "Anna", hello: function() { return "Hello " + this.name; } };
```
`this` alone resolves to the global object:
```javascript
let x = this;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The page notes a mode distinction: `this` used alone is the global object normally, but `undefined` in strict mode. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Object Methods]], [[JavaScript Objects]], [[JavaScript Arrow Functions]]
- **참조 맥락:** Referenced whenever reasoning about method context, and contrasted with arrow functions, which do not bind their own `this`.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Object this — https://www.w3schools.com/js/js_object_this.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Object this" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,212 @@
---
id: javascript-objects
title: "JavaScript Objects"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS objects", "object literal", "object definitions", "new Object", "key value pairs", "objects are mutable", "primitives"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "objects", "object-literal", "primitives"]
raw_sources: ["https://www.w3schools.com/js/js_objects.asp", "https://www.w3schools.com/js/js_object_definition.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Objects]]
## 🎯 한 줄 통찰 (One-line insight)
Objects are variables that can store both values and functions, and in JavaScript almost everything except primitives is an object — addressed by reference, not by value. [S1][S2]
## 🧠 핵심 개념 (Core concepts)
- **Objects store values and functions** — they are one of the most important concepts in JavaScript. [S1]
- **Key:value pairs** — an object literal is a list of property `key:value` pairs inside curly braces `{ }`. [S2]
- **Many ways to define** — object literal, the `new` keyword, an object constructor, `Object.assign()`, `Object.create()`, and `Object.fromEntries()`. [S2]
- **Objects are king** — in JavaScript almost everything is an object; all JavaScript values except primitives are objects. [S2]
- **Objects are mutable and passed by reference** — they are addressed by reference, not by value, so a "copy" actually shares the same memory. [S2]
- **Primitives are immutable** — the seven primitive types hold a single value that cannot be changed. [S2]
## 🧩 추출된 패턴 (Extracted patterns)
- **Prefer the object literal** — for readability, simplicity, and execution speed, use the object literal over `new Object()`. [S2]
- **Reference-aliasing caution** — `const x = person;` does not copy; `x` *is* `person`, so changing `x.age` changes `person.age`. [S2]
- **Build objects from data** — `Object.fromEntries()` constructs an object from iterable key/value pairs; `Object.assign()` merges sources into a target. [S2]
## 📖 세부 내용 (Details)
**What JavaScript objects are**
Objects are variables that can store both values and functions, and they are one of the most important concepts in JavaScript. The learning path covers object basics, properties (which can be changed, added, and deleted), methods (functions stored as property values), the `this` keyword (which refers to the calling object), display techniques (loops and `JSON.stringify()`), and constructors (for creating multiple objects of the same type). [S1]
**Using an Object Literal**
An object literal is a list of property `key:value` pairs inside curly braces `{ }`. [S2]
```javascript
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
```
```javascript
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
```
Note: there is no need to use `new Object()`. For readability, simplicity, and execution speed, use the object literal method. Objects written as name/value pairs are similar to associative arrays in PHP, dictionaries in Python, hash tables in C, hash maps in Java, and hashes in Ruby and Perl. [S2]
**Using the new Keyword** [S2]
```javascript
// Create an Object
const person = new Object({
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
});
```
The examples above do exactly the same. [S2]
**Object.create()**
The `Object.create()` method creates an object from an existing object. [S2]
```javascript
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe"
};
// Create new Object
const man = Object.create(person);
man.firstName = "Peter";
```
**Object.fromEntries()**
ES2019 added the `fromEntries()` method, which creates an object from iterable key/value pairs. [S2]
```javascript
const fruits = [
["apples", 300],
["pears", 900],
["bananas", 500]
];
const myObj = Object.fromEntries(fruits);
```
`fromEntries()` is an ECMAScript 2019 feature, supported in all modern browsers since January 2020. [S2]
| Browser | Version | Release Date |
| --- | --- | --- |
| Chrome | 66 | Apr 2018 |
| Edge | 79 | Jan 2020 |
| Firefox | 61 | Jun 2018 |
| Safari | 12 | Sep 2018 |
| Opera | 50 | May 2018 |
**Object.assign()**
The `Object.assign()` method copies properties from one or more source objects to a target object. [S2]
```javascript
// Create Target Object
const person1 = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Create Source Object
const person2 = {firstName: "Anne",lastName: "Smith"};
// Assign Source to Target
Object.assign(person1, person2);
```
**In JavaScript, Objects are King**
"If you understand objects, you understand JavaScript." In JavaScript, almost everything is an object: objects are objects, maths are objects, functions are objects, dates are objects, arrays are objects, maps are objects, and sets are objects. All JavaScript values, except primitives, are objects. [S2]
**JavaScript Primitives**
A primitive data type can only store a single primitive value. There are seven primitive types: [S2]
| Type | Example Value |
| --- | --- |
| `string` | "Hello" |
| `number` | 3.14 |
| `boolean` | true |
| `bigint` | 12345678901234n |
| `null` | null |
| `undefined` | undefined |
| `symbol` | symbol |
Primitive values are immutable (they are hardcoded and cannot be changed). If `x = 3.14`, you can change the value of `x`, but you cannot change the value of `3.14`. [S2]
**JavaScript Objects are Mutable**
Objects are mutable: they are addressed by reference, not by value. If `person` is an object, `const x = person;` will not create a copy of `person`. The object `x` is not a copy of `person``x` *is* `person`; they share the same memory address, and any change to `x` also changes `person`: [S2]
```javascript
//Create an Object
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
// Try to create a copy
const x = person;
// This will change age in person:
x.age = 10;
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
| Definition method | When to use | Note |
| --- | --- | --- |
| Object literal `{ }` | Default choice | Best readability, simplicity, execution speed [S2] |
| `new Object()` | Equivalent to literal | Does exactly the same; literal preferred [S2] |
| `Object.create()` | Create from an existing object | Inherits from the source object [S2] |
| `Object.assign()` | Merge sources into a target | Copies properties from source(s) [S2] |
| `Object.fromEntries()` | Build from key/value pairs | ES2019 feature [S2] |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — the `person` object literal, the `new Object()` equivalent, `Object.create()`/`Object.assign()`/`Object.fromEntries()`, and the reference-aliasing demonstration. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Preferred object literal:
```javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
```
Reference aliasing (not a copy):
```javascript
const x = person;
x.age = 10; // also changes person.age
```
Build an object from key/value pairs:
```javascript
const myObj = Object.fromEntries(fruits);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. Version notes: `Object.fromEntries()` is an ECMAScript 2019 feature supported in all modern browsers since January 2020. [S2]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.86
- **중복 검사 결과:** 신규 생성 (New discovery). Note: the js_objects.asp page is an overview/index; code detail is grounded in the linked "Object Definitions" lesson [S2].
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Object Properties]], [[JavaScript Object Methods]], [[JavaScript Object this]], [[JavaScript Object Display]]
- **참조 맥락:** The foundation for all object-related topics — properties, methods, `this`, and display.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Objects — https://www.w3schools.com/js/js_objects.asp
- [S2] W3Schools — JavaScript Object Definitions — https://www.w3schools.com/js/js_object_definition.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Objects" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,190 @@
---
id: javascript-operators
title: "JavaScript Operators"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS operators", "JavaScript operator types", "arithmetic operators", "assignment operators", "comparison operators", "logical operators", "concatenation operator"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "operators"]
raw_sources: ["https://www.w3schools.com/js/js_operators.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Operators]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript operators are used for mathematical and logical computations — the `=` assigns, `+` adds (and concatenates strings), `*` multiplies, and comparison/logical operators evaluate conditions. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Operators are for mathematical and logical computations** — they perform operations on values and variables. [S1]
- **Four core single examples** — the assignment operator `=` assigns values, the addition operator `+` adds, the multiplication operator `*` multiplies, and the comparison operator `>` compares. [S1]
- **Operator categories** — JavaScript operators include Arithmetic, Assignment, Comparison, Logical, and String operators. [S1]
- **`+` is overloaded** — when used on strings, the `+` operator is called the concatenation operator; if you add a number and a string, the result is a string. [S1]
- **Comparisons return booleans** — comparison operators always return `true` or `false`, and strings are compared alphabetically. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Compute into a new variable** — combine two operands with an arithmetic operator and store the result: `let z = x + y;`. [S1]
- **Compound assignment** — `x += 5` is shorthand for `x = x + 5`. [S1]
- **Concatenate then assign** — build a string with `+` and a separator: `text1 + " " + text2`. [S1]
## 📖 세부 내용 (Details)
**Operators are for Mathematical and Logical Computations** [S1]
The assignment operator (`=`) assigns a value to a variable:
```javascript
let x = 10;
```
The addition operator (`+`) adds values:
```javascript
let x = 5;
let y = 2;
let z = x + y;
```
The multiplication operator (`*`) multiplies values:
```javascript
let x = 5;
let y = 2;
let z = x * y;
```
A more complex expression mixing addition and multiplication: [S1]
```javascript
let a = 3;
let x = (100 + 50) * a;
```
**Types of JavaScript Operators** [S1]
There are different types of JavaScript operators: Arithmetic, Assignment, Comparison, String, Logical, and others.
**JavaScript Arithmetic Operators** [S1]
Arithmetic operators are used to perform arithmetic on numbers:
| Operator | Description |
|----------|-------------|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| ** | Exponentiation |
| / | Division |
| % | Modulus (Division Remainder) |
| ++ | Increment |
| -- | Decrement |
**JavaScript String Addition** [S1]
When used on strings, the `+` operator is called the concatenation operator:
```javascript
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
```
The `+=` assignment operator can also concatenate:
```javascript
let text1 = "What a very ";
text1 += "nice day";
```
**Adding Strings and Numbers** [S1]
If you add a number and a string, the result will be a string:
```javascript
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
```
**JavaScript Assignment Operators** [S1]
Assignment operators assign values to JavaScript variables. For example, `x += 5` is the same as `x = x + 5`:
```javascript
let x = 10;
x += 5;
```
| Operator | Example | Same As |
|----------|---------|---------|
| = | x = y | x = y |
| += | x += y | x = x + y |
| -= | x -= y | x = x - y |
| *= | x *= y | x = x * y |
| /= | x /= y | x = x / y |
| %= | x %= y | x = x % y |
| **= | x **= y | x = x ** y |
**JavaScript Comparison Operators** [S1]
Comparison operators always return `true` or `false`:
```javascript
let x = 5;
let result = x > 8;
```
| Operator | Description | Example |
|----------|-------------|---------|
| == | equal to | x == 5 |
| === | equal value and equal type | x === 5 |
| != | not equal | x != 5 |
| !== | not equal value or not equal type | x !== 5 |
| > | greater than | x > 5 |
| < | less than | x < 5 |
| >= | greater than or equal to | x >= 5 |
| <= | less than or equal to | x <= 5 |
Strings are compared alphabetically: [S1]
```javascript
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
```
**JavaScript Logical Operators** [S1]
| Operator | Description |
|----------|-------------|
| && | logical and |
| \|\| | logical or |
| ! | logical not |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — assigning with `=`, computing with `+`/`*`, concatenating strings, compound-assigning with `+=`, and comparing values/strings. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Compute and store a result:
```javascript
let x = 5;
let y = 2;
let z = x + y;
```
Concatenate strings with a separator:
```javascript
let text3 = text1 + " " + text2;
```
Compound assignment:
```javascript
let x = 10;
x += 5;
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The behavior that `"5" + 5` yields a string (`"55"`) rather than `10` is intentional, not a contradiction — `+` concatenates when a string operand is present.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Arithmetic]], [[JavaScript Assignment]], [[JavaScript Comparisons]], [[JavaScript Types]]
- **참조 맥락:** The umbrella reference for the operator-family pages (arithmetic, assignment, comparison, logical) that follow it.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Operators — https://www.w3schools.com/js/js_operators.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,181 @@
---
id: javascript-output
title: "JavaScript Output"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["innerHTML", "document.write", "window.alert", "console.log", "JS display data"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "output", "innerhtml", "console-log"]
raw_sources: ["https://www.w3schools.com/js/js_output.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Output]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript can display data four ways — writing into an HTML element (`innerHTML`/`innerText`), HTML output via `document.write()`, an alert box via `window.alert()`, and the browser console via `console.log()`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Four display possibilities** — `innerHTML`/`innerText` (into an HTML element), `document.write()` (HTML output), `window.alert()` (alert box), `console.log()` (browser console). [S1]
- **`innerHTML` is the most common** — accessing an element with `document.getElementById(id)` and setting `innerHTML` is the most common way to display data in HTML. [S1]
- **`innerHTML` vs `innerText`** — use `innerHTML` when you want to change an HTML element; use `innerText` when you only want to change the plain text. [S1]
- **`document.write()` is for testing only** — using it after the document has loaded will delete all existing HTML. [S1]
- **`console.log()` is for debugging.** [S1]
- **No print object** — JavaScript has no print object/method; the only exception is `window.print()` to print the current window. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Select-then-write pattern** — `document.getElementById("demo").innerHTML = ...` is the standard way to inject results into the page. [S1]
- **Testing vs production output** — `document.write()` and `alert()` are quick test outputs; `console.log()` is the debugging channel; `innerHTML`/`innerText` are the production display. [S1]
- **Optional `window` prefix** — `window.alert()` and `alert()` are equivalent because `window` is the global scope object. [S1]
## 📖 세부 내용 (Details)
**JavaScript Display Possibilities** — JavaScript can "display" data in four ways: writing into an HTML element using `innerHTML` or `innerText`, writing into the HTML output using `document.write()`, writing into an alert box using `window.alert()`, and writing into the browser console using `console.log()`. [S1]
**Using innerHTML** — To access an HTML element, use the `document.getElementById(id)` method, then use the `innerHTML` property to change the HTML content. Changing the `innerHTML` property is the most common way to display data in HTML. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
```
**Using innerText** — Use the `innerText` property to change the plain text content of an HTML element. Use `innerHTML` when you want to change an HTML element; use `innerText` when you only want to change the plain text. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerText = "Hello World";
</script>
</body>
</html>
```
**Using document.write()** — For testing purposes, it is convenient to use `document.write()`. Using `document.write()` after an HTML document is loaded will delete all existing HTML; the method should only be used for testing. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
```
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
```
**Using window.alert()** — You can use an alert box to display data. The `window` keyword is optional because `window` is the global scope object. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
```
```html
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
```
**Using console.log()** — For debugging purposes, you can use the `console.log()` method to display data in the browser console. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
```
**JavaScript Print** — JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the `window.print()` method in the browser to print the content of the current window. [S1]
```html
<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Print this page</button>
</body>
</html>
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — injecting markup with `innerHTML`, plain text with `innerText`, test output with `document.write()`/`alert()`, debug output with `console.log()`, and `window.print()` on a button. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Display into an element:
```javascript
document.getElementById("demo").innerHTML = "<h2>Hello World</h2>";
```
Debug to console:
```javascript
console.log(5 + 6);
```
Alert box:
```javascript
window.alert(5 + 6);
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. (The source itself cautions that `document.write()` after load deletes existing HTML — a caveat, not a contradiction.)
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Introduction]], [[JavaScript Where To]], [[JavaScript Statements]]
- **참조 맥락:** Referenced whenever results need to be shown to a user or developer.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Output — https://www.w3schools.com/js/js_output.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Output" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,165 @@
---
id: javascript-primitive-data-types
title: "JavaScript Primitive Data Types"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["JS primitives", "primitive types", "string number boolean", "undefined null", "BigInt"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "primitives", "data-types", "string", "number"]
raw_sources: ["https://www.w3schools.com/js/js_datatypes_primitives.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Primitive Data Types]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript has 7 primitive data types — Number, BigInt, String, Boolean, Undefined, Null, and Symbol — each a simple, immutable value distinct from the single object type. [S1]
## 🧠 핵심 개념 (Core concepts)
- **7 primitive types** — JavaScript variables can hold 7 primitive types (Number, BigInt, String, Boolean, Undefined, Null, Symbol) or 1 object type. [S1]
- **Strings** — a string is a series of characters, written with single or double quotes. [S1]
- **Numbers are 64-bit floats** — all JavaScript numbers are stored as double (64-bit floating point) values; they support decimals and exponential notation. [S1]
- **BigInt (ES2020)** — handles integers too large for standard numbers. [S1]
- **Undefined vs Null** — a variable without a value is `undefined`; `null` represents the intentional absence of a value, but `typeof null` returns `"object"` (a historical quirk). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Nest opposite quotes** — put single quotes inside double-quoted strings (and vice versa) to avoid escaping. [S1]
- **`===` vs `==` for null/undefined** — strict equality (`===`) is `true` only when value and type match; loose equality (`==`) treats `null` and `undefined` as equal. [S1]
- **Empty string is still a string**`let car = "";` has value `""` and `typeof "string"`. [S1]
## 📖 세부 내용 (Details)
JavaScript variables can hold 8 types of data: 7 primitive types or 1 object type. The primitive types are: Number, BigInt, String, Boolean, Undefined, Null, and Symbol. [S1]
**JavaScript Strings**
A string is a series of characters like "John Doe", written with single or double quotes. [S1]
```javascript
// Using double quotes:
let carName1 = "Volvo XC60";
// Using single quotes:
let carName2 = 'Volvo XC60';
```
You can nest the opposite quote type inside a string: [S1]
```javascript
// Single quote inside double quotes:
let answer1 = "It's alright";
// Single quotes inside double quotes:
let answer2 = "He is called 'Johnny'";
// Double quotes inside single quotes:
let answer3 = 'He is called "Johnny"';
```
**JavaScript Numbers**
All JavaScript numbers are stored as decimal (floating point) values — always double (64-bit floating point). [S1]
```javascript
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
```
Exponential notation: [S1]
```javascript
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
```
**JavaScript BigInt**
BigInt (ES2020) handles integers too large for standard numbers: [S1]
```javascript
let x = BigInt("123456789012345678901234567890");
```
**JavaScript Booleans**
Booleans can only hold `true` or `false`: [S1]
```javascript
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
```
**The `typeof` Operator**
The `typeof` operator identifies a variable's type. [S1]
```javascript
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
```
```javascript
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
```
**Undefined**
A variable without a value has the value `undefined` and the type `undefined`: [S1]
```javascript
let car; // Value is undefined, type is undefined
```
```javascript
car = undefined; // Value is undefined, type is undefined
```
**Empty Values**
An empty string has both a legal value and a type: [S1]
```javascript
let car = ""; // The value is "", the typeof is "string"
```
**Datatype null**
`null` represents "nothing" — the intentional absence of a value: [S1]
```javascript
let carName = null;
```
Notes on `null`: the `typeof` operator returns `"object"` for `null` (a historical quirk); the strict equality operator `===` returns `true` only if both value and type match; the loose equality operator `==` returns `true` for both `null` and `undefined`. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own declarations (string quoting variants, number/exponent/BigInt literals, boolean comparisons, and the undefined/empty/null examples) are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Nest opposite quotes (language: JavaScript):
```javascript
let answer1 = "It's alright";
let answer3 = 'He is called "Johnny"';
```
Exponential number notation:
```javascript
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
`typeof null` returns `"object"` even though `null` is a primitive value — the page flags this as a historical quirk. BigInt was introduced in ES2020. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Data Types]], [[JavaScript Object Data Types]], [[JavaScript typeof]], [[JavaScript Symbols]]
- **참조 맥락:** Referenced whenever declaring simple values or reasoning about equality and `typeof` results.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Primitive Data Types — https://www.w3schools.com/js/js_datatypes_primitives.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Primitive Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,300 @@
---
id: javascript-promises
title: "JavaScript Promises"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Promise", "Promises", "Promise.resolve", "Promise.reject", "Promise chaining", "then catch"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "promises", "asynchronous"]
raw_sources: ["https://www.w3schools.com/js/js_promise.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Promises]]
## 🎯 한 줄 통찰 (One-line insight)
A Promise is an object representing the eventual completion or failure of an asynchronous operation, letting you chain steps with `then()`/`catch()` instead of nesting callbacks. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Promises replace callback nesting** — they were created to make asynchronous JavaScript easier than deeply nested callbacks ("callback hell"). [S1]
- **Three states** — a Promise is pending, fulfilled (resolved), or rejected. [S1]
- **Construct with resolve/reject**`new Promise(function(resolve, reject) { ... })`; call `resolve(value)` on success or `reject(value)` on failure. [S1]
- **Consume with then/catch**`then()` takes success (and optional failure) handlers; `catch()` handles rejection across a chain. [S1]
- **Chaining requires return** — each `then()` should `return` the next promise so the chain links correctly; forgetting to return breaks the chain. [S1]
- **Shortcuts**`Promise.resolve(value)` and `Promise.reject(value)` create already-settled promises. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Resolve/reject wrapper** — wrap slow work in `new Promise`, calling `resolve`/`reject` when done. [S1]
- **then-chain with return**`step1().then(v => step2(v)).then(v => step3(v))...` runs steps in sequence. [S1]
- **Single catch for the chain** — one `.catch()` at the end handles any failure along the chain. [S1]
- **Promisify a timer or XHR** — wrap `setTimeout` or `XMLHttpRequest` so its completion resolves a promise. [S1]
## 📖 세부 내용 (Details)
**The problem promises solve (callback hell)**
Deeply nested callbacks are hard to read: [S1]
```javascript
step1(function(r1) {
step2(r1, function(r2) {
step3(r2, function(r3) {
console.log(r3);
});
});
});
```
**Promise syntax — resolve case**
[S1]
```javascript
let myPromise = new Promise(function(resolve, reject) {
ok = true;
// Code that may take some time
if (ok) {
resolve("OK");
} else {
reject("Error");
}
});
// Using then() to display the result
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
```
**Promise syntax — reject case**
[S1]
```javascript
let myPromise = new Promise(function(resolve, reject) {
ok = false;
// Code that may take some time
if (ok) {
resolve("OK");
} else {
reject("Error");
}
});
// Using then() to display the result
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
```
**Promise.resolve()**
[S1]
```javascript
let promise = Promise.resolve("OK");
promise
.then(function(value) {
console.log(value);
})
.catch(function(value) {
myDisplayer(value);
});
```
**Promise.reject()**
[S1]
```javascript
let promise = Promise.reject("Error");
promise
.then(function(value) {
console.log(value);
})
.catch(function(value) {
myDisplayer(value);
});
```
**Promise chaining**
Run three functions in steps, each returning a promise: [S1]
```javascript
// Three functions to run in steps
function step1() {
return Promise.resolve("A");
}
function step2(value) {
return Promise.resolve(value + "B");
}
function step3(value) {
return Promise.resolve(value + "C");
}
// Run the three functions in steps
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.then(function(value) {
myDisplayer(value);
});
```
**Error handling with catch()**
A single `catch()` handles failure anywhere in the chain: [S1]
```javascript
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.catch(function(error) {
console.log(error);
});
```
**Common mistake — forgetting to return**
Without `return`, the next `then()` does not receive the resolved value: [S1]
```javascript
step1()
.then(function(value) {
step2(value);
})
.then(function(value) {
console.log(value);
});
```
**Fetch API with promises**
[S1]
```javascript
fetch("data.json")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
```
**Timeout with a callback vs a promise**
Callback version: [S1]
```javascript
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
```
Promise version (promisified timer): [S1]
```javascript
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
```
**File loading — callback vs promise**
Callback version using XMLHttpRequest: [S1]
```javascript
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(req.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
```
Promise version: [S1]
```javascript
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets — the `step1/step2/step3` chain, the promisified `setTimeout`, and the promisified `XMLHttpRequest` file loader — are the canonical applied examples. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Construct and consume a promise (language: JavaScript):
```javascript
let myPromise = new Promise(function(resolve, reject) {
if (ok) { resolve("OK"); } else { reject("Error"); }
});
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
```
Chain steps with a single catch:
```javascript
step1()
.then(function(value) { return step2(value); })
.then(function(value) { return step3(value); })
.catch(function(error) { console.log(error); });
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Callbacks** — the original approach; deeply nested callbacks become "callback hell," hard to read. [S1]
- **Promises** — created to make async JavaScript easier; chainable with `then()` and a single `catch()`, but require remembering to `return` each step. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Async Callbacks]], [[JavaScript Async Await]], [[JavaScript Async Fetch]], [[JavaScript Async Timeouts]]
- **참조 맥락:** The cleaner successor to callbacks and the foundation that async/await is built on.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Promises — https://www.w3schools.com/js/js_promise.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Promises" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,141 @@
---
id: javascript-random
title: "JavaScript Random"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Math.random", "random number", "random integer", "getRndInteger", "JS random"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "math", "random"]
raw_sources: ["https://www.w3schools.com/js/js_random.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Random]]
## 🎯 한 줄 통찰 (One-line insight)
`Math.random()` returns a float in [0, 1); wrapping it in `Math.floor(Math.random() * n)` yields a random integer, and the inclusive-range formula `Math.floor(Math.random() * (max - min + 1)) + min` covers both endpoints. [S1]
## 🧠 핵심 개념 (Core concepts)
- **`Math.random()`** always returns a number lower than 1 (and ≥ 0). [S1]
- **Random integers** are produced by combining `Math.random()` with `Math.floor()`. [S1]
- **Multiplying by `n`** then flooring gives an integer from 0 to n1; using `n+1` makes the top bound inclusive. [S1]
- **Adding an offset** (`+ 1`, `+ min`) shifts the range away from 0. [S1]
- **The inclusive-range function** uses `(max - min + 1)` so that both `min` and `max` are possible results. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **0 to n1**`Math.floor(Math.random() * n)`. [S1]
- **0 to n (inclusive)**`Math.floor(Math.random() * (n + 1))`. [S1]
- **1 to n (inclusive)**`Math.floor(Math.random() * n) + 1`. [S1]
- **min to max, max excluded**`Math.floor(Math.random() * (max - min)) + min`. [S1]
- **min to max, max included**`Math.floor(Math.random() * (max - min + 1)) + min`. [S1]
## 📖 세부 내용 (Details)
**Math.random()** — `Math.random()` returns a random number between 0 (inclusive), and 1 (exclusive). `Math.random()` always returns a number lower than 1: [S1]
```javascript
// Returns a random number:
Math.random();
```
**JavaScript Random Integers** — `Math.random()` used with `Math.floor()` can be used to return random integers. [S1]
Return a random integer from 0 to 9 (both included): [S1]
```javascript
// Return a random integer from 0 to 9 (both included):
Math.floor(Math.random() * 10);
```
Return a random integer from 0 to 10 (both included): [S1]
```javascript
// Return a random integer from 0 to 10 (both included):
Math.floor(Math.random() * 11);
```
Return a random integer from 0 to 99 (both included): [S1]
```javascript
// Return a random integer from 0 to 99 (both included):
Math.floor(Math.random() * 100);
```
Return a random integer from 0 to 100 (both included): [S1]
```javascript
// Return a random integer from 0 to 100 (both included):
Math.floor(Math.random() * 101);
```
Return a random integer from 1 to 10 (both included): [S1]
```javascript
// Return a random integer between 1 and 10 (both included):
Math.floor(Math.random() * 10) + 1;
```
Return a random integer from 1 to 100 (both included): [S1]
```javascript
// Returns a random integer from 1 to 100 (both included):
Math.floor(Math.random() * 100) + 1;
```
**A Proper Random Function** — As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes. This function returns a random number between `min` (included) and `max` (excluded): [S1]
```javascript
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
```
This function returns a random number between `min` and `max` (both included): [S1]
```javascript
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
```
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — generating random integers in fixed ranges (09, 0100, 1100) and the reusable `getRndInteger(min, max)` helpers in both exclusive-max and inclusive-max forms. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Random integer 0 to n1:
```javascript
Math.floor(Math.random() * 10); // 0..9
```
Random integer 1 to n (inclusive):
```javascript
Math.floor(Math.random() * 100) + 1; // 1..100
```
Reusable inclusive-range function:
```javascript
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Exclusive-max vs inclusive-max**`getRndInteger` with `(max - min)` excludes `max`; the variant with `(max - min + 1)` includes `max`. Choose based on whether the upper bound should be a possible result. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Math]], [[JavaScript Numbers]], [[JavaScript Array Sort]]
- **참조 맥락:** Referenced whenever randomized values or random integer ranges are needed.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Random — https://www.w3schools.com/js/js_random.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Random" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,215 @@
---
id: javascript-regexp
title: "JavaScript RegExp"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["regular expressions", "regex", "RegExp object", "pattern matching", "regex flags", "metacharacters"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "regexp", "regex", "string"]
raw_sources: ["https://www.w3schools.com/js/js_regexp.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript RegExp]]
## 🎯 한 줄 통찰 (One-line insight)
A regular expression is a sequence of characters forming a search pattern (`/pattern/flags`), used in JavaScript for searching, replacing, and validating text through string methods and the RegExp object. [S1]
## 🧠 핵심 개념 (Core concepts)
- **A regex is a search pattern** — "A Regular Expression is a sequence of characters that forms a search pattern." [S1]
- **Syntax** — written as `/pattern/modifier flags`. [S1]
- **String methods**`match(regex)` returns an array of results, `replace(regex)` returns a new string, and `search(regex)` returns the index of the first match. [S1]
- **Flags**`/g` global match, `/i` case-insensitive, `/u` Unicode support (new 2015). [S1]
- **Metacharacters**`\d` digits, `\w` word characters, `\s` spaces. [S1]
- **Quantifiers**`x+`, `x*`, `x?` control how many occurrences match. [S1]
- **Assertions**`^`, `$`, `\b`, lookahead `(?=...)`, lookbehind `(?<=...)`. [S1]
- **Character classes**`[a]`, `[abc]`, `[a-z]`, `[0-9]` match sets/ranges of characters. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **String method + regex literal** — call `text.match(/.../)`, `text.search(/.../)`, or `text.replace(/.../, ...)` with an inline regex. [S1]
- **Flag-driven behavior** — append `g` to find all matches and `i` to ignore case. [S1]
- **`pattern.test(text)` for boolean validation** — use anchored patterns (`^`, `$`) with `.test()` to validate where a substring sits. [S1]
## 📖 세부 내용 (Details)
**Regular Expressions Overview**
"A Regular Expression is a sequence of characters that forms a search pattern." Regular expressions in JavaScript are handled through the RegExp object and are used for text searching, replacing, and validation. [S1]
**Syntax** — `/pattern/modifier flags`. [S1]
**Using String Methods** — three primary string methods work with regex: `match(regex)` returns an array; `replace(regex)` returns a new string; `search(regex)` returns the index of the first match. [S1]
Case-insensitive search: [S1]
```javascript
let text = "Visit W3Schools";
let n = text.search(/w3schools/i);
```
Using `match()`: [S1]
```javascript
let text = "Visit W3Schools";
let n = text.match(/W3schools/);
```
Using `replace()`: [S1]
```javascript
let text = "Visit Microsoft!";
let result = text.replace(/Microsoft/i, "W3Schools");
```
Using `search()`: [S1]
```javascript
let text = "Visit W3Schools";
let n = text.search(/W3Schools/);
```
Alternation (OR): [S1]
```javascript
let text = "Black, white, red, green, blue, yellow.";
let result = text.match(/red|green|blue/g);
```
**Regex Flags** [S1]
| Flag | Description |
|------|-------------|
| `/g` | Performs a global match (find all) |
| `/i` | Performs case-insensitive matching |
| `/u` | Enables Unicode support (new 2015) |
Global flag: [S1]
```javascript
let text = "Is this all there is?";
const pattern = /is/g;
let result = text.match(pattern);
```
Case-insensitive flag: [S1]
```javascript
let text = "Visit W3Schools";
const pattern = /w3schools/i;
let result = text.match(pattern);
```
**Metacharacters** — common metacharacters include `\d` (digits), `\w` (words), and `\s` (spaces). [S1]
Digits metacharacter: [S1]
```javascript
let text = "Give 100%!";
const pattern = /\d/g;
let result = text.match(pattern);
```
Word characters: [S1]
```javascript
let text = "Give 100%!";
const pattern = /\w/g;
let result = text.match(pattern);
```
**Quantifiers** [S1]
| Quantifier | Description |
|------------|-------------|
| `x+` | Matches any string with at least one occurrence of x |
| `x*` | Matches any string with zero or more occurrences of x |
| `x?` | Matches any string with zero or one occurrence of x |
Question-mark quantifier: [S1]
```javascript
let text = "1, 100 or 1000?";
const pattern = /10?/g;
let result = text.match(pattern);
```
**Assertions** — string boundaries and lookarounds: [S1]
| Syntax | Name | Description |
|--------|------|-------------|
| `^` | String boundary | Matches the beginning of a string |
| `$` | String boundary | Matches the end of a string |
| `\b` | Word boundary | Matches the beginning or end of a word |
| `(?=...)` | Lookahead | Matches the subsequent string |
| `(?<=...)` | Lookbehind | Matches the previous string |
Caret (beginning) — true: [S1]
```javascript
const pattern = /^W3Schools/;
let text = "W3Schools Tutorial";
let result = pattern.test(text); // true
```
Caret (beginning) — false: [S1]
```javascript
const pattern = /^W3Schools/;
let text = "Hello W3Schools";
let result = pattern.test(text); // false
```
Dollar (end) — true: [S1]
```javascript
const pattern = /W3Schools$/;
let text = "Hello W3Schools";
let result = pattern.test(text); // true
```
Dollar (end) — false: [S1]
```javascript
const pattern = /W3Schools$/;
let text = "W3Schools tutorial";
let result = pattern.test(text); // false
```
**Character Classes** [S1]
| Class | Description |
|-------|-------------|
| `[a]` | Matches the character between the brackets |
| `[abc]` | Matches all characters between the brackets |
| `[a-z]` | Matches all characters in the range from a to z |
| `[0-9]` | Matches all characters in the range from 0 to 9 |
Character class `[0-9]`: [S1]
```javascript
let text = "More than 1000 times";
const pattern = /[0-9]/g;
let result = text.match(pattern);
```
The page concludes with links to related topics including RegExp flags, character classes, meta characters, assertions, groups, quantifiers, patterns, objects, and methods. [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets are the canonical applied examples — case-insensitive `search`, `match`/`replace`, alternation, the `g`/`i` flags, the `\d`/`\w` metacharacters, the `?` quantifier, anchored `.test()` validation, and the `[0-9]` character class. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Search, match, and replace with regex literals (language: JavaScript):
```javascript
text.search(/w3schools/i); // index of first match, case-insensitive
text.match(/red|green|blue/g); // all alternation matches
text.replace(/Microsoft/i, "W3Schools"); // returns new string
```
Validate position with anchors and `.test()`:
```javascript
/^W3Schools/.test("W3Schools Tutorial"); // true (starts with)
/W3Schools$/.test("Hello W3Schools"); // true (ends with)
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript String Methods]], [[JavaScript String Search]], [[JavaScript Type Conversion]], [[JavaScript Form Validation]]
- **참조 맥락:** The pattern-matching toolkit used by string methods for searching, replacing, and validating text input.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript RegExp — https://www.w3schools.com/js/js_regexp.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript RegExp" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,138 @@
---
id: javascript-scope
title: "JavaScript Scope"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["variable scope", "global scope", "function scope", "block scope", "local variables"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "scope", "variables", "let", "const", "var"]
raw_sources: ["https://www.w3schools.com/js/js_scope.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Scope]]
## 🎯 한 줄 통찰 (One-line insight)
Scope determines the accessibility (visibility) of variables — JavaScript has three kinds: global, function, and block. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Scope = accessibility** — scope determines where variables are visible and reachable in your code. [S1]
- **Three scopes** — JavaScript has global scope, function scope, and (since ES6) block scope. [S1]
- **`let` and `const` are block scoped** — variables declared with `let` and `const` inside a block `{ }` cannot be accessed outside it; `var` is *not* block scoped. [S1]
- **Function scope applies to all three keywords**`var`, `let`, and `const` are all function-scoped when declared inside a function and cannot be accessed from outside. [S1]
- **Automatic globals are a trap** — assigning a value to an undeclared variable makes it a global automatically, which is discouraged; strict mode prevents it. [S1]
- **Lifetime** — local (function) variables live only while the function runs; global variables live until the page/browser closes. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Declare in the narrowest scope** — keep variables local to the function or block that uses them. [S1]
- **Prefer block scope for safety** — use `let`/`const` inside blocks to confine variables and avoid leaks. [S1]
- **Avoid undeclared assignment** — always declare before assigning to avoid creating accidental globals. [S1]
## 📖 세부 내용 (Details)
**What is scope?**
Scope determines the accessibility (visibility) of variables. JavaScript has 3 types of scope: Block scope, Function scope, and Global scope. [S1]
**Global Scope**
Variables declared *outside* any function or block have global scope and can be accessed everywhere, whether declared with `var`, `let`, or `const`: [S1]
```javascript
let carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
```
**Function Scope (Local Scope)**
Variables declared inside a function are local to that function and cannot be accessed from outside. Each function creates a new scope, and all three declaration keywords behave the same way here: [S1]
```javascript
function myFunction1() {
var carName = "Volvo"; // Function Scope
}
function myFunction2() {
let carName = "Volvo"; // Function Scope
}
function myFunction3() {
const carName = "Volvo"; // Function Scope
}
```
**Block Scope**
Before ES6 (2015), JavaScript had only global scope and function scope. ES6 introduced `let` and `const`, which provide block scope. Variables declared inside a `{ }` block with `let` or `const` cannot be accessed from outside the block: [S1]
```javascript
{
let x = 2;
}
// x can NOT be used here
```
Variables declared with `var` do *not* have block scope and *can* be accessed outside the block: [S1]
```javascript
{
var x = 2;
}
// x CAN be used here
```
**Automatically Global**
If you assign a value to a variable that has not been declared, it automatically becomes a global variable. This is discouraged. [S1]
**Strict Mode**
In "strict mode", undeclared variables are not automatically global. [S1]
**The Lifetime of JavaScript Variables**
The lifetime of a JavaScript variable starts when it is declared. Function (local) variables are deleted when the function completes. Global variables are deleted when you close the page (or browser window). [S1]
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets illustrate the rule directly: the same `carName` variable visible globally vs. confined inside `myFunction1/2/3`, and the contrast between `let x` (block scoped) and `var x` (leaks out of the block). No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Block scope with `let`/`const` (language: JavaScript):
```javascript
{
let x = 2;
}
// x can NOT be used here
```
`var` ignores block scope:
```javascript
{
var x = 2;
}
// x CAN be used here
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`var` vs. `let`/`const` for block scope** — only `let` and `const` are confined to the block; `var` escapes to the enclosing function/global scope. Choose `let`/`const` to limit visibility. [S1]
- **Global vs. local** — declare globally only when the value must be shared everywhere; otherwise keep variables local for shorter lifetime and fewer collisions. [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript var let const]], [[JavaScript Code Blocks]], [[JavaScript Hoisting]], [[JavaScript Strict Mode]]
- **참조 맥락:** Underpins decisions about where to declare variables and which keyword to use.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Scope — https://www.w3schools.com/js/js_scope.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Scope" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,145 @@
---
id: javascript-set-logic
title: "JavaScript Set Logic"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Set logic", "union", "intersection", "difference", "symmetricDifference", "isSubsetOf", "isDisjointFrom"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "set", "set-logic"]
raw_sources: ["https://www.w3schools.com/js/js_set_logic.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Set Logic]]
## 🎯 한 줄 통찰 (One-line insight)
JavaScript 2025 added seven set-theory methods to `Set``union`, `intersection`, `difference`, `symmetricDifference` (returning new Sets) and `isSubsetOf`, `isSupersetOf`, `isDisjointFrom` (returning booleans) — for direct mathematical set operations. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Seven logical Set methods** were added to the Set object in JavaScript 2025. [S1]
- **Combining methods return a new Set**`union`, `intersection`, `difference`, `symmetricDifference`. [S1]
- **Relationship methods return a boolean**`isSubsetOf`, `isSupersetOf`, `isDisjointFrom`. [S1]
- **Each operates on this Set and an argument Set** — e.g. `A.union(B)`. [S1]
- **Browser support is recent** — Chrome/Edge 136 (Apr 2025), Firefox 129 (Aug 2024), Safari 18.2 (Dec 2024), Opera 120 (May 2025). [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Binary set operation** — call a method on set A passing set B: `const C = A.intersection(B);`. [S1]
- **New-Set vs predicate** — combining ops yield a Set you store; relationship ops yield a `true`/`false` you store in `answer`. [S1]
## 📖 세부 내용 (Details)
**union()** — returns a new set containing the elements which are in this set, or in the argument set, or in both: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
const C = A.union(B);
```
**intersection()** — returns a new set containing the elements which are in this set and in the argument set: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
const C = A.intersection(B);
```
**difference()** — returns a new set containing elements which are in this set but not in the argument set: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
const C = A.difference(B);
```
**symmetricDifference()** — returns a new set containing elements which are in this set or in the argument set, but not in both: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
const C = A.symmetricDifference(B);
```
**isSubsetOf()** — returns `true` if all elements in this set is also elements in the argument set: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
let answer = A.isSubsetOf(B);
```
**isSupersetOf()** — returns `true` if all elements in the argument set are also in this set: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
let answer = A.isSupersetOf(B);
```
**isDisjointFrom()** — returns `true` if this set has no elements in common with the argument set: [S1]
```javascript
const A = new Set(['a','b','c']);
const B = new Set(['b','c','d']);
let answer = A.isDisjointFrom(B);
```
**Browser Support** — JavaScript Set Logic methods are supported in modern browsers from 2024-2025: [S1]
| Browser | Version | Release |
|---------|---------|---------|
| Chrome | 136 | Apr 2025 |
| Edge | 136 | Apr 2025 |
| Firefox | 129 | Aug 2024 |
| Safari | 18.2 | Dec 2024 |
| Opera | 120 | May 2025 |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — running each operation over two fixed Sets `A = {a,b,c}` and `B = {b,c,d}`, storing combining results in `C` and relationship results in `answer`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Intersection of two Sets (language: JavaScript):
```javascript
const C = A.intersection(B);
```
Subset predicate:
```javascript
let answer = A.isSubsetOf(B);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
Choose the method by the question being asked, per the source definitions: [S1]
- Need everything from both → `union()`.
- Need only shared elements → `intersection()`.
- Need this set minus the other → `difference()`.
- Need elements unique to one side (the XOR) → `symmetricDifference()`.
- Just need a yes/no relationship → `isSubsetOf()`, `isSupersetOf()`, or `isDisjointFrom()` (boolean, no new Set produced).
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
These are new additions (JavaScript 2025). Older runtimes predating the browser versions listed will not have them. No contradictions found in the source. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Sets]], [[JavaScript Set Methods]], [[JavaScript Maps]]
- **참조 맥락:** Referenced when performing mathematical set operations between two Sets.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Set Logic — https://www.w3schools.com/js/js_set_logic.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Set Logic" page (Astra wiki-curation, P-Reinforce v3.1 format).
@@ -0,0 +1,231 @@
---
id: javascript-set-methods
title: "JavaScript Set Methods"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Set methods", "Set.add", "Set.has", "Set.size", "Set.values", "Set.entries", "Set.forEach"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "set", "methods"]
raw_sources: ["https://www.w3schools.com/js/js_set_methods.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Set Methods]]
## 🎯 한 줄 통찰 (One-line insight)
The core Set methods — `add`, `delete`, `clear`, `has`, `forEach`, `values`, `keys`, `entries`, plus the `size` property — manage and iterate a unique-value collection; because a Set has no keys, `keys()` and `entries()` mirror `values()` to stay compatible with Maps. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Sets only store unique values** — if you add an element that already exists, `add()` has no effect and the Set is unchanged. [S1]
- **`size` is a property, not a method** — it returns the number of elements. [S1]
- **`has()` tests membership** — returns `true` if a value exists in the Set. [S1]
- **`forEach()` runs a callback per element.** [S1]
- **`values()` returns an Iterator** of the Set's values. [S1]
- **A Set has no keys** — so `keys()` returns the same as `values()`, and `entries()` returns `[value,value]` pairs. This makes Sets compatible with Maps. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Iterator-then-loop** — capture `letters.values()` (or `keys()`/`entries()`) into a variable, then `for...of` it; or loop the call directly. [S1]
- **Membership guard**`letters.has(x)` before acting on a value. [S1]
- **forEach for side effects** — accumulate or process each value via a callback. [S1]
## 📖 세부 내용 (Details)
**The new Set() Method** — pass an array to the `new Set()` constructor: [S1]
```javascript
// Create a new Set
const letters = new Set(["a","b","c"]);
```
**The add() Method** [S1]
```javascript
letters.add("d");
letters.add("e");
```
Sets only store unique values. If an attempt is made to add an element that already exists in the Set, the `add()` method will have no effect, and the Set will remain unchanged: [S1]
```javascript
letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
```
**The size Property** — returns the number of elements: [S1]
```javascript
// Create a new Set
const mySet = new Set(["a","b","c"]);
// The number of elements are
mySet.size;
```
**Listing Set Elements** — list all elements with a `for...of` loop: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
let text = "";
for (const x of letters) {
text += x;
}
```
**The has() Method** — returns `true` if a value exists: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// Does the Set contain "d"?
answer = letters.has("d");
```
**The forEach() Method** — invokes a callback for each element: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// List all entries
let text = "";
letters.forEach (function(value) {
text += value;
})
```
**The values() Method** — returns an Iterator with the values in a Set: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// Get all Values
const myIterator = letters.values();
// List all Values
let text = "";
for (const entry of myIterator) {
text += entry;
}
```
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Values
let text = "";
for (const entry of letters.values()) {
text += entry;
}
```
**The keys() Method** — a Set has no keys, so `keys()` returns the same as `values()`. This makes Sets compatible with Maps: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// Create an Iterator
const myIterator = letters.keys();
// List all Elements
let text = "";
for (const x of myIterator) {
text += x;
}
```
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
let text = "";
for (const x of letters.keys()) {
text += x;
}
```
**The entries() Method** — a Set has no keys, so the `entries()` method returns `[value,value]`. This makes Sets compatible with Maps: [S1]
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// Get all Entries
const myIterator = letters.entries();
// List all Entries
let text = "";
for (const entry of myIterator) {
text += entry;
}
```
```javascript
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Entries
let text = "";
for (const entry of letters.entries()) {
text += entry;
}
```
**Set Methods and Properties** [S1]
| Method/Property | Description |
|---|---|
| new Set() | Creates a new Set |
| add() | Adds a new element to the Set |
| clear() | Removes all elements from a Set |
| delete() | Removes a specified element from a Set |
| entries() | Returns an Iterator with [value,value] pairs from a Set |
| forEach() | Invokes a callback for each element in the Set |
| has() | Returns true if a value exists in the Set |
| keys() | Returns an Iterator with the values in a Set |
| values() | Returns an Iterator with the values in a Set |
| size | Returns the number of elements in a Set |
## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — building a `letters`/`mySet` Set, reading `size`, testing membership with `has()`, and walking the Set with `forEach()`, `values()`, `keys()`, and `entries()`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Membership test (language: JavaScript):
```javascript
answer = letters.has("d");
```
Iterate values via the values() iterator:
```javascript
let text = "";
for (const entry of letters.values()) {
text += entry;
}
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. Note the intentional design choice: `keys()` and `entries()` echo `values()` because Sets have no keys — done deliberately for Map compatibility, not a bug. [S1]
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Sets]], [[JavaScript Set Logic]], [[JavaScript Map Methods]]
- **참조 맥락:** Referenced whenever managing or iterating the contents of a Set.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Set Methods — https://www.w3schools.com/js/js_set_methods.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Set Methods" page (Astra wiki-curation, P-Reinforce v3.1 format).

Some files were not shown because too many files have changed in this diff Show More