Syntax และ Shorthand Techniquesในภาษา JavaScript

NottDev
4 min readOct 17, 2019

--

สำหรับภาษา JavaScript เชื่อว่าเป็นภาษาที่หลายคนคุ้นเคยกันมาอย่างช้านาน เนื่องจากเป็นภาษาที่ใช้สำหรับเพิ่มลูกเล่นให้กับเว็บไซต์ และบทความนี้จะมาแนะนำ Syntax และวิธีการเขียนโค้ดให้สั้นและกระชัด แบบจัดเต็ม มีอะไรบ้างนั้นไปดูกันเล๊ยยยย

?: (Ternary Operator)

รูปย่อของ if ที่น่าจะคุ้นเคยกันในหลายๆภาษา เช่น php , dart

  • รูปแบบคือ condition? true : false

การเขียนรูปแบบทั่วไป

bool isLogin = false;String message = "";if(isLogin) {
message = "Welcome";
} else {
message = "Please login";
}

การเขียนรูปแบบย่อ

bool isLogin = false;
String message = isLogin ? "Welcome" : "Please login";

|| (Short-circuit Evaluation)

เมื่อต้องการตรวจสอบค่าของตัวแปรว่าเป็น null, undefined, empty หรือไม่? ก่อนนำค่าไปใช้ การใช้ if นั้นอาจจะทำให้มีเงื่อนไขที่ยาว ซึ่งสามารถเขียนให้อยู่ในรูปย่อได้

  • รูปแบบคือ variable || default value

การเขียนรูปแบบทั่วไป

if (var1 !== null || var1 !== undefined || var1 !== '') {
let var2 = var1;
}

การเขียนรูปแบบย่อ

const var2 = var1  || 'default value';

=> (Arrow notation)

รูปย่อของ function/method ที่มีการทำงานบรรทัดเดียว

  • รูปแบบคือ functionName() => value;

การเขียนรูปแบบทั่วไป

function lowerCase(String str) {
return str.toLowerCase();
}

การเขียนรูปแบบย่อ

const lowerCase = str =>  str.toLowerCase();

+ (Converting a String into a Number)

สามารถแปลงจาก String format เป็น Numerical format

  • รูปแบบคือ +String

การเขียนรูปแบบทั่วไป

let age = parseInt('25');

การเขียนรูปแบบย่อ

let age = +'25';

` (Template Literals)

คุณไม่เบื่อการใช้ ‘ + ’ เพื่อเชื่อมหลายๆตัวแปรกับ String บ้างหรอ? มีวิธีที่ง่ายกว่านั้นมาก ถ้าคุณใช้ ES6 โดยแค่ใช้ backtick (`) และใช้ ${} ครอบตัวแปร

  • รูปแบบคือ `${variable} ..`

การเขียนรูปแบบทั่วไป

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

การเขียนรูปแบบย่อ

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

Declaring variables

สามารถประกาศตัวแปรแบบรวดเร็วและประหยัดพื้นที่ได้

  • รูปแบบคือ type variable1, variable2, …

การเขียนรูปแบบทั่วไป

let x;
let y;
let z = 3;

การเขียนรูปแบบย่อ

let x, y, z=3;

If Presence

นี่อาจจะดูเป็นเรื่องเล็กน้อย แต่ก็ควรค่าแก่การพูดถึง สำหรับการเช็ค if (true or false ) ที่สามารถละเว้นการเขียนรูปเต็มได้

  • รูปแบบคือ if(variable) and if(!variable)

การเขียนรูปแบบทั่วไป

if (likeJavaScript === true)
if (likeJavaScript !== true)

การเขียนรูปแบบย่อ

if (likeJavaScript)
if (!likeJavaScript)

Decimal Base Exponents

หากต้องทำงานกับค่าที่มีจำนวนเลขศูนย์มากๆ สามารถเขียนย่อๆได้

  • รูปแบบคือ 1e(zero number)

การเขียนรูปแบบทั่วไป

for (let i = 0; i < 10000; i++) {}

การเขียนรูปแบบย่อ

for (let i = 0; i < 1e7; i++) {}

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

Default Parameter Values

ปกติสามารถใช้ if เช็คและประกาศค่า default ของ param ของฟังก์ชัน แต่ใน ES6 สามารถกำหนดค่า default ตอนประกาศ param ของฟังก์ชันได้เลย

  • รูปแบบคือ function(param = default)

การเขียนรูปแบบทั่วไป

function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}

การเขียนรูปแบบย่อ

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24

JavaScript For Loop

การประกาศตัวแปร Object ถ้าชื่อตัวแปรเหมือนกับ object key สามารถเขียนในรูปย่อได้

  • รูปแบบคือ { x, y }

