Javascript - how to declare namespace objects using new conventions

92 views Asked by At

I am a big fan of latest programming conventions and latest additions to programming languages. Recently I read in Google Guidelines that we should use const and let instead of var.

Now in my project I have namespace object variables (if that's what they are called, correct me please if I am wrong) like this

var myObj = {

    func1: {},
    func2: {}
};

var myOtherObj = {

    var1: 'foo',
    var2: 'bar'
};

How should I name these objects now using the new conventions, with const or with let? I am confused because I don't know if these big objects change over time, or not...

3

There are 3 answers

0
Denys Séguret On BEST ANSWER

const doesn't prevent objects from changing (said otherwise it doesn't freeze them). It prevents the value of variables to change.

For example you can still do

const myObj = {

    func1: {},
    func2: {}
};

and then

myObj.fun3 = function(){...

What you can't do with a variable declared with const (but which doesn't seem to be your will) is

myObj = {};

Modules are usually declared with const.

2
sma On

The general rule I try to follow is: const everywhere you can, let when you can't use const and var never.

In the case of your example, when you are defining objects (or in other cases arrays, etc.), I tend to define those with let to give a clear indication that either the variable reference could change or the contents inside.

const will not prevent properties of objects or elements in a list from being changed, so if you're unsure if thats going to happen, its best to use let in my opinion. It's more clear and could prevent confusion down the road.

0
Pointy On

If you really want a symbol that can't change value to refer to an object that is also immutable, you can do this:

const CONSTANT = Object.freeze({
  a: "hello",
  b: "world"
});

Also bear in mind that older platforms are still out there that won't support const and let (and probably Object.freeze() for that matter).