DEV Community

Shahir Ahmed
Shahir Ahmed

Posted on


What is and How to Use It

While interning as a software engineer at AMEX, I've come to learn you can write the same line of code a thousand different ways, only ever so slightly more concise every time. Most of the time I can also find myself using a certain method without any regard as to how it is more beneficial to use than any other. One piece of code that I recognized became more often used in my arsenal is the method. I decided to take this opportunity to learn more about the method and share those thoughts.

What is it? is a function that creates a new array by calling a function on each element in an array. Essentially, it's a loop in which the goal of that loop is to create a new array from a given array.

Imperative vs Declarative Programming

To understand and what it does, it helps to understand what imperative and declarative programming is. Imperative programming uses statements to mutate the state. Prior to using, I may have used a for loop to push items into a new array.

Imperative Programming

In this example I have an array of objects that contain some user data. Let's say my goal is to take this array of objects and convert it to an array of strings that only contain the usernames. I can approach this imperatively by creating a new empty array then use a for loop to push each individual username to a new array.
Screen Shot 2021-01-28 at 4.43.48 PM

Declarative Programming

Now if I want to approach this same piece of code declaratively, I can use the method. With, I can use a callback function to create a new array. A callback function is a function that will be called on later, which is why it has that name. Once it's gone over every item in the array, the map function will return an array containing the values returned from each call of the function. This is how I am then able to compute a new value and return it, giving us our array of strings.
Screen Shot 2021-01-28 at 4.49.53 PM


After this, you can see that gives us the same result, only with less code written - as is always the goal to keep your work more concise - and without mutating the original internal array, or source. I hope I will was able to deliver a nice and gentle introduction to :)

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!