การเขียนรูปแบบทั่วไป

const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)

การเขียนรูปแบบย่อ

for (let fruit of fruits)

หากต้องการเข้าถึงแต่ละ index สามารถใช้ for in

for (let index in fruits)

… (Spread operator)

ฟีเจอร์ใน ES6 ที่มีความสามารถในการกระจายแต่ละ element ของ array

  • รูปแบบคือ …variable

การเขียนรูปแบบทั่วไป

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

การเขียนรูปแบบย่อ

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

ซึ่งจะแตกต่างจากฟังก์ชัน concat() เพราะสามารถใช้ spread operator ในการเพิ่ม array ในส่วนไหนก็ได้ใน array อื่น

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

และยังสามารถใช้ spread operator ใน ES6 ร่วมกับ destructuring notation ได้

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

Destructuring Assignment

การ unpack component ใน data object แล้วประกาศให้หลายตัวแปรพร้อมกันในครั้งเดียว

  • รูปแบบคือ functionName() => value;

การเขียนรูปแบบทั่วไป

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

การเขียนรูปแบบย่อ

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

และยังสามารถกำหนดชื่อตัวแปรเองได้

const { store, form, loading, errors, entity:customVariable } = this.props;

Multi-line String

สำหรับการเขียนขึ้นบรรทัดใหม่ลืม \n ไปได้เลย สามารถใช้ backtick character (`)

  • รูปแบบคือ ``

การเขียนรูปแบบทั่วไป

const profile = 'I am NottDev.\n\t'
+ 'I am 25 years old.\n\t'
+ 'My hobby is blogging.\n\t';

การเขียนรูปแบบย่อ

const profile = `I am NottDev.
I am 25 years old.
My hobby is blogging.`;

~~ (Double Bitwise NOT)

ใช้แทน Math.floor()

  • รูปแบบคือ ~~value

การเขียนรูปแบบทั่วไป

Math.floor(4.9) === 4  //true

การเขียนรูปแบบย่อ

~~4.9 === 4  //true

** (Exponent Power)

ใช้แทน Math exponent power function

  • รูปแบบคือ base**exponent

การเขียนรูปแบบทั่วไป

Math.pow(2,3); // 8
Math.pow(2,2); // 4
Math.pow(4,3); // 64

การเขียนรูปแบบย่อ

2**3 // 8
2**4 // 4
4**3 // 64

~ (Bitwise IndexOf)

เมื่อใช้งานกับ indexOf() ซึ่งผลลัพธ์จะ return -1 เมื่อไม่พบ หากพบก็ return เป็น index นั้นๆ ซึ่งการเช็คใน JavaScript นั้น 0 คือ false และ 1 คือ true ดังนั้นสามารถใช้ Bitwise ได้

  • รูปแบบคือ ~value

การเขียนรูปแบบทั่วไป

if(arr.indexOf(item) > -1) { // Confirm item IS found

}

if(arr.indexOf(item) === -1) { // Confirm item IS NOT found

}

การเขียนรูปแบบย่อ

if(~arr.indexOf(item)) { // Confirm item IS found

}

if(!~arr.indexOf(item)) { // Confirm item IS NOT found

}

Object Property

การประกาศตัวแปร Object ถ้าชื่อตัวแปรเหมือนกับ object key สามารถเขียนในรูปย่อได้

  • รูปแบบคือ { x, y }

การเขียนรูปแบบทั่วไป

const x = 1920, y = 1080;
const obj = { x:x, y:y };

การเขียนรูปแบบย่อ

const obj = { x, y };

Object.entries()

ฟีเจอร์ใหม่ใน ES8 ที่สามารถแปลง literal object เป็น key/value ใน array format

  • รูปแบบคือ Object.entries(variable)
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);

/** Output:
[ [ 'producer', 'John' ],
[ 'director', 'Jane' ],
[ 'assistant', 'Peter' ]
]
**/

Object.values()

ฟีเจอร์ใหม่ใน ES8 ที่เหมือนกับ Object.entries() แต่มีเฉพาะ value ไม่มี key

  • รูปแบบคือ Object.values(variable)
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);

/** Output:
[ 'John', 'Jane', 'Peter' ]
**/

Reference:

(ข้อมูลอาจมีข้อผิดพลาด ถ้าจะเอาบทความนี้ไปอ้างอิงที่อื่นให้ตรวจสอบให้ดีก่อนนะครับ ขอบคุณครับ)

สำหรับวันนี้ ต้องขอลาไปก่อน สวัสดีครับ NottDev :)

--

--

NottDev
NottDev

Written by NottDev

Your only limit is your mind.

No responses yet