Search code examples
javascriptnode.jsreversezerobrackets

what is the meaning of brackets after function : reverse[0]?


I'm using node v10.1 and i have an object which keeps some MIME types like this:

let all_mime_types = {
  //media types...

  text: "text/plain",
  html: "text/html",
  jpeg: "image/jpeg",
  jpg: "image/jpg",
  png: "image/png",
  javascript: "text/javascript",
  css: "text/css"
};

when i want to get to one of MIME types with some code(based on my refered files in directory), i see this code :

let mime =
        all_mime_types[
          path
            .extname(full_address)
            .split(".") // seperates the "." from path.extname(full_address);
            .reverse()[0]
        ];

my problem is .reverse()[0]part ...

when i delete 0 or [0] it returns undefined.

what does .reverse()[] and [0] mean ?


Solution

    1. split(".") takes string as an input, and returns array as output
    2. reverse takes array and reverses it, as the name suggests
    3. [0] is first element of the array, which in turn was last element of the original array

    So, what this code does, is having string such as "/path/to/file/some.txt", returns you "txt" as a result.

    Let's rewrite this is less confusing style:

    let file_path = path.extname(full_address)
    let split_by_extension_path = file_path.split(".")
    let reversed_path = split_by_extension_path.reverse()
    let extension = reversed_path[0]
    let mime = all_mime_types[extension]
    

    Please note that there are multiple problems with this code.

    First, not all files have extensions, and not all file extensions are correct.
    Second, probably your JavaScript files have .js extension, and not .javascript. Same for .text and .txt files.