Get extension of a file

This code return extension of a file , just pass the file name with extension and then it use the array pop method to extract the extension from file name.
example: 

extension("myvideo.mp4")
output : mp4

function extension(filename) {
    let ex = ( filename && filename.split('.').pop());
    console.log(ex);
    return ex;
}


This one is very useful when your code requirement is to get extension of file. There's lots of approach to achieve the same result some programming language has predefined methods for the same. But this will help us to think ourselves and create the approach for our code problem. So here is an approach for this

Approach

1. Create a method return extension of file. We using argument to be passed in the method that is filename which is string type.

2. There is lots methods available with string type variable to we going to make use of them string.split method this method break string into array and return an array but required an argument that tell it where to break this string like if value is : then it breaks the string where it will find : in the string "hello:this:is" so split (':') then result is [hello,this,is]. We split the filename with . As argument.

3. Now we use the result of split method that is an array and pass this to pop extension method
Whic return the popped element of an array and store it to ex variable. And then return ex element.


Try this example yourself. Try to write your own approach and then write the code also you can create flowchart for this to break down a Problem and easily achieve the solution.

Comments