• Brooke Bachman

Declarative Vs. Imperative Functions in Javascript

I can sometimes be stubborn about adopting new ways of doing things, if my old ways are effective.


Touch typing is something I did not start to practice until I started coding.


I can type surprisingly quickly and accurately with my creative style, but I know with practice touch typing will be faster and more accurate.


Most recently I have had to step into the new and exciting with arrow functions.


There are two types of arrow functions, but the kind I will focus on today are the ones with implicit returns.


This is the old way of imperative functions where you detail each individual step. We need to make sure we use the return keyword because Javascript does not have implicit returns outside of arrow functions.


Unlike our friendly language Ruby.


function Func(x,y) {

return x * y

}


This is another way to write an arrow function. It is most similar to the imperative function.


You may notice it also does not have an implicit return.

asgdfashj


const arrowFunc = (x, y) => { return x * y };


or


((x,y) => x * y)


You may notice we are able to do way more with drier code. They take up less lines, they can accomplish complex tasks in a few easy steps.


Let's take a look at some functions that replace the beloved for loop.

hdksahka

for (index = 0; index < array.length; index ++){

return array[index] + 1

}


Let us do this with a declarative function.

array.map(x + 1)


Map in Javascript allows you to edit each item in an array and returns a new array to you.


It is non-destructive it does not affect the original array. It creates a new array.


I have turned over a new leaf, I love declarative functions and arrow functions.


At first, they were scary, but like all good things in life, at first, they may seem new and frightening but nothing ventured nothing gained.












8 views