let, constJavaScript เพิ่มพฤติกรรมและตรรกะให้เว็บเพจ เช่น การคำนวณ การตอบสนองต่อปุ่ม การแสดงผลตามเงื่อนไข และการจัดการข้อมูลฝั่งผู้ใช้ การเริ่มต้นที่ดีควรเข้าใจ data type, function และ control flow ก่อนเชื่อมกับ DOM
JavaScript เป็นภาษาที่ทำให้เว็บเพจมีพฤติกรรมและตอบสนองต่อผู้ใช้ได้ เบราว์เซอร์มี JavaScript Engine สำหรับอ่านและรันโค้ด เช่น V8 ใน Chrome หรือ SpiderMonkey ใน Firefox
HTML ใช้สร้างโครงสร้าง CSS ใช้กำหนดหน้าตา ส่วน JavaScript ใช้เพิ่ม logic เช่น คำนวณราคา ตรวจเงื่อนไข แสดงข้อความ เปลี่ยน class และตอบสนองต่อ event ของผู้ใช้
flowchart LR
HTML[HTML Structure] --> CSS[CSS Presentation]
CSS --> JS[JavaScript Behavior]
JS --> UX[User Interaction]
วิธีเชื่อม JavaScript กับ HTML ที่นิยมคือใช้ไฟล์ภายนอกและใส่ defer เพื่อให้ browser โหลด script โดยไม่ขัดจังหวะการอ่าน HTML
<script src="js/main.js" defer></script>
ตัวอย่าง JavaScript เบื้องต้น:
console.log("Hello Front-end");
console.log() ใช้แสดงผลใน DevTools Console เหมาะสำหรับตรวจค่าระหว่างพัฒนา แต่ไม่ควรใช้แทนการแสดงผลจริงให้ผู้ใช้เห็น
let, constVariable หรือตัวแปรใช้เก็บข้อมูลเพื่อนำไปใช้ต่อในโปรแกรม JavaScript สมัยใหม่แนะนำให้ใช้ const เป็นค่าเริ่มต้น และใช้ let เมื่อรู้ว่าค่าจะเปลี่ยน
const courseName = "Front-end Development";
let score = 0;
score = 85;
ความแตกต่างหลัก:
| คำสั่ง | ใช้เมื่อ | เปลี่ยนค่าใหม่ได้หรือไม่ |
|---|---|---|
const |
ค่าที่ไม่ต้อง assign ใหม่ | ไม่ได้ |
let |
ค่าที่ต้องเปลี่ยนระหว่างทำงาน | ได้ |
ตัวอย่างการใช้ let กับ counter:
let count = 0;
count = count + 1;
count += 1;
count++;
ข้อควรจำ:
totalPrice, studentNameuserScoredata, x, thingvar ในงานใหม่ เพราะมีพฤติกรรม scope ที่ทำให้สับสนได้ง่ายกว่าData Type คือชนิดของข้อมูลที่ JavaScript ใช้ทำงาน การเข้าใจชนิดข้อมูลช่วยลด bug เช่น การเอาข้อความไปบวกกับตัวเลขโดยไม่ตั้งใจ
ชนิดข้อมูลพื้นฐานที่ใช้บ่อย:
| Type | ตัวอย่าง | ความหมาย |
|---|---|---|
| String | "HTML" |
ข้อความ |
| Number | 42, 3.14 |
ตัวเลข |
| Boolean | true, false |
ค่าจริง/เท็จ |
| Undefined | undefined |
ยังไม่มีค่า |
| Null | null |
ตั้งใจให้ไม่มีค่า |
| Array | ["HTML", "CSS"] |
รายการข้อมูล |
| Object | { name: "Ann" } |
ข้อมูลเป็นคู่ key/value |
ตัวอย่าง:
const title = "Portfolio";
const year = 2026;
const isPublished = true;
const tags = ["HTML", "CSS", "JavaScript"];
const student = {
name: "Suda",
major: "AI and Digital Innovation",
};
ตรวจชนิดข้อมูลด้วย typeof:
console.log(typeof title); // string
console.log(typeof year); // number
console.log(typeof isPublished); // boolean
ข้อควรระวังคือข้อมูลจาก form มักเป็น string แม้ผู้ใช้กรอกตัวเลข หากต้องคำนวณควรแปลงเป็น number ก่อน
const priceText = "120";
const price = Number(priceText);
Operator คือเครื่องหมายหรือคำสั่งที่ใช้คำนวณ เปรียบเทียบ หรือเชื่อมเงื่อนไข
const subtotal = 100 * 3;
const discount = subtotal * 0.1;
const total = subtotal - discount;
| Operator | ความหมาย |
|---|---|
+ |
บวก หรือเชื่อม string |
- |
ลบ |
* |
คูณ |
/ |
หาร |
% |
เศษจากการหาร |
const score = 75;
console.log(score >= 50); // true
console.log(score === 75); // true
console.log(score !== 0); // true
ควรใช้ === และ !== แทน == และ != เพื่อเปรียบเทียบแบบไม่แปลงชนิดข้อมูลอัตโนมัติ
const age = 20;
const hasTicket = true;
const canEnter = age >= 18 && hasTicket;
| Operator | ความหมาย |
|---|---|
&& |
และ |
| ` | |
! |
ไม่ |
ใช้ backtick เพื่อแทรกค่าตัวแปรในข้อความ
const name = "Suda";
const message = `Hello, ${name}`;
Condition ใช้ให้โปรแกรมเลือกทำงานตามเงื่อนไข เช่น ผ่าน/ไม่ผ่าน แสดง/ซ่อน หรือเลือกข้อความตามคะแนน
const score = 82;
if (score >= 80) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else if (score >= 50) {
console.log("Pass");
} else {
console.log("Retry");
}
เงื่อนไขควรเขียนให้อ่านง่ายและเรียงจากกรณีเฉพาะไปทั่วไป หากเงื่อนไขซับซ้อนควรแยกเป็นตัวแปรชื่อสื่อความหมาย
const email = "student@example.com";
const password = "12345678";
const isEmailValid = email.includes("@");
const isPasswordValid = password.length >= 8;
if (isEmailValid && isPasswordValid) {
console.log("Form is valid");
}
Ternary Operator ใช้กับเงื่อนไขสั้น ๆ ที่คืนค่า:
const status = score >= 50 ? "pass" : "retry";
แต่ถ้าเงื่อนไขหลายชั้น ควรใช้ if/else เพื่อให้อ่านง่ายกว่า
Loop ใช้ทำงานซ้ำ เช่น แสดงรายการสินค้า คำนวณคะแนนหลายคน หรือค้นหาข้อมูลใน array
for loopเหมาะเมื่อรู้จำนวนรอบหรือใช้ index
for (let i = 1; i <= 5; i++) {
console.log(`รอบที่ ${i}`);
}
for...ofเหมาะกับการวนอ่านค่าจาก array
const skills = ["HTML", "CSS", "JavaScript"];
for (const skill of skills) {
console.log(skill);
}
forEachเป็น method ของ array ใช้ทำงานกับแต่ละ item
skills.forEach((skill) => {
console.log(`กำลังเรียน ${skill}`);
});
ตัวอย่างคำนวณผลรวม:
const scores = [80, 75, 90];
let total = 0;
for (const score of scores) {
total += score;
}
const average = total / scores.length;
console.log(average);
ข้อควรระวังคือ loop ต้องมีเงื่อนไขสิ้นสุด ไม่เช่นนั้นจะเกิด infinite loop ทำให้ browser ค้างได้
Function คือการรวมชุดคำสั่งที่ทำงานอย่างใดอย่างหนึ่งไว้ในชื่อเดียว ช่วยให้โค้ดใช้ซ้ำได้ อ่านง่าย และทดสอบง่ายขึ้น
function calculateTotal(price, quantity) {
return price * quantity;
}
const total = calculateTotal(120, 3);
console.log(total);
ส่วนประกอบของ function:
calculateTotalprice, quantityreturn สำหรับส่งค่ากลับArrow Function เป็นรูปแบบย่อที่ใช้บ่อยใน JavaScript สมัยใหม่
const calculateTotal = (price, quantity) => {
return price * quantity;
};
ถ้ามีคำสั่งเดียวและต้องการ return ทันที สามารถเขียนสั้นลงได้
const calculateTotal = (price, quantity) => price * quantity;
ตัวอย่าง function สำหรับตรวจคะแนน:
const gradeOf = (score) => {
if (score >= 80) return "A";
if (score >= 70) return "B";
if (score >= 50) return "Pass";
return "Retry";
};
แนวทางตั้งชื่อ function ควรใช้คำกริยา เช่น calculateTotal, renderProfile, validateEmail, getAverageScore
Array ใช้เก็บรายการข้อมูลที่มีลำดับ เช่น รายชื่อวิชา รายการสินค้า หรือคะแนนหลายค่า
const skills = ["HTML", "CSS", "JavaScript"];
console.log(skills[0]); // HTML
console.log(skills.length); // 3
skills.push("Angular");
Method ที่ใช้บ่อย:
| Method | หน้าที่ |
|---|---|
push |
เพิ่ม item ท้าย array |
pop |
ลบ item ท้าย array |
map |
แปลงข้อมูลเป็น array ใหม่ |
filter |
กรองข้อมูล |
find |
ค้นหา item แรกที่ตรงเงื่อนไข |
Object ใช้เก็บข้อมูลเป็นคู่ key/value เหมาะกับข้อมูลหนึ่งรายการที่มีหลายคุณสมบัติ
const student = {
id: "651234",
name: "Suda",
score: 82,
isActive: true,
};
console.log(student.name);
console.log(student["score"]);
Array ของ Object เป็นรูปแบบที่พบมากในงาน Front-end โดยเฉพาะข้อมูลจาก API
const courses = [
{ code: "04-511-208", title: "Front-end Development" },
{ code: "04-522-306", title: "Web Application Development" },
];
for (const course of courses) {
console.log(`${course.code}: ${course.title}`);
}
ตัวอย่างใช้ map เพื่อแปลงข้อมูล:
const courseTitles = courses.map((course) => course.title);
console.log(courseTitles);
const เป็นค่าเริ่มต้น และใช้ let เมื่อค่าต้องเปลี่ยน=== และ !== สำหรับการเปรียบเทียบconsole.log() ระหว่างพัฒนา แล้วลบส่วนที่ไม่จำเป็นก่อนส่งงานconst score = 82;
function gradeOf(value) {
if (value >= 80) return "A";
if (value >= 70) return "B";
return "C";
}
console.log(gradeOf(score));
ทำแบบฝึกคำนวณคะแนน ตรวจเงื่อนไข และแสดงผลลัพธ์จากข้อมูลใน array
เขียน function สำหรับคำนวณค่าใช้จ่ายหรือคะแนนจากโจทย์ใกล้ตัว
let และ const ต่างกันอย่างไร