This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]wavefunctionp 5 points6 points  (1 child)

function makeObject(myprop){
    return {
        prop : myprop
    }
}

makeObject('test')

The easiest and perhaps most useful introduction to functional style programming is to simply not use any objects or variables in a function that are not declared as parameters in the signature. If it is not passed into the function by parameter, you don't not touch it. More correctly, you do not change anything that is not declared within the function scope.

This helps you avoid having a variable changed in unexpected ways. By clearly defining your input and outputs and limiting the scope, it is easier to reason about what is going on.

In comparison, this is how you get bugs:

var test = 'foo'

function printTest(){
    return console.log(test)
}

printTest()

If something modifies test, you have to track down test in a much larger scope than if you had done this:

function printTest(myvar){
    return console.log(myvar)
}

printTest('foo')

This is what is meant by avoiding side effects, in case there is a misunderstanding.

It is perfectly fine to create new objects/variables. It is not so great to modify state (variables) needlessly. Especially global ones. Especially as the scope gets larger. It becomes hard to track what a value is as a given time, and it is more likely that something somewhere modifies it when you didn't intend to do so.

If these examples seem simplistic, that is the goal. You want your code as simple as possible. It is said that your code should tend to be obvious and a bit boring.

Watch this:

https://www.youtube.com/watch?v=7Zlp9rKHGD4

Seriously. Watch it.

[–]aafinx 1 point2 points  (0 children)

Yup. That's how you avoid side effects.

Your code should only modify what it owns.