Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Class fields let you declare properties directly in the class body, without using the constructor! You can have public fields (accessible everywhere) and private fields (only inside the class using #).
class User {
constructor() {
this.name = 'Guest';
this.age = 0;
this.role = 'user';
}
}
const user = new User();
console.log(user.name); // 'Guest'class User {
name = 'Guest';
age = 0;
role = 'user';
}
const user = new User();
console.log(user.name); // 'Guest'this. assignments in the constructor anymore!Use # prefix to make fields truly private - they can't be accessed from outside the class!
class BankAccount {
// Public field
accountNumber = '12345';
// Private fields (# prefix)
#balance = 0;
#pin = '0000';
deposit(amount) {
this.#balance += amount;
console.log(`Deposited: $${amount}`);
}
getBalance(enteredPin) {
if (enteredPin === this.#pin) {
return this.#balance;
}
return 'Invalid PIN!';
}
}
const account = new Account();
account.deposit(100);
console.log(account.accountNumber); // '12345' ✅
console.log(account.getBalance('0000')); // 100 ✅
// These throw errors!
console.log(account.#balance); // ❌ SyntaxError
console.log(account.#pin); // ❌ SyntaxErrorPrivate fields are truly private - not just a convention! You literally can't access them outside the class.
class User {
// Public fields
username = '';
email = '';
role = 'user';
// Private fields
#password = '';
#loginAttempts = 0;
#isLocked = false;
constructor(username, email, password) {
this.username = username;
this.email = email;
this.#password = password;
}
login(enteredPassword) {
if (this.#isLocked) {
return 'Account locked!';
}
if (enteredPassword === this.#password) {
this.#loginAttempts = 0;
return 'Login successful!';
}
this.#loginAttempts++;
if (this.#loginAttempts >= 3) {
this.#isLocked = true;
return 'Too many attempts! Account locked.';
}
return 'Invalid password';
}
// Public method to access private data safely
getLoginAttempts() {
return this.#loginAttempts;
}
}
const user = new User('alice', 'alice@example.com', 'secret123');
// Public fields accessible
console.log(user.username); // 'alice' ✅
console.log(user.email); // 'alice@example.com' ✅
// Private fields NOT accessible
console.log(user.#password); // ❌ Error
console.log(user.#loginAttempts); // ❌ Error
// But can access through methods
console.log(user.login('wrong')); // 'Invalid password'
console.log(user.getLoginAttempts()); // 1 ✅Private fields MUST begin with #. You must use # everywhere you reference them!
Each instance gets its own copy of the fields - they're not shared!
Can't use bracket notation: this['#field'] won't work. Must use this.#field
Declare properties directly - no constructor needed!
Use # for truly private, encapsulated data
More readable and maintainable classes
Modern JavaScript class syntax standard