4.Front End Development‐JavaScript - YukaKoshiba/MyknowledgeDocs GitHub Wiki
Front End Development_JavaSCript @English Version
Create Date:2025/07/12
Last Update Date:2025/07/12
Terms
Best Practices
Template Literals
Events
Processing Timing
Data Types
Data/Data Structures
Message Output
Variable Declaration
Basic Syntax:
Conditional Branching (
if statement
switch statement )
loops (
for loop
while loop )
Exception Handling
Operators
Functions Arrow Functions Asynchronous Functions (async function) Anonymous Functions
Objects
Classes
Creating Objects
Accessing Object Arrays
Spread Syntax
Built-in Objects and Methods
Methods
Global Objects:
Object
RegExp (Regular Expression)
window
Number
Standard Objects:
console
String
Math
Date
Object
document
Array
Event
HTMLAudioElement
DOM Elements (Element) Object
:
Notes on using document.addEventListener
Category Object
Regular Expressions AJAX Implementation
Helpful Information for Debugging: Executing with User Screen Behavior Developer Mode
D3:
jQuery:
Best Practices
Implementation Method
Functions
Objects and Methods(
Attribute Manipulation
HTML Manipulation
CSS Manipulation
DOM Structure Manipulation)
Pseudo Classes
AJAX Implementation
React:
Terms
How to Use Components
Component Naming Conventions
Component Creation
JSX Writing Rules/Differences from HTML:
Closing Tags
Comments
Behavior of JSX Syntax Errors
Creating JSX Elements
Return Rule
Setting Element Class Names with `className`
Handling Variables and Objects
Style Specification
Specifying Props
Composition (Consolidating Components)
Virtual DOM Rendering
React Event Handlers
Stateless Components (stateful component)
Changing State
Server-side Processing
Lifecycle Methods (or Lifecycle Hooks)
Redux:
Terms
Processing Flow
How to Use Redux
React Integration
A scripting/programming language that enables the implementation of complex features on web pages.
It allows for the creation of dynamic web pages.
A programming language created in the 1990s, derived from other programming languages.
It originates from C language syntax, making it relatively easy to learn if you understand C.
JavaScript can be used as an object-oriented programming language,
and objects have properties (attributes) and methods (functions).
JavaScript runs on the client side, meaning it operates on the computer of the user viewing the web page.
Furthermore, JavaScript operates based on event-driven programming.
This is the idea that program execution is driven by user interactions or events occurring in the web browser.
The program waits for specific events to occur, and once an event happens, it executes the corresponding process.
Unlike procedural programming languages like C, the program's execution order is not predetermined.
- End statements with a semicolon (;).
- Variable names can use letters, numbers, $, and _.
Spaces are not allowed; the first character must not be a number. - Strings are case-sensitive.
- Naming convention for statements is camel case.
console.log(variableName or "string" or function, etc.)You can output multiple values at once by separating them with a comma (,).
console.log(variableName, "string", function())
// Single-line comment
/* Multi-line comment */
- Variables
Specific memory addresses that store values.
Declaring a variable = giving a variable a name. - Initialized
Deciding what value to put into a variable initially.
Initialization prevents unexpected values, errors, and bugs.
If not initialized, `console.log()` or similar screen output will display "undefined". - Variables
Specific memory addresses that store values.
Declaring a variable = giving a variable a name.
* Global Scope
Variables declared outside of functions or blocks like for loops.
* Local Scope
Variables declared inside a function.
Accessing the variable from outside the block will result in a reference error. - Immutable
A property of String (and other types) that means they are unchangeable once created.
Even if a different value is assigned to a variable, making it appear as if the value has changed, a new string is actually created.
This not only prevents unintended operations but also makes program behavior more predictable as strings are not changed, and optimizes memory management and performance. - Mutable
A property of Array (and other types) where their values or states can be changed after they are created. - Non-primitive
Mutable data types that are not undefined, null, boolean, number, string, or symbol. - DOM (Document Object Model)
An API (mechanism) used when JavaScript interacts with HTML and XML.
Loads the document structure of HTML or XML as a tree of nodes.
= Represents each element (tags, text, etc.) within a document as an object,
and manages these objects in a tree structure.
By manipulating the DOM from JavaScript, you can dynamically change the content, structure, and style of a web page.
Reference - NodeList
An object used in the DOM that represents a collection of nodes (such as HTML elements).
= Manages a list of nodes (similar to an array).
Although similar to an array, it is not an array, so operations like `push()` that are performed on arrays are not possible. - Constructor
Similar to a regular function but starts with a capital letter and is initialized with the `new` operator.
A special function for creating new objects and performing their initialization.
= Creates new objects based on the class definition. - Hoisting
Function declarations are interpreted before function calls, regardless of where they are declared in the code.
= It is possible to call a function before declaring it.
Refactoring (changing the internal structure of source code without altering its external behavior), such as using the ternary operator, can aim to improve code readability and performance.
| Name | Symbol | Description |
|---|---|---|
| Equality Operator | == === |
Does not check data type (e.g., 0=="0" → True) Checks data type (e.g., 0==="0" → False) |
| Inequality Operator | !== | Checks that value and data type are not equal. |
| Remainder Operator | % | Returns the remainder. |
| Exponentiation | ** | |
| AND | A && B | |
| OR | A || B | |
| Increment | ++ // compound assignment i += 1 // increment operator i++ |
Operation to increase by 1 (i = i + 1) Caution: The `+=` operator cannot be applied directly to properties of uninitialized (undefined) objects. |
| Decrement | -- // compound assignment i -= 1 // decrement operator i-- |
Operation to decrease by 1 (i = i - 1) |
| Ternary Operator | Condition ? True_case : False_case; | `if-else` statements can be refactored with the ternary operator. |
JavaScript does not have an operator that returns only the quotient of a division.
If only the integer quotient is needed, you can calculate it using the `Math.floor()` function.
let integerQuotient = Math.floor(dividend / divisor);
// if-else statement
if (score > 0) {
return score
} else {
return default_score
}
// ternary operator
return score > 0 ? score : default_score
// It's also possible to set the ternary operator for variables
const variable_to_set = value_to_check < 0 ? less_than_0 : 0_or_more;
Unlike other programming languages, explicit variable type specification is not required.
| Declaration Method | Features |
|---|---|
let |
Variable reassignment is possible. Basically use `let` when declaring variables. |
| const | A value assigned once cannot be changed later. Declares a variable as a constant. |
| var | Has function scope and allows variable redeclaration. More flexible than `let` or `const` but incorrect use can lead to bugs. Generally should not be used. |
let variableName; // Declare a variable
variableName = "value"; // Initialize the variable
variableName = "value" or otherVariableName; // Change the value of the variable
| Data Type | Notes |
|---|---|
| String | Enclosed in single quotes (') or double quotes ("). Immutable. |
| Number | Single quotes (') or double quotes (") are not required. |
| Boolean | true / false ※Must always be all lowercase. The following falsy values are recognized as false: false, 0, "", null, undefined, NaN |
| Objects | A non-primitive data type that stores key-value pairs. |
To create a new object, use the `new` keyword.
- null
No value. - Array
A data structure for storing data of the same type in contiguous memory locations.
Each element is sequentially assigned a number (index) starting from 0.
Data stored in an array is called "elements", and the maximum size that can be stored is called "size".
Mutable (i.e., elements can be added, deleted, or modified). - Stack
A data structure stored in a LIFO (last-in-first-out) manner. - Call
A collection of function calls stored in a stack structure.
When a function is called, it is added to the top of the stack, and when the function returns, it is removed from the top/end of the stack.
Events refer to occurrences on a web page.
In JavaScript, various events occur, such as:
・User interaction: clicks, mouseovers, key input, etc.
・Web browser actions: page load completion, form submission, etc.
・Timers: after a certain period of time, etc.
Overall diagram of JavaScript Events
Events like the ones above can be handled by registering a corresponding **EventHandler (= a function executed when an event occurs)**.
= In JavaScript, you define event handlers that are executed when an event occurs.
An EventHandler can be defined using one of the following two methods:
1. Write it as an attribute of an HTML element
2. Define it within JavaScript code
When an event occurs, an event object containing information about the event is generated.
The event object provides information about the occurred event,
including the type of event, the source element, mouse coordinates, and input characters.
By receiving the event object as an argument in the EventHandler, you can obtain event-related information and use it for processing.
An EventListener is a mechanism that tells the web browser which function to execute when a specific event occurs.
You register an EventListener to a DOM element using the `addEventListener()` method.
This allows you to register multiple EventHandlers to a single element or add EventHandlers later.
In the DOM tree structure, when an event occurs on an element, that event may propagate to its parent elements.
There are two methods of event propagation:
・Event Bubbling: The method where the event propagates from the child element to the parent element.
・Event Capturing: The method where the event propagates from the parent element to the child element.
You can specify the event propagation method using the third argument of the `addEventListener()` method.
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
click |
When the element is clicked | If an `` element is clicked, navigate to the linked page. |
cdblclickc |
When the element's value is changed AND the element is double-clicked. |
|
mousedown |
When a mouse button is pressed over an element | |
mouseup |
When a mouse button is released over an element | |
mousemove |
When the mouse cursor moves over an element | |
mouseover |
When the mouse cursor moves onto an element | |
mouseout |
When the mouse cursor moves out of an element | |
mouseleave |
When the mouse cursor leaves an element |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
keydown |
When a key is pressed | |
keyup |
When a key is released | |
keypress |
When a key is pressed and released (Deprecated) |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
submit |
When the form is submitted HTML form submission, button or Enter key click, etc. |
The form submission process is executed |
change |
When the value of a form element is changed When the element's value is changed AND the element loses focus. |
If the value of a `` element is changed, the selected option is changed. |
focus |
When a form element receives focus | |
blur |
When a form element loses focus | |
input |
When the value of an input element changes |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
load |
When the page has finished loading | |
unload |
When the page is being closed | |
resize |
When the window size is changed | |
scroll |
When the page is scrolled |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
DOMContentLoaded |
When the HTML document is fully loaded and parsed *Does not wait for images, stylesheets, or subframes to complete. |
|
readystatechange |
When the Document's readyState property changes |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
touchstart |
When a finger touches the touchscreen | |
touchmove |
When a finger moves on the touchscreen | |
touchend |
When a finger is lifted from the touchscreen | |
touchcancel |
When a touch operation is interrupted |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
dragstart |
When dragging of an element begins | |
drag |
While an element is being dragged | |
dragenter |
When a dragged element enters a drop target | |
dragover |
When a dragged element is over a drop target | |
dragleave |
When a dragged element leaves a drop target | |
drag |
When a dragged element is dropped onto a drop target | |
dragend |
When a drag operation ends |
| Event Name | Occurrence Timing | Default Behavior |
|---|---|---|
play |
When media playback begins | |
pause |
When media playback is paused | |
ended |
When media playback ends | |
volumechange |
When media volume is changed |
Web pages are loaded in the following order:
Therefore, depending on the writing method, functions or events may be executed before loading is complete, leading to errors.
(Example) Errors occurring when performing DOM operations before HTML loading is complete.
Processing Timing:
1. HTML Parsing: The browser parses the HTML file from top to bottom and begins constructing the DOM tree.
2. `script` tag execution: When a `script` tag is encountered, the browser temporarily pauses HTML parsing and executes the JavaScript code within that `script` tag.
3. `DOMContentLoaded` Event Occurrence: When HTML parsing is complete and the DOM tree is fully constructed, the `DOMContentLoaded` event occurs.
*At this point, external resources such as images and CSS may not yet have finished loading.
4. Callback Function Execution: Immediately after the `DOMContentLoaded` event occurs, the callback function registered with `document.addEventListener('DOMContentLoaded', ...)` is executed.
// if: Performs processing if the condition is true
if (condition1) {
process
} else if (condition2) {
process
} else {
process
}
// switch: Executes different processing depending on the condition
switch (conditionalExpression) {
case value1:
console.log("Matches case 1");
break;
case value2:
console.log("Matches case 2");
break;
// Processing to execute if no case matches
default:
console.log("No match");
}
When setting a Boolean value for a condition, simply write `if (true)` instead of `if (variable === true)`.
for (let i = 0; repetitionCondition; i = i + 1) {
process
}
for (let variable of array/iterableObject) {
process
}
// while: Repeats processing as long as the condition is met
while (condition) {
process
}
Optional Chaining:
A syntax that prevents errors from occurring when accessing object properties or methods if those properties or methods do not exist.
const user = {
address: {
street: 'Main Street',
city: 'New York'
}
};
// Without optional chaining
const city = user.address.city; // If the address property does not exist, an error will occur
// With optional chaining
const city = user?.address?.city; // No error occurs, and city becomes undefined
A writing method enclosed by ` (backtick character) instead of " (double quotes) / ' (single quotes).
Allows variables to be included within strings, making it possible to handle strings more flexibly in JavaScript.
Offers higher code readability than concatenating strings enclosed in " (double quotes) / ' (single quotes) with the + (addition operator).
Variables are enclosed in `${}`.
Function calls are also possible within template literals.
const name = "Tom";
const templateLiteral = `Hello, my name is ${name}~!`; // template literal
console.log(templateLiteral);
// When you want to call a function within a template literal
`${functionToCall(arguments)}
`
A convenient feature in JavaScript for expanding arrays, objects, and strings.
`[...]` is the notation used to "expand" elements of arrays or objects.
You can extract the contents of arrays or objects and expand them into other arrays or objects, or expand them as function arguments.
// Array concatenation
const array1 = [1, 2];
const array2 = [3, 4];
const combinedArray = [...array1, ...array2]; // [1, 2, 3, 4]
// Array copy
const array1 = [1, 2];
const array2 = [...array1]; // [1, 2]
// Expanding an array as function arguments
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers); // 6
try {
// Code that may cause an error
} catch (error) {
// Code to execute if an error occurs
console.error("An error occurred:", error);
} finally {
// Code that is always executed (optional)
console.log("Processing complete");
}
There are two ways to declare functions.
1. Function declaration Classical function declaration method function functionName(parameter) {code to process within the function} Hoisting: Possible 2. `const` and Arrow Function A new function definition method introduced in ES6.Allows for more concise writing than function declarations.
→ May not be supported in older browsers.
Suitable when you want to clarify `this` handling or when a function expression is needed.
Useful when passing functions to other functions or storing them in arrays. const functionName = (parameter) => {code to process within the function} Hoisting: Not possible
// Function declaration
function functionName(parameter) {
// Write processing
return returnValue;
}
// Function call
functionName(argument);
Parameter: A special variable to which a value is given when the function is called.
Can dynamically change the result of the function.
Argument: The value passed to the function's parameter when calling the function.
`return` keyword: Stops the execution of code within a function or block.
= No processing can be written after `return`.
Hardcode: Refers to code where strings like "Hello!" are explicitly written within the function, which reduces reusability.
Define parameters for functions to prevent hardcoding.
// Function call (the function's processing is executed)
functionName()
// Function reference (the function itself is not executed)
functionName // The function itself is treated as a value, used when passing functions to other functions or utilizing higher-order functions
Syntax for writing functions more concisely.
Anonymous functions.
Allows for particularly shorter function definitions compared to traditional functions defined with the `function` keyword.
Does not have its own `this`, which can prevent unintended references.
If there is only one argument: parentheses can be omitted.
If there are no arguments: empty parentheses are required.
If the process is a single line, curly braces and `return` can be omitted.
// Arrow function definition
const exampleFunction = () => {
// code goes here
}
// Arrow function call
exampleArrowFunction();
// Definition of an arrow function with one argument
const exampleFunction = parameter => {
console.log(`Hello, ${name}!`);
};
// Calling an arrow function with arguments
exampleArrowFunction(parameter);
// Definition of an arrow function with two or more arguments
const exampleFunction = (parameter1, parameter2) => {
return parameter1 * parameter2;
};
// Calling an arrow function with arguments
multiplyTwoNumbers(3, 4);
Explicitly return: Write `return`.
const isSpam = (msg) => {
return false;
};
Implicitly return: Do not write `return`.
const isSpam = msg => false;
Functions that can perform asynchronous processing (= concurrent processing).
Often used when fetching data via API using `fetch()` (asynchronous communication: an asynchronous operation).
Don't forget to implement exception handling with `try-catch`.
// Creating a fetch asynchronous function
// For function declaration
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
// For arrow function
const fetchData = async () => {
const res = await fetch(forumLatest);
const data = await res.json();
};
Async/Await: The `await` keyword handles the asynchronous nature of the `fetch()` method.
A function without a name.
While regular functions are identified by name, anonymous functions can be assigned to variables, passed as arguments to other functions, or executed directly on the spot.
A data structure that stores key-value pairs.
In JavaScript, arrays and variables are also treated as types of objects.
Blueprints for objects in object-oriented programming.
// Class Declaration
class ClassName {
// method
constructor(pram1, pram2) {
// my code here
}
};
// Creating an instance
const variableName = new Class();
this: A very important keyword in object-oriented programming.
Points to the current object.
※Even with the same 'this', the object it refers to changes depending on where 'this' is used.
const ObjectName = {
key1 = value1,
key2 = value2
};
Property: Something like a variable that an object possesses.
A key and a value form one property set.
key: The name of the property.
If it contains spaces, it must be enclosed in double quotes (").
value: The data stored in the property.
Storing objects in an array.
const locations = [
// Object
{
key1: value1, // Property
key2: value2
},
{
key1: value3,
key2: value4
}
];
There are several ways to access the values of an object.
1. Dot notation
The most common method.
Accessed by `objectName.propertyName(=key)`.
2. Bracket notation
Used when the property name is a variable or contains special characters.
Accessed by `objectName[variableName]` or `objectName["stringLiteral"]`.
3. Object destructuring syntax
Allows for more concise and intuitive code than traditional assignment.
Accessed by `const {keyName1, keyName2} = objectName;`.
// Object definition
const car = { // Object name
color: "red", // Property name and value
maker: "Corp",
year: 2023
};
// Accessing properties
console.log(car.color); // "red" // Dot notation
console.log(car["color"]); // "red" // Bracket notation
let key = "maker";
console.log(car[key]); // "red" // Bracket notation
const {color, maker} = car; // destructuring
// Changing values
car.year = 2024;
Built-in objects: Objects pre-prepared in the JavaScript execution environment.
Property: Represents data or attributes that an object possesses (= state).
A function associated with a specific object and defined as its property.
Methods are functions called through their object,
used to manipulate the object's state or behavior.
object.myMethod()
Among built-in objects, it refers to an object that is always available in the environment where a JavaScript program is executed.
Properties and methods of the global object can be accessed from anywhere.
The ancestor object of all objects in JavaScript.
All objects inherit properties and methods from Object.prototype.
| Method | Function |
|---|---|
Object.create() | |
Object.key() | |
Object.value() | |
| .hasOwnProperty() | Checks if the specified property exists in the object. Returns a boolean value. |
.constructor()
| A constructor is a special method called first when an object is created. It is used to perform necessary initialization processes when creating a new object. Use cases: ・Object initialization ・Setting initial values for object properties ・Creating other objects that the object depends on ・Opening resources used by the object (files, databases, etc.) |
| Method | Function |
|---|---|
.test()
| Can test regular expressions, etc. |
RegExp.prototype.test() | |
RegExp.prototype.exec() |
Used to control the entire browser window where a web page is displayed, or to get information about the window.
Since it is a global object, global variables declared with `var` or `let` become properties of the `window` object.
Global functions like `alert()` and `console.log()` are actually called as `window.alert()` and `window.console.log()`.
Since the window object is a global object, `window.` can be omitted when calling its properties or methods.
| Property | Function |
|---|---|
| Opens a window |
| Current URL |
| Displays browser information |
| Displays browser history |
| Inner width and height of the window |
| Total width and height of the window |
| Method | Function |
|---|---|
| Opens a window Closes a window |
| Changes the size of the browser window to the specified width and height. Specified in pixels. |
| Moves the window to the specified x and y coordinates. |
| Outputs a popup |
| Sets a timer |
| Scrolls the window |
| Displays a confirmation dialog |
| Displays an input dialog |
| A powerful API for asynchronous communication with web servers. Supports various HTTP methods (requests) such as GET, POST, PUT, DELETE. Retrieves and extracts data. If the request is successful, it returns a Promise (a placeholder object). The Promise resolves to a Response object, (= The Promise returns a Response object) You can access the Response using the `.then()` method. ※If it fails, it is rejected. |
| alert('Message text'); | A function that displays a small dialog box in the browser. The specified string will be displayed in this dialog box. |
An object for handling numerical values.
Provides numerical conversions, and constants and functions related to numbers.
| Method | Function |
|---|---|
| Determines whether the argument is `NaN (Not a Number)`. If the argument is non-numeric → `true` If the argument is numeric → `false` |
| Converts a string to an integer. Returns NaN (=Not a Number) if it cannot be converted to an integer. |
Regular built-in objects that are not global objects exist as properties or methods of specific objects.
To use these objects, you first need to access their parent object.
Provides access to the console within the browser's developer tools.
Mainly used for debugging and logging output.
| Method | Function |
|---|---|
| Outputs to the console. General log. |
| Outputs information messages. |
| Outputs warning messages. |
| Outputs error messages. |
| Displays object properties in a tree structure. |
| Displays objects or arrays in a table format. |
| Starts time measurement. |
| Ends time measurement and displays elapsed time. |
| Groups logs. |
| Ends grouping. |
| Displays the function call history. |
| Displays an error message if the condition is false. |
An object for handling strings.
| Method | Function |
|---|---|
| .length() | Gets the length of the string. |
.split()
| Splits a string. To perform flexible splitting, use a regular expression inside the parentheses. |
| .repeat() | Returns a new string by copying the calling string the specified number of times and concatenating them. |
| .toLowerCase() .toUpperCase() | Converts all characters to lowercase. Converts all characters to uppercase. |
variableName/value.replace(pattern, replacementString/function);
| Replaces a value. Pattern: String/Regular Expression, etc. |
| .match(regularExpression) | Can be used on strings. |
| .charCodeAt() | Returns the Unicode character code as a number. |
Performs mathematical calculations.
| Property | Information Retrieved | Example |
|---|---|---|
| Math.random() | Generates a random number between 0 (inclusive) and 1 (exclusive). | |
| Math.floor() | Rounds down a given number to the nearest integer. | |
| Math.abs(value/variable) | Returns the absolute value. | |
| Math.sqrt(radicand) | Calculates the square root. | Math.sqrt(9) → 3 |
| Math.pow(base, exponent); | Returns the value of base raised to the power of exponent. | Math.pow(3, 2) → 9 |
Performs date and time calculations.
| Property | Information Retrieved |
|---|---|
| Date.getDate(); | Gets the day of the month from a date. |
| Date.getMonth(); | Gets the month from a date. |
| Date.getFullYear(); | Gets the full year (4 digits) from a date. |
| Date.getHours(); | Gets the hour from a date/time. |
| Date.getMinutes(); | Gets the minutes from a date/time. |
Manipulate objects
| Property | Information Obtained |
|---|---|
| Object.freeze(objectName); | Makes the object unchangeable |
| Object.localStorage object; | A mechanism to persistently store data in the user's browser |
| localStorage.setItem("key", value); | Saves data to the web browser's local storage |
| localStorage.removeItem('ItemName'); | Deletes a specific item from local storage |
| localStorage.clear(); | All items are deleted from local storage |
HTML elements are expressed hierarchically
console.dir(document)| Property | Information Obtained |
|---|---|
| document.innerHTML; | The HTML content within the tag |
| document.nodeName; | The name of the node (e.g., title, input) |
| document.id; | The value of the HTML element's ID attribute |
| document.parentNode; | Reference to the parent node |
| document.childNodes; | Array of child nodes |
| document.attributes; | Array of HTML element attributes (e.g., src of an img tag) |
| document.style; | CSS styles |
// Get all p tags
const paragraphs = document.querySelectorAll('p');
// Get elements with class name "my-class"
const myClass = document.querySelectorAll('.my-class');
// Get element with id "my-id"
const myId = document.querySelectorAll('#my-id');
// Select all corresponding elements by specifying multiple selectors
const elements = document.querySelectorAll('p, h1, .my-class');
// Select all descendant elements
const linksInDiv = document.querySelectorAll('div a');
// Get the very first "h1" element
let h1 = document.querySelector("h1");
// Get the very first element with id "button1"
const button1 = document.querySelector("#button1");
// Get the element with id "title"
const mainTitleElement = document.getElementById('title');
// Delete all child elements
const parentElement = document.getElementById('parent');
const childElements = document.querySelectorAll('.child');
.remove() or
childElements.forEach(element => {
parentElement.removeChild(element);
});
Array object
JavaScript arrays are a type of object and come with various methods.
Similar to C language and Java, declare arrays by specifying the element type.
It is dynamically typed, allowing arrays to mix elements of different types.
let array = []; // Declare an array
let array = [value1, value2, value3]; // Put values into an array
console.log(array); // Display all values in the array
console.log(array[0]); // Display the first value in the array
let i = array.length // .length (property to get the number of elements in an array)
// Check if a value is included in the array
if (arrayName.includes(value)) {
// Write processing
}
// Remove duplicate values from an array
const nums = [1, 2, 3, 2, 4, 1];
const uniqueNums = [...new Set(nums)]; // [1, 2, 3, 4]
// call data
const callStack = [
`string`,
'string',
"string"
]
| Method | Information Obtained |
|---|---|
|
Adds a value to the end of the array |
|
Removes the last value from the array |
|
Adds a value to the beginning of the array |
|
Removes the first value from the array |
|
Converts to an array Can be used to convert a NodeList to an array |
| arrayName.sort() (Example provided below the table) |
Sorts the array in ascending order Sorted after conversion to UTF-16 strings |
|
Used to iterate over an array and return a new array |
|
Concatenates all elements of an array into a single string |
| .indexOf() | Returns the first index at which a given element can be found in the array |
|
Processes each element of an array and ultimately combines them into a single value. Useful for calculating sums or averages. If the initial value for the second argument is not specified, the first element of the array is used as the accumulator. |
| variable/array.includes(stringToCheck/variableName) | Returns a boolean value (true/false) |
| .arrayName.find(function); | Used to find a single element that matches a specific condition. Returns `undefined` if no matching element is found. |
|
Executes the specified function for each element in the array |
| .some() | Checks if at least one element in the array satisfies a condition. Returns a boolean value (true/false). |
| .filter() | Returns a new array containing elements from the array that satisfy a condition. |
| .toSorted() | Creates a new array |
| .reverse() | Reverses the order of elements in an array. The original array itself is modified. ※Does not create a new array. |
| .slice() | Extracts a specified range of elements from an array or string and returns them as a new array or string. ※The original array or string is not modified. |
const numbers = [1, 2, 3, 4, 5];
// Find the first element in the 'numbers' array that is greater than 3
const foundNumber = numbers.find(number => number > 3);
console.log(foundNumber); // Output: 4
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Extract the first two elements
const firstTwo = nums.slice(0, 2); // [1, 2]
// Extract the last two elements
const lastTwo = nums.slice(-2); // [9, 10]
ArrayName.sort((a, b) => {
// If the first array name is smaller than the second array name, sort the first and second arrays.
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
const developerObj = {
name: 'John',
age: 34,
}
developerObj.hasOwnProperty('name'); // true
developerObj.hasOwnProperty('salary'); // false
An object that holds information about a dispatched event.
When an event occurs, it is generated by the browser and passed as an argument to the event handler.
It provides information such as the type of event, its source, and the time it occurred.
= An object that holds information about events occurring in the DOM (Document Object Model).
| Property | Information Obtained |
|---|---|
type |
A string indicating the type of event that occurred. e.g., "click", "mouseover" |
target |
The element on which the event occurred. |
currentTarget |
The element to which the event listener is attached. |
timeStamp |
The time the event occurred (in msec). |
| Method | Function |
|---|---|
.preventDefault() |
Cancels the default action of the event. |
.stopPropagation() |
Stops the propagation of the event. |
An object for manipulating the HTML `<audio>` element from JavaScript.
Allows playing, pausing, and adjusting the volume of audio files.
| Method | Function |
|---|---|
audio.play(); |
Plays audio using `<audio>`. |
audio.pause() |
Pauses audio using `<audio>`. |
audio.load() |
Reloads the audio file. |
Objects for manipulating HTML document elements (tags) from JavaScript.
DOM elements are objects provided by environments that display web pages, such as browsers.
DOM elements are not part of the JavaScript language specification, but rather part of the Web browser's API (Application Programming Interface).
| Method | Function | |
|---|---|---|
|
Registers an event listener (a function to be executed when an event occurs) for an HTML element. | |
|
Used to remove a specified attribute from an HTML element. | |
|
Adds a class attribute to an HTML element. | |
|
Returns a NodeList of all elements that match the selector. The argument can combine various conditions such as element, class, id, tag name, and attributes to filter elements. |
|
|
Returns **all** elements that match the element specified in the argument. The argument can combine various conditions such as element/class/id/tag name/attribute to filter elements. |
|
|
Returns the **first** element that matches the element specified in the argument. The argument can combine various conditions such as element/class/id/tag name/attribute to filter elements. |
|
|
Returns exactly one element whose id matches the argument. The retrieved value is a string; convert it with parseInt() or parseFloat() if you want to treat it as a number. |
|
|
Adds a new attribute to an HTML element or changes the value of an existing attribute. | |
|
Creates an HTML element. | |
|
Creates an HTML text node. | |
|
Appends a child element. | |
| .toggle() | Adds a class to an element if it doesn't have it, and removes it if it does. Combines .classList.add() and .classList.remove(). |
|
|
Can be used on an HTML dialog element to display a modal window. | |
|
Disables form elements (buttons, text boxes, etc.). |
Due to the order of processing, the timing of registering event listeners is very important when using `document.addEventListener`.
Event listeners must be registered after the HTML document's elements are fully loaded and the DOM (Document Object Model) is constructed.
If the timing is not correct, errors may occur because the DOM to be loaded does not exist.
There are 3 ways to avoid this:
1. Using the `DOMContentLoaded` event (Recommended)
The `DOMContentLoaded` event fires when the HTML document has been completely parsed and the DOM tree has been built.
It fires even before external resources like images, stylesheets, and subframes have finished loading, allowing event listeners to be registered relatively early.
document.addEventListener('DOMContentLoaded', function() {
// Code to register event listeners here
document.getElementById('answerCheck2').addEventListener('click', function()
{
// Code to execute
});
});
2. Placing the `<script>` tag at the end of the HTML
Since HTML documents are parsed and executed from top to bottom, JavaScript will only execute after all DOM elements have finished loading.
However, the execution of JavaScript code may be delayed compared to the DOMContentLoaded event because it waits for all HTML elements to load.
<body>
<script>
document.getElementById('answerCheck2').addEventListener('click', function()
{
// Code to execute
});
</script>
</body>
3. Adding the `defer` attribute to the `<script>` tag
The script is downloaded in parallel with HTML parsing, but script execution is delayed until HTML parsing is complete.
However, older browsers may not support it.
<head>
<script defer>
document.getElementById('answerCheck2').addEventListener('click', function()
{
// Code to execute
});
</script>
</head>
<body>
</body>
innerText: Controls the text displayed within an HTML element.
innerHTML: Gets/changes the content of an HTML element using JavaScript.
---HTML ---
<p id="info">Sample Text</p>
// JavaScript
const currentValue = document.getElementById("info");
console.log(currentValue.id); // "info"
console.log(currentValue.tagName); // "P"
console.log(currentValue.textContent); // "Sample Text"
// When the web page loads, "SampleText" is written, but JavaScript execution changes it to "Hello World".
info.innerText = "Hello World";
console.log(currentValue.textContent); // "Hello World"
// Rewriting HTML
info.innerHTML = "<h3>Changed!</h3>";
// Rewriting CSS
info.style.color = "blue";
button_id.style.display = "block"; // Display
button_id.style.display = "none"; // Hide
onclick: Executes on click.
// Calls myFunction when the is clicked.
button.onclick = myFunction;
An object used in JavaScript and Python to store specific categories and their associated information.
Used in blog platforms, e-commerce sites, learning platforms, etc.
const allCategories = {
299: { category: "Career Advice", className: "career" },
409: { category: "Project Feedback", className: "feedback" },
417: { category: "freeCodeCamp Support", className: "support" },
421: { category: "JavaScript", className: "javascript" },
423: { category: "HTML - CSS", className: "html-css" },
424: { category: "Python", className: "python" },
432: { category: "You Can Do This!", className: "motivation" },
560: { category: "Backend Development", className: "backend" },
};
By using shorthand character classes, you can match specific characters without explicitly writing them in the pattern.
= Used to match specific characters within a string.
Often abbreviated as "regex".
Syntax: /string_to_check_for_match/
Enclosing in [ ] will match any of the characters within in any order.
Using | (alternation) allows you to specify multiple patterns.
Regular expressions have escape sequences, so check for them if errors occur.
// Checks if it contains "hello"
const regex = /hello/;
// Checks if it matches any single character from h, e, l, o in any order
const regex = /[helo]/;
// Checks if it matches "yes" or "no"
const regex = /yes|no/;
const str = 'example string';
const regex = /example/; // Regular expression
const result = str.match(regex); // Returns ['example']
If a match is found, the console will display the following:
[ 'matched_value_by_regex', index: index_of_matched_value_in_string, input: 'original_matched_string', groups: matched_groups ]
※ If no match is found, null will be outputted.
Flags
g (global): Continues pattern matching search after the first match.
const regex = /hello/g;i (insensitive): Ignores case (case-insensitive).
const regex = /Hello/i;
// Can search for hello, Hello, HELLO, hElLo, etc.
Character class [0-9]: Notation to match any digit.
Using the "+" quantifier in regular expressions allows matching patterns that appear one or more times.
To match a digit pattern one or more times, add a plus after the character class for each digit.
\d: A shorthand character class for [0-9] that matches any digit.
const regex = /[0-9]+/; // Character class
const regex = /\d+/g; // Shorthand character class
Capture Groups
In regular expressions, a mechanism for reusing matched substrings later.
By grouping a part of the matched string and assigning a number to that group, you can extract specific substrings, not just the entire matched string.
Enclosed in ( ).
Non-capturing Groups
Written with (?: ).
?: Optional (matches zero or one time).
// Matches the preceding character 0 or 1 time.
const regex = /cat?s/;
console.log(regex.test("cat")); // true
console.log(regex.test("cats")); // true
You need to create a special JavaScript object called `XMLHttpRequest`.
This object allows you to send requests to a server asynchronously and retrieve additional information after the page loads or refreshes, rather than at the same time.
function ajax_request(argument)
{
// Creates an XMLHttpRequest object.
var aj = new XMLHttpRequest();
aj.onreadystatechange = function() {
// If the request is complete and the response from the server is successful.
if (aj.readyState === 4 && aj.status === 200) {
// do something to the page
}
};
aj.open("GET", /* url */, true);
aj.send();
}
The `XMLHttpRequest` object has an `onreadystatechange` property that is executed whenever the request's state changes. It has 5 states from 0 to 4.
`0` (UNSENT): Request not yet initialized.
`1` (OPENED): `open()` method has been called, and the request is ready.
`2` (HEADERS_RECEIVED): `send()` method has been called, the server has accepted the request, and response headers are available.
`3` (LOADING): Downloading the response body. `responseText` may contain partial data.
`4` (DONE): Request completed (entire data has been loaded).
Ultimately, if successful, `Status 200` will be returned from the server.
※ The above describes the standard behavior of the HTTP communication protocol.
When a program runs automatically, its behavior may differ from the user's screen.
If you want to execute with similar behavior, write the following code:
// When running automatically, execute with similar behavior to the user's screen.
document.querySelector('#purchase-btn').click();
In the console tab of developer mode, you can see where errors occur.
You can also check the output of `console.log()`.
D3 stands for Data-Driven Documents.
It is a JavaScript library for data visualization.
It allows you to create complex graphs and interactive visualizations on web pages.
D3.js has its own set of DOM manipulation methods that wrap the standard DOM API, supporting almost all aspects of data visualization.
However, D3.js's DOM manipulation can be idiosyncratic, making it sometimes difficult to use by simply copying and pasting samples and making minor modifications.
- Data-driven: Manipulates the DOM (Document Object Model) based on data to create dynamic visualizations.
- Flexibility: Enables highly flexible visualizations by combining SVG, HTML, CSS, etc.
- Graph creation: Creates various types of graphs such as line graphs, bar charts, pie charts, and scatter plots.
- Map display: Creates maps using GeoJSON data and overlays data.
- Interactive visualization: Visualizations that change in response to user operations.
- Animation: Visually clear expressions achieved by animating graph elements.
Data visualization is performed by linking data, scales, and visual representations.
It is only displayed on the screen when placed within an SVG drawing area.
(1) Use a CDN
<head>
<!-- Importing D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js" integrity="sha512-M7nHCiNUOwFt6Us3r8alutZLm9qMt4s9951uo8jqO4UwJ1hziseL6O3ndFyigx6+LREfZqnhHxYjKRJ8ZQ69DQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
</html>
(2) Save locally and use
<html>
<head>
<!-- Importing D3.js -->
<script src="d3.v7.min.js"></script>
</head>
</html>
Prepare data in array or JSON format.
<body>
<script>
const data = [10, 20, 30, 40, 50];
</script>
</body>
SVG: An XML-based format for embedding images and graphics on web pages.
<script>
// prepare datas for creating graph
const data = [10, 20, 30, 40, 50];
// add below code
// create SVG element
const svg = d3.select("body") // Which element to create SVG for
.append("svg") // Create a SVG element for selected elements
.attr("width", 500) // Set the “width” attribute of the SVG created
.attr("height", 300); // Set the “height” attribute of the SVG created
</script>
Bind data to elements using the data() method.
<script>
// prepare datas for creating graph
const data = [10, 20, 30, 40, 50];
// create SVG element
const svg = d3.select("body") // Which element to create SVG for
.append("svg") // Create a SVG element for selected elements
.attr("width", 500) // Set the “width” attribute of the SVG created
.attr("height", 300); // Set the “height” attribute of the SVG created
Scatter Plot
// add below code
// Link datas and elements
svg.selectAll("circle") // Select elements to link datas
.data(data) // Link datas to selected elements
.enter() // Create actually elements
.append("circle") // Add elements to link datas
.attr("cx", (d, i) => i * 50 + 25) // Set an attribute
.attr("cy", 50) // (same as above)
.attr("r", (d) => d); // (same as above)
</script>
Bar Chart
// add below code
// Link datas and elements
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 25)
.attr("height", 100);
</script>
The steps to add X and Y axes with D3.js are:
1. Create scales: Create scales to map the data range to the graph's coordinate system.
2. Generate axes: Generate axes using d3.axisBottom() or d3.axisLeft() and set the scales.
3. Add axes: Append axes to the SVG and adjust their position and style.
// Create Scale
const xScale = d3.scaleLinear()
.domain([0, data.length - 1]) // an index of datas
.range([0, 500]); // a range of X-axis
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)]) // a maximum data
.range([300, 0]); // a range of Y-axis
// Create axis
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// Add axis to the SVG element
svg.append("g")
.attr("transform", "translate(0," + 300 + ")")
.call(xAxis);
svg.append("g")
.call(yAxis);
The steps to add X and Y axes with D3.js are:
1. Create scales: Create scales to map the data range to the graph's coordinate system.
2. Generate axes: Generate axes using d3.axisBottom() or d3.axisLeft() and set the scales.
3. Add axes: Append axes to the SVG and adjust their position and style.
// Create Scale
const xScale = d3.scaleLinear()
.domain([0, data.length - 1]) // an index of datas
.range([0, 500]); // a range of X-axis
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)]) // a maximum data
.range([300, 0]); // a range of Y-axis
// Create axis
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// Add axis to the SVG element
svg.append("g")
.attr("transform", "translate(0," + 300 + ")")
.call(xAxis);
svg.append("g")
.call(yAxis);
You can add a title to the top of the graph using the SVG text element.
// Add title to SVG
svg.append("text")
.attr("x", width / 2)
.attr("y", 20)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.text("Graph's Title");
You can add a legend using the SVG g element.
// Create legend group
var legend = svg.selectAll(".legend")
.data(data)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
// Add rectangle in legend
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d) { return color(d.key); });
// Add label in legend
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.key; });
// Add data labels
svg.selectAll(".do\t")
.data(data)
.enter().append("text")
.attr("class", "label")
.attr("x", function(d) { return xScale(d.x); })
.attr("y", function(d) { return yScale(d.y); })
.attr("dy", "-.35em")
.text(function(d) { return d.y; });
Provided by the library, these are not original built-in JavaScript methods.
| Method | Function | Example Code |
|---|---|---|
| select("target element") | Selects the first matching element from the document. | |
| selectAll("target element") | Gets all matching elements from the document as an array. | |
| append("adding element") | Adds one element to the document. | |
| text("adding text in target element") | Adds text to the selected element. | |
| data(dataset) | Binds DOM elements (selected elements) with a data array. | |
| enter() | Creates a selection for adding missing elements. | |
| style("property", "value") | Specifies the style of the selected element. | |
| attr("property", "value") | Adds an inline style. | |
| scaleLinear() | Generates a linear scale (axis). | |
| domain() | Specifies the minimum and maximum values of the data. | |
| range() | Specifies the output range for visual representation. | |
| axisBottom()/axisLeft() | Creates an axis at the bottom/left of the graph. | |
| call() | Calls the generated axis generation function, and draws the axis on the SVG element. |
|
Add suffix to text
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("h2")
.data(dataset)
.enter()
.append("h2")
.text(function(d) {
return d + " USD";
});
</script>
One of JavaScript's libraries, a tool for easily manipulating dynamic elements on web pages.
It allows for concise JavaScript code and can significantly increase development efficiency.
It abstracts away browser differences, making cross-browser development easier.
In recent years, with the emergence of React and similar frameworks, the use of jQuery has been declining.
- `$` function
Selects DOM elements based on a selector and generates a jQuery object.
`$('selector')`
The selector can use notation similar to CSS selectors. - jQuery object methods often return the jQuery object itself.
This allows multiple methods to be chained, leading to concise code.
(= Method Chaining) - By calling various jQuery methods on the jQuery object generated by the `$` function,
you can perform DOM manipulation, event handling, and more. - Methods are provided to concisely write event handling.
`$('selector').on('eventName', function);`
By using the `on()` method,
you can register multiple event handlers and control event propagation.
(1) Download and use the program.
Download the entire program from the official website or other sources, extract the files, and upload them to the appropriate file storage location on your server.
Add the following inside the `<head>` tag:
<script type="text/javascript" src="js/jquery-X.X.X.min.js"></script>
(2) Use a CDN (Content Delivery Network).
This method involves loading the jQuery program directly from another server instead of downloading it to your local computer.
Add the following inside the `<head>` tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/X.X.X/jquery.min.js"></script>
All functions start with `$`, usually called the dollar sign operator or bling.
$(function(){
$(targetElement/selector).method()
});document ready
Specify elements with `$('selector')` and perform operations with `.method()`.
| Method | Function | Code Example |
|---|---|---|
| prop(property, value) | Sets/gets the value of the specified property. Similar to css(), but manipulates HTML attributes, not CSS. |
|
| Method | Function | Code Example |
|---|---|---|
| html(content) | Sets/gets the HTML content of an element. | |
D3 stands for Data-Driven Documents.
It is a JavaScript library for data visualization.
It allows you to create complex graphs and interactive visualizations on web pages.
D3.js has its own set of DOM manipulation methods that wrap the standard DOM API, supporting almost all aspects of data visualization.
However, D3.js's DOM manipulation can be idiosyncratic, making it sometimes difficult to use by simply copying and pasting samples and making minor modifications.
- Data-driven: Manipulates the DOM (Document Object Model) based on data to create dynamic visualizations.
- Flexibility: Enables highly flexible visualizations by combining SVG, HTML, CSS, etc.
- Graph creation: Creates various types of graphs such as line graphs, bar charts, pie charts, and scatter plots.
- Map display: Creates maps using GeoJSON data and overlays data.
- Interactive visualization: Visualizations that change in response to user operations.
- Animation: Visually clear expressions achieved by animating graph elements.
Data visualization is performed by linking data, scales, and visual representations.
It is only displayed on the screen when placed within an SVG drawing area.
(1) Use a CDN
<head>
<!-- Importing D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js" integrity="sha512-M7nHCiNUOwFt6Us3r8alutZLm9qMt4s9951uo8jqO4UwJ1hziseL6O3ndFyigx6+LREfZqnhHxYjKRJ8ZQ69DQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
</html>
(2) Save locally and use
<html>
<head>
<!-- Importing D3.js -->
<script src="d3.v7.min.js"></script>
</head>
</html>
Prepare data in array or JSON format.
<body>
<script>
const data = [10, 20, 30, 40, 50];
</script>
</body>
SVG: An XML-based format for embedding images and graphics on web pages.
<script>
// prepare datas for creating graph
const data = [10, 20, 30, 40, 50];
// add below code
// create SVG element
const svg = d3.select("body") // Which element to create SVG for
.append("svg") // Create a SVG element for selected elements
.attr("width", 500) // Set the “width” attribute of the SVG created
.attr("height", 300); // Set the “height” attribute of the SVG created
</script>
Bind data to elements using the data() method.
<script>
// prepare datas for creating graph
const data = [10, 20, 30, 40, 50];
// create SVG element
const svg = d3.select("body") // Which element to create SVG for
.append("svg") // Create a SVG element for selected elements
.attr("width", 500) // Set the “width” attribute of the SVG created
.attr("height", 300); // Set the “height” attribute of the SVG created
Scatter Plot
// add below code
// Link datas and elements
svg.selectAll("circle") // Select elements to link datas
.data(data) // Link datas to selected elements
.enter() // Create actually elements
.append("circle") // Add elements to link datas
.attr("cx", (d, i) => i * 50 + 25) // Set an attribute
.attr("cy", 50) // (same as above)
.attr("r", (d) => d); // (same as above)
</script>
Bar Chart
// add below code
// Link datas and elements
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 25)
.attr("height", 100);
</script>
The steps to add X and Y axes with D3.js are:
1. Create scales: Create scales to map the data range to the graph's coordinate system.
2. Generate axes: Generate axes using d3.axisBottom() or d3.axisLeft() and set the scales.
3. Add axes: Append axes to the SVG and adjust their position and style.
// Create Scale
const xScale = d3.scaleLinear()
.domain([0, data.length - 1]) // an index of datas
.range([0, 500]); // a range of X-axis
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)]) // a maximum data
.range([300, 0]); // a range of Y-axis
// Create axis
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// Add axis to the SVG element
svg.append("g")
.attr("transform", "translate(0," + 300 + ")")
.call(xAxis);
svg.append("g")
.call(yAxis);
The steps to add X and Y axes with D3.js are:
1. Create scales: Create scales to map the data range to the graph's coordinate system.
2. Generate axes: Generate axes using d3.axisBottom() or d3.axisLeft() and set the scales.
3. Add axes: Append axes to the SVG and adjust their position and style.
// Create Scale
const xScale = d3.scaleLinear()
.domain([0, data.length - 1]) // an index of datas
.range([0, 500]); // a range of X-axis
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)]) // a maximum data
.range([300, 0]); // a range of Y-axis
// Create axis
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// Add axis to the SVG element
svg.append("g")
.attr("transform", "translate(0," + 300 + ")")
.call(xAxis);
svg.append("g")
.call(yAxis);
You can add a title to the top of the graph using the SVG text element.
// Add title to SVG
svg.append("text")
.attr("x", width / 2)
.attr("y", 20)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.text("Graph's Title");
You can add a legend using the SVG g element.
// Create legend group
var legend = svg.selectAll(".legend")
.data(data)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
// Add rectangle in legend
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d) { return color(d.key); });
// Add label in legend
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.key; });
// Add data labels
svg.selectAll(".do\t")
.data(data)
.enter().append("text")
.attr("class", "label")
.attr("x", function(d) { return xScale(d.x); })
.attr("y", function(d) { return yScale(d.y); })
.attr("dy", "-.35em")
.text(function(d) { return d.y; });
Provided by the library, these are not original built-in JavaScript methods.
| Method | Function | Example Code |
|---|---|---|
| select("target element") | Selects the first matching element from the document. | |
| selectAll("target element") | Gets all matching elements from the document as an array. | |
| append("adding element") | Adds one element to the document. | |
| text("adding text in target element") | Adds text to the selected element. | |
| data(dataset) | Binds DOM elements (selected elements) with a data array. | |
| enter() | Creates a selection for adding missing elements. | |
| style("property", "value") | Specifies the style of the selected element. | |
| attr("property", "value") | Adds an inline style. | |
| scaleLinear() | Generates a linear scale (axis). | |
| domain() | Specifies the minimum and maximum values of the data. | |
| range() | Specifies the output range for visual representation. | |
| axisBottom()/axisLeft() | Creates an axis at the bottom/left of the graph. | |
| call() | Calls the generated axis generation function, and draws the axis on the SVG element. |
|
Add suffix to text
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("h2")
.data(dataset)
.enter()
.append("h2")
.text(function(d) {
return d + " USD";
});
</script>
One of JavaScript's libraries, a tool for easily manipulating dynamic elements on web pages.
It allows for concise JavaScript code and can significantly increase development efficiency.
It abstracts away browser differences, making cross-browser development easier.
In recent years, with the emergence of React and similar frameworks, the use of jQuery has been declining.
- `$` function
Selects DOM elements based on a selector and generates a jQuery object.
`$('selector')`
The selector can use notation similar to CSS selectors. - jQuery object methods often return the jQuery object itself.
This allows multiple methods to be chained, leading to concise code.
(= Method Chaining) - By calling various jQuery methods on the jQuery object generated by the `$` function,
you can perform DOM manipulation, event handling, and more. - Methods are provided to concisely write event handling.
`$('selector').on('eventName', function);`
By using the `on()` method,
you can register multiple event handlers and control event propagation.
(1) Download and use the program.
Download the entire program from the official website or other sources, extract the files, and upload them to the appropriate file storage location on your server.
Add the following inside the `<head>` tag:
<script type="text/javascript" src="js/jquery-X.X.X.min.js"></script>
(2) Use a CDN (Content Delivery Network).
This method involves loading the jQuery program directly from another server instead of downloading it to your local computer.
Add the following inside the `<head>` tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/X.X.X/jquery.min.js"></script>
All functions start with `$`, usually called the dollar sign operator or bling.
$(function(){
$(targetElement/selector).method()
});document ready
Specify elements with `$('selector')` and perform operations with `.method()`.
| Method | Function | Code Example |
|---|---|---|
| prop(property, value) | Sets/gets the value of the specified property. Similar to css(), but manipulates HTML attributes, not CSS. |
|
| Method | Function | Code Example |
|---|---|---|
| html(content) | Sets/gets the HTML content of an element. | |
| Method | Function | Code Example |
|---|---|---|
| addClass(class) | Adds the specified class to the element. | |
| removeClass(class) | Removes the specified class from the element. | |
| css(property, value) | Sets/gets the value of the specified property. | |
| Method | Function | Code Example |
|---|---|---|
| remove() | Removes the element and its child elements from the DOM. | |
| appendTo(selector) | Appends the element as a child of the element specified by the selector. | |
| clone() | Creates a clone (copy) of the specified element. Can duplicate the structure and content of the original element as a new element. |
|
| parent() | Gets the parent element of the element. | |
| children() | Gets the child elements of the element. | |
| ready() | Specifies a function to execute after the DOM has finished loading. | |
:nth-child(num): One of CSS pseudo-classes, used to select a specific child element within a parent element.
// Selects the 2nd element with the class 'target' and adds 'animated' and 'bounce' classes
$(".target:nth-child(2)").addClass("animated bounce");
:even: One of CSS pseudo-classes, used to apply styles to even-numbered child elements within a parent element.
// Selects even-numbered elements with the class 'target' and adds 'animated' and 'shake' classes
$(".target:even").addClass("animated shake");
A JavaScript library for building user interfaces.
An open-source view library created and maintained by Facebook.
An excellent tool for rendering user interfaces (UI) of modern web applications.
Frequently used and popular for building reusable component-driven user interfaces for web pages and applications.
Major companies like Facebook, Instagram, and Netflix use React.
Achieves fast rendering by using a virtual DOM.
Suitable for large-scale web application development.
Basic Processing Flow
ajax documentation
- Component
A part of a web page UI (one unit of screen elements).
You can display only one component on an entire web page, or combine it with other components.
(e.g., header, footer, button) encapsulated as independent units for reusability. - Composition
Creating a larger component by combining multiple components. - Virtual DOM (Document Object Model)
One of React's biggest features; the virtual DOM is a lightweight copy of the actual DOM.
Significantly improves application performance by efficiently updating only the necessary parts, instead of updating the entire UI with every change. - Rendering
Reflecting the UI expressed in Virtual DOM into the actual browser's DOM.
Rendering requires calling the ReactDOM API.
When rendered, the component's state changes. - JSX
A JavaScript syntax extension generally recommended for use when utilizing the React library.
React's own markup language that allows writing HTML directly within JavaScript.
Helps keep code readable and easily manage the overall data flow of the application. - Bind
In programming, it means associating a specific value (usually 'this') with a specific context (execution environment) of a function or object.
When using 'this' inside an event handler, you need to bind class component methods.
Basically, HTML and JSX are similar, but there are some important differences.
const JSX = <h1>Hello JSX!</h1>;
If you want to return multiple elements, you must wrap them in a `
const JSX = { // valid JSX
<div>
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</div>
}
const JSX = { // invalid JSX
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
}
<div class="myDiv"> // HTML
<div className="myDiv"> // JSX
Void elements:
Elements that do not require a closing tag, such as `
` or `
`.
In JSX, void elements must have a self-closing tag, and all elements must be closed.
// HTML
<p>paragraph-1<br>
paragraph-2</p>
<hr>
// JSX
<p>paragraph-1<br />
paragraph-2</p>
<hr />
{/* the comment text */}
Since JSX is not valid JavaScript, JSX code is compiled into JavaScript before execution.
At this time, a tool called Babel, which is a transpiler, is generally used.
If you write syntactically invalid JSX, compilation will fail.
It is highly likely that a simple problem related to React's rendering process is hidden at the root of what appears to be a complex issue.
Variable and object declarations are the same as in regular JavaScript, but when using their values, enclose the variable/object name in `{ }`.
function MyComponent() {
const myObject = {'this is treated as JavaScript code'};
return (
{/* To display the content of an object */}
<p>{JSON.stringify(myObject)}</p>
{/* To pass an object's value as a prop */}
<OtherComponent data={myObject} />
);
}
In addition to referencing stylesheets the same way as HTML, styles can also be applied using React's inline styles specified within the element.
<div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div>
または
const style = {color: "yellow", fontSize: 16};
<div style={style}>Mellow Yellow</div>
To improve readability, instead of writing long HTML tags directly in the return statement, components are managed by splitting them into multiple files.
The extension can be either .jsx or .js, but it's better to use .jsx for component files.
// index.js
// Import the componentized App.js in index.js
index.js: Imports and uses the componentized App.js.
App.js: Componentizes the screen rendering part (HTML tags within return).
import React from "react";
import ReactDOM from "react-dom"; // Corrected from ReacrDom
import App from './App'; // Assuming App.js is in the same directory
ReactDOM.render(, document.getElementById("root"));
// App.jsx
import React from "react";
const App = () => {
return (
<>
<h1>Hello,</h1>
<p>How are you?</p>
</>
);
};
// Allows use in other files
export default App;
React components must be named using UpperCamelCase (= PascalCase).
(= A variable naming convention where the first letter is capitalized and word boundaries are also capitalized).
Examples: 〇 App, MyComponent, etc.
✕ app, myComponent, etc.
There are two ways to create components: defining them as JavaScript functions or as classes.
props: Similar to arguments passed to a component.
Not only variables, but also arrays can be passed (when dealing with data, use JavaScript's join() etc.).
state: The state held by each component; when the state changes, it is re-rendered.
1. Define with JavaScript functions.
Function components receive props and return JSX (≈HTML) or null, which are React elements.
const DemoComponent = function(props) {
return (
<div className='customClass' />
// Can also return by connecting with && within { }
{this.props.name && <h1>Displayed!</h1>}
);
};
2. Use ES6 Class Syntax.
// Creating MyComponentName that extends React.Component
class MyComponentName extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>Hi</h1>
);
}
}
What can be specified:
・Default values to be used if props are not passed.
・Data types.
const MyComponent = (props) => {
return (
<div>
<h1>Shopping quantity: {props.quantity}</h1>
</div>
)
};
// Set default Props
MyComponent.defaultProps = { quantity: 0 }
// Set propTypes
MyComponent.propTypes = { quantity: PropTypes.number.isRequired }
When combining multiple components into one to display as an application, return the child components you want to combine within the parent component's return value.
// child Component
const ChildComponent1 = () => { /* logic */ }
const ChildComponent2 = () => { /* logic */ }
const ParentComponent = () => {
// logic
return (
<App>
<ChildComponent1 />
<ChildComponent2 />
</App>
)
}
When including multiple parent components, since there are multiple props, you need to explicitly state the current component's props with "this.props".
In such cases, use JavaScript's bind() method to fix the target that 'this' refers to.
// To correctly set the scope of 'this', bind the handleChange method to the class's context.
this.handleClick = this.handleClick.bind(this)
handleChange(): A function called when the value of a form element changes, reflecting the changed value in the state.
Use the ReactDOM.render() function to reflect the virtual DOM into the browser's DOM (HTML DOM).
Following the flow of React processing described in JSX, describe the ReactDOM.render() function after writing JSX.
// Reflects the "React element" of the virtual DOM into the browser's DOM (HTML DOM).
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
// Reflects the "component" of the virtual DOM into the browser's DOM (HTML DOM).
// Creating the Greeting component
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
}
// Reflects the Greeting component into the browser's DOM (HTML DOM).
const root = ReactDOM.createRoot(document.getElementById('root'));
// Passes name = "Alice" to the Greeting component's props.
root.render();
React has its own event handlers based on JavaScript.
| Event Handler | Timing |
|---|---|
| onClick() | When the user clicks an element. |
| keydown() | An event that occurs when a keyboard key is pressed. Used to detect user keyboard operations on a web page and perform corresponding processing. |
A component that does not hold state (i.e., there is no part that manages state using this.state in class components or useState hook in function components).
While complex logic cannot be implemented, performance is improved due to simpler processing.
React expects you not to directly modify the state; therefore, always use `this.setState()` to change the state.
React may batch multiple state updates to improve performance (meaning state updates via the setState method might be asynchronous).
The setState method has an alternative syntax that avoids this problem, but it's rarely needed.
Details
// Updates the state of a class-based component.
this.setState({
username: 'Lewis'
});
// Renders a React component on the server-side and converts it to an HTML string.
ReactDOMServer.renderToString();
Several special methods that provide an opportunity to execute actions at specific points in the component's lifecycle.
Functions that are automatically called at specific timings during a component's journey from creation to destruction.
Scheduled for deprecation after Ver. 17.
By default, when a component receives new props, it will re-render even if the props haven't changed.
This method allows you to compare props and return a boolean value to tell React whether to perform re-rendering and update the component.
| Lifecycle methods | Timing |
|---|---|
| componentWillMount() | Immediately before the component is first rendered |
| componentDidMount() | After the component is mounted to the DOM After the component's initial rendering is complete and DOM manipulation is possible |
| shouldComponentUpdate(nextProps, nextState) | When props or state change, specifically declares whether the component should update before the render method is called. |
| componentWillMount() | After props or state have changed, before the render method is called |
| componentWillUnmount() | Immediately before the component is destroyed |
| componentDidUpdate() | A function called immediately after the component has been updated |
A framework (library) for managing the State of JavaScript applications.
= A state management library for JavaScript applications.
Redux was developed by the creators of React to make it easier to share data between different components.
It is often used in combination with React, but can also be used with other languages or frameworks.
While JavaScript itself is a programming language, Redux is more like a toolkit specialized for a specific purpose.
Redux aims to gather and manage state in one place, making application state predictable and reducing bugs.
Generally, as applications become more complex, managing state becomes difficult. Redux makes it easier to track and debug state by centralizing state management.
★By centralizing state management with Redux, it facilitates state tracking and debugging.★
In Redux, state is read-only, so you always receive a new copy of the state from the store to modify each state.
= You must never directly modify the state.
※Redux does not enforce state immutability, so you can modify it if you try.
- Store: An object, the single source of truth for the application's state.
Even if an application holds multiple states, they are managed within a single object in the Store.
It can store arbitrary data and can hold various types of data, such as strings, numbers, arrays, objects, and functions.
= Any state update must go through the Store. - Action: A JavaScript object containing information about an Action event that occurred.
All state updates in Redux are triggered by dispatching Actions.
It must always have a `type` property, and it commonly includes a `payload` with additional information indicating how you want to change the state. - Pure Function
A function that does not call API endpoints or have any other hidden side effects. - Reducer: A pure function that returns a new state.
It is solely responsible for state changes that occur in response to an action.
It takes `state` and `action` as arguments and returns a new `state`.
Reference: Free Code Camp (Terms and Concepts)How to Use Redux and Redux Toolkit – Tutorial for Beginners
What is Redux? Store, Actions, and Reducers Explained for Beginners
Processing Flow
GeeksforGeeksmdn web docs
ProEngineer
W3CSchool