var app = angular.module('UseConstantsToMakeYourCodeUnderstandable', [])
.config(function ($provide){
$provide.constant('dayNames', {
SUNDAY:0,
MONDAY:1,
TUESDAY:2,
WEDNESDAY:3,
THURSDAY:4,
FRIDAY:5,
SATURDAY:6
});
});
app.controller('MainCtrl', function($scope, dayNames) {
$scope.isTodayAWeekDayWithoutConstants = function() {
var dayOfWeekAsNumber = new Date().getDay(),
isWeekday = dayOfWeekAsNumber !== 0 && dayOfWeekAsNumber !== 6;
return isWeekday;
}
$scope.isTodayAWeekDayWithConstants = function() {
var dayOfWeekAsNumber = new Date().getDay(),
isWeekday = dayOfWeekAsNumber !== dayNames.SATURDAY && dayOfWeekAsNumber !== dayNames.SUNDAY;
return isWeekday;
}
});
<!DOCTYPE html>
<html ng-app="UseConstantsToMakeYourCodeUnderstandable">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>without constants</h1>
<p ng-show="isTodayAWeekDayWithoutConstants()">It's a week day... go to work now.</p>
<p ng-hide="isTodayAWeekDayWithoutConstants()">It's the weekend... relax a little.</p>
<hr />
<h1>using constants</h1>
<p ng-show="isTodayAWeekDayWithConstants()">It's a week day... go to work.</p>
<p ng-hide="isTodayAWeekDayWithUsingConstants()">It's the weekend... relax a little.</p>
<p>The result is the same whether you use constants or not. But the difference lies in how much more easily you can understand the code that uses constants.</p>
</body>
</html>
# Use constants in AngularJS to make your code easier to read, understand and maintain.
| This example is deliberately simple to make the salient parts easier to find
and understand; to make it easy to copy the technique used here into a more
realistic application.
You may find yourself having to work with values (data returned from an API, for example)
that are difficult to understand. Consider this example:
```javascript
console.log(data.customerType);
// 'hvr'
```
You may have to make decisions in your application based on that data. It can be easy to find yourself in this situation.
```javascript
switch (data.customerType) {
case: 'hvr'
// hmmm... what does 'hvr' mean?
break;
case: 'otp'
// wait... what?!
break;
case: 'xyz'
// I better ask someone from the back end team what all of these acronyms means
break;
// fill in any number of case statements
// using equally cryptic values here
}
```
When you track down the right team member and get the answers you need to solve the immediate problem, you _can_ just implement your solution and leave it at that. If you think ahead and realize that you (or some other developer who arrives on the scene later) might need this information again, you might sprinkle your code with comments explaining the meaning of those cryptic values.
```javascript
switch (data.customerType) {
case: 'hvr'
// high value repeat
break;
case: 'otp'
// one-time purchase
break;
case: 'xyz'
// I think you get the point by now
break;
}
```
But you don't have to stop there. If this data makes multiple appearances in a bunch of different places in your application, I would argue that you _should NOT_ stop there. You can make two small changes to make the lives of your team mates, present and future, a whole lot easier.
You can define some constants.
The _names_ of the constants will reflect the meaning of the values they represent. They are self documenting. And you'll never have to use the actual values in your code so it'll be easier to avoid bugs related to typographical errors.
OK, you're convinced that it's a good idea. Implementing constants involves two simple steps.
1. Define the constants in your module
2. Inject and use them in your controller(s).
## Defining constants in an Angular application
Use the ```$provide``` service in the module's ```config``` function.
```javascript
var app = angular.module('UseConstantsToMakeYourCodeUnderstandable', [])
.config(function ($provide){
$provide.constant('customerTypes', {
HIGH_VALUE_REPEAT: 'hvr',
ONE_TIME_PURCHASE: 'otp',
ANOTHER_MEANINGFUL_NAME: 'acv' //another cryptic value
});
});
```
Now you have a variable called ```customerTypes``` that can be injected anywhere you need to use it.
## Injecting and using constants in an Angular controller
```javascript
app.controller('MainCtrl', function($scope, customer, customerTypes) {
$scope.calculateDiscount = function() {
let discountPercentage = 0;
switch (customer.customerType) {
case: customerTypes.HIGH_VALUE_REPEAT
discountPercentage = 15;
break;
case: customerTypes.ONE_TIME_PURCHASE
discountPercentage = 5;
break;
case: customerTypes.ANOTHER_MEANINGFUL_NAME
discountPercentage = 25;
break;
return discountPercentage;
}
});
```
If you ever find yourself having to work with values (from an API, for example)
that don't make sense
```javascript
console.log(data.customerType);
// 'hvr'
```
you may be
If you have to use that data to make decisions in your application, it's easy to find yourself in this situation.
```javascript
switch (data.orderType) {
case : 'hvr' // ask someone from the back end team what 'hvr' means
//
break;
// fill in any number of case statements
// using equally cryptic values here
case : 'abc' // ask someone from the back end team what 'xyz' means
//
break;
}
```