Variables
សេចក្តីផ្តើម
Variables គឺជា containers សម្រាប់រក្សាទុកទិន្នន័យ។ ក្នុង JavaScript មាន 3 វិធីប្រកាស variables: var, let, និង const។
Variable Declaration
Keyword | Scope | Reassign | Hoisting |
---|---|---|---|
var | Function | Yes | Yes |
let | Block | Yes | No |
const | Block | No | No |
var Keyword
var name = "John";
var age = 25;
var isStudent = true;
វិធីចាស់សម្រាប់ប្រកាស variable (មិនសូវប្រើ)
let Keyword
let name = "John";
let age = 25;
age = 26; // Can reassign
ប្រើសម្រាប់ variables ដែលតម្លៃអាចផ្លាស់ប្តូរ
const Keyword
const PI = 3.14;
const name = "John";
// PI = 3.15; // Error! Cannot reassign
ប្រើសម្រាប់ values ដែលមិនផ្លាស់ប្តូរ
Variable Scope
let global = "global";
function test() {
let local = "local"; // Only in function
}
if (true) {
let block = "block"; // Only in block
}
Scope កំណត់កន្លែងដែល variable អាចប្រើ
Data Types
let str = "text"; // String
let num = 42; // Number
let bool = true; // Boolean
let arr = [1, 2, 3]; // Array
let obj = {name: "John"}; // Object
let nothing = null; // Null
let undef; // Undefined
Variable អាចរក្សា data types ផ្សេងៗ
Naming Rules
// Valid names
let firstName = "John";
let age2 = 25;
let _private = true;
let $jquery = "value";
// Invalid names
// let 2age = 25; // Cannot start with number
// let first-name; // Cannot use hyphen
// let let = "test"; // Cannot use keyword
Rules សម្រាប់ដាក់ឈ្មោះ variables
Best Practices
- ប្រើ const តាមលំនាំដើម, let នៅពេលត្រូវការ reassign
- ជៀសវាង var (ប្រើ let ឬ const)
- ប្រើ camelCase សម្រាប់ឈ្មោះ variables
- ប្រើឈ្មោះដែលមានន័យច្បាស់លាស់
- Declare variables នៅដើមនៃ scope
សង្ខេប
- Variables រក្សាទុកទិន្នន័យ
- var - Function scope, hoisted (មិនសូវប្រើ)
- let - Block scope, reassignable
- const - Block scope, constant
- ប្រើ const តាមលំនាំដើម