JavaScript Cheat Sheet - สรุปคำสั่ง JavaScript
ตัวแปร (Variables)
// const - ค่าคงที่ (แนะนำ)
const PI = 3.14159;
const name = "Alice";
// let - ตัวแปรที่เปลี่ยนค่าได้
let age = 25;
age = 26;
// var - เก่า ไม่แนะนำ
var oldStyle = "avoid";ชนิดข้อมูล (Data Types)
// String
const text = "Hello";
const text2 = 'World';
const text3 = `Template ${text}`;
// Number
const integer = 42;
const float = 3.14;
const negative = -10;
// Boolean
const isTrue = true;
const isFalse = false;
// Array
const fruits = ["apple", "banana", "orange"];
const mixed = [1, "two", true, null];
// Object
const person = {
name: "Alice",
age: 25,
isStudent: true
};
// Null & Undefined
const empty = null;
let notDefined;
// typeof
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"Operators (ตัวดำเนินการ)
// Arithmetic
let sum = 5 + 3; // 8
let diff = 5 - 3; // 2
let product = 5 * 3; // 15
let quotient = 5 / 3; // 1.666...
let remainder = 5 % 3; // 2
let power = 5 ** 3; // 125
// Assignment
let x = 10;
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2; // x = x * 2
x /= 4; // x = x / 4
x++; // x = x + 1
x--; // x = x - 1
// Comparison
5 == "5" // true (เท่ากัน)
5 === "5" // false (เท่ากันและชนิดเดียวกัน)
5 != "5" // false
5 !== "5" // true
5 > 3 // true
5 < 3 // false
5 >= 5 // true
5 <= 3 // false
// Logical
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)
// Ternary
const result = age >= 18 ? "Adult" : "Minor";String Methods
const str = "Hello World";
str.length // 11
str.toUpperCase() // "HELLO WORLD"
str.toLowerCase() // "hello world"
str.trim() // ตัดช่องว่างหน้า-หลัง
str.includes("World") // true
str.startsWith("Hello") // true
str.endsWith("World") // true
str.indexOf("World") // 6
str.slice(0, 5) // "Hello"
str.substring(0, 5) // "Hello"
str.replace("World", "JS") // "Hello JS"
str.split(" ") // ["Hello", "World"]
str.charAt(0) // "H"
str.repeat(3) // "Hello WorldHello WorldHello World"Array Methods
const arr = [1, 2, 3, 4, 5];
// Add/Remove
arr.push(6) // เพิ่มท้าย [1,2,3,4,5,6]
arr.pop() // ลบท้าย [1,2,3,4,5]
arr.unshift(0) // เพิ่มหน้า [0,1,2,3,4,5]
arr.shift() // ลบหน้า [1,2,3,4,5]
arr.splice(2, 1) // ลบตำแหน่งที่ 2 จำนวน 1 ตัว
// Search
arr.indexOf(3) // 2
arr.includes(3) // true
arr.find(x => x > 3) // 4
arr.findIndex(x => x > 3) // 3
// Transform
arr.map(x => x * 2) // [2,4,6,8,10]
arr.filter(x => x > 2) // [3,4,5]
arr.reduce((sum, x) => sum + x, 0) // 15
arr.sort() // เรียงลำดับ
arr.reverse() // กลับลำดับ
arr.slice(1, 3) // [2,3]
arr.concat([6, 7]) // [1,2,3,4,5,6,7]
arr.join(", ") // "1, 2, 3, 4, 5"
// Check
arr.every(x => x > 0) // true (ทุกตัวเป็นจริง)
arr.some(x => x > 4) // true (บางตัวเป็นจริง)Object Methods
const obj = { name: "Alice", age: 25, city: "Bangkok" };
Object.keys(obj) // ["name", "age", "city"]
Object.values(obj) // ["Alice", 25, "Bangkok"]
Object.entries(obj) // [["name","Alice"], ["age",25], ["city","Bangkok"]]
Object.assign({}, obj) // คัดลอก object
// Destructuring
const { name, age } = obj;
console.log(name); // "Alice"
// Spread
const newObj = { ...obj, country: "Thailand" };Control Flow
// If-Else
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}
// Switch
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek");
}
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For...of (Array)
for (const fruit of fruits) {
console.log(fruit);
}
// For...in (Object)
for (const key in obj) {
console.log(key, obj[key]);
}
// While
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Do-While
do {
console.log(i);
i++;
} while (i < 5);Functions
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
// Arrow Function
const greet = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const square = x => x * x;
// Default Parameters
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
// Rest Parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}DOM Manipulation
// Select Elements
document.getElementById("myId")
document.querySelector(".myClass")
document.querySelectorAll("p")
document.getElementsByClassName("myClass")
document.getElementsByTagName("p")
// Create & Modify
const div = document.createElement("div");
div.textContent = "Hello";
div.innerHTML = "<strong>Hello</strong>";
div.setAttribute("id", "myDiv");
div.classList.add("active");
div.classList.remove("inactive");
div.classList.toggle("visible");
div.style.color = "red";
// Add to DOM
parent.appendChild(div);
parent.insertBefore(div, referenceNode);
parent.removeChild(div);
div.remove();
// Get/Set Values
input.value
input.checked
select.selectedIndexEvents
// Add Event Listener
element.addEventListener("click", function(e) {
console.log("Clicked!");
e.preventDefault(); // ยกเลิกการทำงานปกติ
e.stopPropagation(); // หยุดการส่งต่อ event
});
// Common Events
"click"
"dblclick"
"mouseenter"
"mouseleave"
"mousemove"
"keydown"
"keyup"
"keypress"
"submit"
"change"
"input"
"focus"
"blur"
"load"
"DOMContentLoaded"
// Remove Event Listener
element.removeEventListener("click", handlerFunction);Async/Await & Promises
// Promise
const promise = new Promise((resolve, reject) => {
if (success) {
resolve("Success!");
} else {
reject("Error!");
}
});
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
// Async/Await
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
// Fetch API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));Common Patterns
// Debounce
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
// Throttle
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Deep Clone
const clone = JSON.parse(JSON.stringify(obj));
// Random Number
Math.random() // 0 ถึง 1
Math.floor(Math.random() * 10) // 0 ถึง 9
Math.floor(Math.random() * 100) + 1 // 1 ถึง 100LocalStorage
// Set
localStorage.setItem("key", "value");
localStorage.setItem("user", JSON.stringify(userObj));
// Get
const value = localStorage.getItem("key");
const user = JSON.parse(localStorage.getItem("user"));
// Remove
localStorage.removeItem("key");
// Clear All
localStorage.clear();Console Methods
console.log("Normal log");
console.error("Error message");
console.warn("Warning message");
console.info("Info message");
console.table([{name: "Alice", age: 25}]);
console.time("timer");
// ... code ...
console.timeEnd("timer");
console.clear();💡 Tips:
- ใช้
constเป็นค่าเริ่มต้น เปลี่ยนเป็นletเมื่อจำเป็น - ใช้ Arrow Functions สำหรับฟังก์ชันสั้นๆ
- ใช้ Template Literals แทน String Concatenation
- ใช้
===แทน==เสมอ - ใช้ Async/Await แทน Promise chains