JavaScript Custom Function defined as a Variable, Should the Declaration be a ‘var’ or ‘let’ or ‘const’?

I have code-smell suggestion to add declaration to below function.

Add the “let”, “const” or “var” keyword to this declaration of “nullToEmpty” to make it explicit.

nullToEmpty = function (obj) {
    if(typeof obj == 'undefined'){
        return null;
    }else{
        return JSON.parse( JSON.stringify(obj).replace(/:null/gi, ':""') );
    }
};

I wonder what is the most appropriate declaration type for this type of a function, should I use const ?

  const nullToEmpty = function (obj) {
        if(typeof obj == 'undefined'){
            return null;
        }else{
            return JSON.parse( JSON.stringify(obj).replace(/:null/gi, ':""') );
        }
    };

Answer

var

var is the “old way” of declaring variables – it can be redeclared, and its scope is local ( only exists inside the current function ) if declared inside a function, and global otherwise. It might be useful in some cases, but it’s not that recommended anymore since the global scope may cause some undesired effects if not used with caution.

let

let is a newer declaration, and has almost the same behaviour as var, but the scope is always local.

const

const is also always local, but it differs because it cannot be redeclared. That is a little bit misleading sometimes, though, because “you can’t redaclare” does not mean “you can’t alter it”.

That works as expected for primitive values ( strings, numbers, etc ), but not for objects, arrays or functions.

This is invalid code:

const primitive = 1;
primitive = 2;

This is valid:

const array = [1, 2, 3];
array.push(4);

answer

So, with all that said: yes, I would use const in that scenario. Your function declaration is not going to change, and there is no need for it to be of a global scope.