What does the colon ( : ) mean in this javascript line?

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;

}

Answers:

Answer

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]);
Answer

That's how you define key value pairs in an object. So errorTypes.2 would return the string "Position is not available".

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.