Variables

#HelloFrontend #HelloErmine #HelloWorld2021

Variable คืออะไร ?

คือ ตัวแปรที่สามารถเก็บค่าไว้เพื่อใช้ในภายหลังได้ โดยตัวแปรใน JavaScript สามารถเก็บค่าได้ทุกประเภท

การตั้งชื่อตัวแปร

ชื่อตัวแปรเป็นแบบ case-sensitive และต้องขึ้นต้นด้วย a-z, A-Z, _ หรือ $ เท่านั้น ตัวที่เหลือสามารถใส่เป็น 0-9 ได้

let _type;
let $type;
let num0;
let 0piece; // SyntaxError: Invalid or unexpected token
let typeof; // SyntaxError: Unexpected token 'typeof'

การประกาศตัวแปร

นิยมใช้อยู่ 2 วิธี โดยจะมี scope อยู่ใน block ที่มันถูกประกาศเท่านั้น คือ

block คือ statement ที่คลุม statement อื่น ๆ ด้วย { }

  1. let จะประกาศตัวแปรที่เปลี่ยนแปลงค่าได้

    let x  = 10;
     
    {
      let x = 5;
      console.log(x); // 5
    }
     
    console.log(x); // 10
    x = 100;
    console.log(x); // 100
  2. const จะประกาศตัวแปรที่เก็บค่าคงที่ที่เปลี่ยนแแปลงค่าไม่ได้

    const y  = 10;
     
    {
      const y = 5;
      console.log(y); // 5
    }
     
    console.log(y); // 10
    y = 100; // TypeError: Assignment to constant variable
    console.log(y);

แหล่งอ้างอิง 📑

Last updated

Was this helpful?