PatrickJS / NG6-starter

:ng: An AngularJS Starter repo for AngularJS + ES6 + Webpack
https://angularclass.github.io/NG6-starter
Apache License 2.0
1.91k stars 1.35k forks source link

Why define object inside factory as const? #179

Closed Emnalyeriar closed 7 years ago

Emnalyeriar commented 7 years ago

With the const statement you can add properties to object because of how const is implemented. The object is not immutable so you can do that but it seems a bit illogical for me to expand an object that is declared as constant. Wouldn't a simple var/let be better here? Example code take from this starter:

let UserFactory = function () {
  const user = {};

  let getUser = () => {
    return user;
  };

  let isSignedIn = () => {
    return user.isSignedIn; 
  };

  return { getUser, isSignedIn };
};

export default UserFactory;
Emnalyeriar commented 7 years ago

Could I get a response to my question? That would be great :)

fesor commented 7 years ago

@Emnalyeriar I'll try to explain.

tl;dr You should use const by default. let should be used if value of a variable could be changed, for example for index in for loop.

With the const statement you can add properties to object because of how const is implemented.

const restricts changes of variable value. In case of objects, value will be reference to object, not object itself. So by making variable const we are just protecting ourselves from accidental changes of reference.

The object is not immutable

variable is. That's the point.

p.s. I prefer this code:

export default function userFactory() {
    const user = {};

    return {
         getUser() {
              return user;
         }

         isSignedIn() {
              return user.isSignedIn; 
         }
    };
}
Emnalyeriar commented 7 years ago

This makes sense, thank you for this explanation :)