Javascript

Prettier ашиглаж кодоо форматлана. Энэ нь кодыг нэг форматанд оруулахаас гадна, бидний үндсэн философи болох (Consistency is key) зарчмыг мөрдүүлэхэд тусладаг.

indent_size = 2
{
    "printWidth": 80,
}

Javascript орчинд 'single quote' ашиглах. Учир нь PHP буюу Backend талдаа мөн адил ('single quote') хэрэглэнэ (Consistency is key).

{
    "singleQuote": true
}

Файлын нэр

Файлын нэр жижиг үсгээр (lowercase) нэрлэх, мөн дундуур зураас (-) ашиглах.

order/list-orders.tsx
order/listOrders.tsx

Хувьсагчийн нэр

Товчилсон нэр ашиглахгүй байх.

// Clear and explicit variable names make the function easier to understand
function calculateTotal(product, quantity) {
    return product.price * quantity;
}
// It's unclear what "prd" and "q" stand for without additional context
function calculateTotal(prd, q) {
    return prd.price * q;
}

Хувьсагчид утга оноох

Хувьсагч зарлахдаа болж өгвөл "const" ашигла. Тухайн хувьсагчид утга дахин оноох тохиолдолд зөвхөн "let" ашиглах. Never use "var".

const phone = { name: 'iPhone' };
phone.name = 'Android';
let phone = { name: 'iPhone' };
phone.name = 'Android';

Утга харьцуулах

Хувьсагчийн утга шалгахдаа үргэлж "===" ашиглах. Хэрвээ төрөл нь тодорхойгүй байвал, "cast" хий.

const a = 1;
const b = "1"

if (a === parseInt(b)) {
    // ...
}
const a = 1;
const b = "1"

if (a == b) {
    // ...
}

Функц зарлах

Функц зарлахдаа "function" keyword ашиглах.

function greet() {
  // ...
}
const greet = function() {
  // ...
}

Гэхдээ, функц нь "single line" бол "arrow" синтакс ашиглаж болно. Тогтсон хатуу дүрэм дагах хэрэггүй.


function sum(a, b) { return a + b; } // short and simple method, it is ok. const sum = (a, b) => a + b;
export function query(selector) {
    return document.querySelector(selector);
}
// This function is a bit longer, and the single-line feels a bit heavy.
// Unlike the previous example, it's not easily scannable.
export const query = (selector) => document.querySelector(selector);

Destruct Object and Array

const person = { name: 'Чингис', age: 30, country: 'Mongolia' };
const { name, age, country } = person;
const [hours, minutes] = '13:00'.split(':');
const time = '13:00'.split(':');
const hours = time[0];
const minutes = time[1];