Constants
A constant is a value you set once and can't change while the program runs. You create one with the const keyword:
const namaToko = "Laundry Kilat"
const jamBuka = 8
Here's how that differs from a variable:
var stok = 10
stok = 12 // boleh, variabel bisa diubah
const maksimum = 100
maksimum = 200 // ERROR: cannot assign to maksimum
Reassigning the variable stok is fine; reassigning the constant maksimum is a compile error.
When should you use a constant?
Use constants for values that are guaranteed to stay the same: rates, limits, the app name, the number of seconds in a minute, and so on. Giving them a name makes your code much easier to read than "magic numbers" scattered all over the place:
// kurang jelas
total := berat*7000 + 2000
// lebih jelas
total := berat*hargaPerKg + biayaAdmin
The first version is less clear; the second tells you what each number means. And if the rate changes one day, you only have to update a single constant declaration.
The value must be known at compile time
The compiler has to be able to work out a constant's value before the program runs. Literals (7000, "halo", true) and arithmetic between constants are allowed:
const menitPerJam = 60
const detikPerJam = menitPerJam * 60 // boleh: dihitung saat kompilasi
You can declare constants at package level (outside any function) or inside a function.
Task
A pay-by-the-kilo laundry wants to calculate its washing fees.
- Change the values of the two package-level constants:
hargaPerKg(price per kg) set to7000biayaAdmin(admin fee) set to2000
- Complete the function
biayaLaundry(beratKg int) intso it returnsberatKg * hargaPerKg + biayaAdmin.
Example: biayaLaundry(3) returns 23000.
The tests will make sure both are really constants, not variables.