What does the ":" mean in the 3-6th lines below?
function displayError(error) {
var errorTypes = {
0: "Unknown error",
1: "Permission denied",
2: "Position is not available",
3: "Request timeout"
};
var errorMessage = errorTypes[error.code];
if (error.code == 0 || error.code == 2) {
errorMessage = errorMessage + " " + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
The variable errorTypes
is an object literal. The :
separates the object property name (the numbers) from its value. If you are familiar with hash tables in other languages, this structure is a similar concept. Or in PHP, for example, this could be represented as an associative array.
You can do:
var errorTypes = {
0: "Unknown error",
1: "Permission denied",
2: "Position is not available",
3: "Request timeout"
};
console.log(errorTypes[0]);
// Unknown error
console.log(errorTypes[2]);
// Permission denied
Note that the normal syntax for referencing an object property (using the dot operator) won't work for these numeric properties:
// Won't work for numeric properties
errorTypes.0
SyntaxError: Unexpected number
// Instead use the [] notation
errorTypes[0]
In this instance, since numeric property names were used, the whole thing could have been defined as an array instead and accessed exactly the same way via the []
notation, but with less syntactic control over the keys.
// As an array with the same numeric keys
var errorTypes = [
"Unknown error",
"Permission denied",
"Position is not available",
"Request timeout"
];
console.log(errorTypes[2]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With