Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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;

}
like image 932
Clay Nichols Avatar asked Dec 16 '22 06:12

Clay Nichols


1 Answers

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]);
like image 91
Michael Berkowski Avatar answered Dec 26 '22 14:12

Michael Berkowski