Types

#HelloFrontend #HelloErmine #HelloWorld2021

Type คืออะไร ?

คือ ประเภทของค่าที่เราสามารถใช้ได้ ที่พบเห็นได้บ่อยจะมีอยู่ 8 ชนิด คือ number, boolean, undefined, null, object, array, string และ function

number

เป็นค่าตัวเลข เก็บได้ทั้งจำนวนเต็มและทศนิยม

let num1 = 3000;
let num2 = 11.50;
console.log(typeof num1); // number
console.log(typeof num2); // number

typeofเป็นตัวที่บอกว่าตัวแปรเป็นค่าประเภทใด

boolean

เป็นค่าความจริง มีสอง keyword คือ true และ false

console.log(typeof true);  // boolean
console.log(typeof false); // boolean

undefined

เป็นค่าที่บอกว่าตัวแปรยังไม่ถูกกำหนดค่าให้

let huh;
console.log(huh); // undefined

ตัวแปรทุกตัวที่เราประกาศจะมีค่าเริ่มต้นเป็น undefined

null

เป็นค่าที่แสดงถึงความว่างเปล่า

ต่างกับ undefined อย่างไร ?

  • undefined อาจจะมีค่าแต่ยังไม่กำหนด

  • null ไม่มีค่าอะไรเลย

let nully = null;
console.log(nully); // null

object

เป็นตัวที่สามารถเก็บค่าแบบ key-value pair ได้ คือ เราใช้ key (หรืออีกชื่อคือ property) เพื่อเข้าถึง value ที่เกี่ยวข้องกับ key นั้น ๆ

let aCat = {
    color: "black",
    age: 5,
    isSleeping: true
};
console.log(aCat);        // {color: "black", age: 5, isSleeping: true}
console.log(aCat.color);  // black (dot notation)
console.log(aCat["age"]); // 5     (bracket notation)
console.log(typeof aCat); // object

จากตัวอย่าง aCat คือ object ที่มี key เป็น color, age และ isSleeping ส่วน value จะอยู่หลัง colon (:) และแต่ละ key-value pair จะคั่นด้วย comma (,)

การเข้าถึงค่าใน object

สามารถทำได้ 2 แบบ คือ

  1. dot notation (obj.key)

  2. bracket notation (obj["key"])

array

เป็นค่าที่สามารถเก็บค่าอื่น ๆ ในตัวมันเองได้ สามารถเข้าถึงค่าข้างในผ่าน bracket notation ด้วย index หรือตำแหน่งใน array (เริ่มต้นจาก 0) เช่น arr[0]

let arr = [27, "Huh", true];
let sussy = {
  0: 27,
  1: "Huh",
  2: true
};
console.log(arr[1]);             // Huh
console.log(sussy[1]);           // Huh
console.log(typeof arr);         // object
console.log(typeof sussy);       // object
console.log(Array.isArray(arr)); // true

string

เป็นค่าข้อมูลตัวอักษรหรือข้อความ จะล้อมรอบด้วย double quote (“) หรือ single quote (‘) ก็ได้

let str1 = "School was Pog today xqcL";
let str2 = 'No';
console.log(typeof str1); // string
console.log(typeof str2); // string

function

อ่านเพิ่มเติมที่ Functions

function  myFunc() {
    console.log("This is a function");
}
console.log(typeof myFunc); // function

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

Last updated

Was this helpful?