DEV Community

Discussion on: Introduction to Functional Programming

Collapse
 
cappe987 profile image
Casper
let name = "Sayuri" ;
let message = "Hey, fellow devs, I am " ;
console.log(message + name)
Enter fullscreen mode Exit fullscreen mode

Do you consider this non-functional because it's all written in the global scope? Because I don't really see anything else that would make it non-functional. It doesn't mutate and doesn't access variables in an outer scope (since there is none). I would say it's completely functional.

function greet(){
    let name = "Sayuri" ;
    let message = "Hey, fellow devs, I am " ;
    console.log(message + name)
}
Enter fullscreen mode Exit fullscreen mode

Is this still non-functional? Impure functions are still allowed in functional programming btw. But should be kept to a minimum.

A pure function also doesn't have to take an argument. Although if it doesn't it's just a constant function, always returning the same value. But by definition, it is still pure.

Collapse
 
jackmellis profile image
Jack

Agreed. I can only assume that first example because it's logging to the console (side effect).

Yes there can be minimal impure functions because otherwise your code would do nothing. But I'd say if a function is impure, you should look for a way to make it pure, and only leave it impure as a last resort, most of the time function composition/partial application is the key.

Your greet function I would pass the console in as a parameter. Even better would be to create an abstraction over logging to the console so your function isn't coupled to the console implementation!

Collapse
 
cappe987 profile image
Casper

Yes of course you could improve the function. I just put his code in a function to show as example.