ตัวแปร Const ใน Javascript ES6, Typescript

Narupon Tee Srisantitham
Konoe
Published in
1 min readJan 9, 2017

Const

Const คือตัวแปรใหม่ที่เพิ่มเข้ามาใน ES6 / TypeScipt ทำให้เราสามารถสร้างตัวแปรคงที่ได้ มันทำให้ code ของเราดูสวยงามและก็อ่านง่ายมากขึ้น วิธีใช้ก็แค่ใส่ const แทน var ตามตัวอย่าง

const foo = 123;

const ทำให้ code อ่านงานและทำให้การบำรุงรักษาโปรแกรมทำได้ง่ายขึ้น

// ใช้เป็นค่าทำให้อ่านยากif (x > 10) {}// เปลี่ยนเป็น const ทำให้อ่านได้ง่ายขึ้นconst maxRows = 10;if (x > maxRows) {}

Const ต้องมีค่าเสมอ

const foo; // ERROR: const declarations must be initialized

เปลี่ยนค่าไม่ได้

const foo = 123;foo = 456; // ERROR: Left-hand side of an assignment expression cannot be a constant

Block Scoped

Const ทำงานภายใน block (สามารถดูการทำงานของ block ได้ที่บทความ let)

const foo = 123;
if (true) {
const foo = 456;
// สร้างตัวแปรขึ้นมาใหม่ อยู่ใน block ของ if
}

ความลึกของค่าคงที่

Const ทำงานเป็น object

const foo = { bar: 123 };foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant

แต่เราสามารถแก้ไข้ค่าภายใน object ได้

const foo = { bar: 123 };foo.bar = 456; // ทำได้!console.log(foo); // { bar: 456 }

สรุป

การใช้งาน const มีไว้สำหรับค่าคงที่ต่าง ๆ ในโปรแกรมรวมถึง object ที่เราไม่ต้องการให้มีการเปลี่ยนแปลงค่าด้วย ทำให้ code อ่านได้ง่ายและแก้ไขได้ง่ายขึ้น

บทความอ้างอิง : https://basarat.gitbooks.io/typescript/content/docs/const.html

--

--