What is the best way to write this line in JS

im has simple if statment, and I want to check that the return values ​​have a default value, if so, put it on some kind of variable, for me it looks a little ugly (to use the statement twice), there is a shorter / more convenient way to write it in js?

    if (this._oIn._mMet[sM].returns.defVal) {
        var defValue = this._oIn._mMet[sM].returns.defVal;
+4
source share
7 answers

That doesn't make sense to me. If the value is undefined, then you must define the variable as follows:

if(typeof something === 'undefined')
 var something = 'something';

But in your case, the value is already testing, if it exists, then define a variable, so it makes no sense. So you just use the variable there:

var defValue = this._oIn._mMet[sM].returns.defVal;

You can also check to see if to use if not specified like this:

var defValue = this._oIn._mMet[sM].returns.defVal || 'undefined';
+1

i.e.

var defValue = this._oIn._mMet[sM].returns.defVal;

, "defValue", null. , . "if condition".

+1

:

var defValue = this._oIn._mMet[sM].returns.defVal || 0;

this._oIn._mMet[sM].returns.defVal -, 0, javascript boolean false.

0 , this._oIn._mMet[sM].returns.defVal undefined.

+1

|| ?

var defValue = this._oIn._mMet[sM].returns.defVal || false; // or whatever alternative you want it to be?
0

var defValue = this._oIn._mMet[sM].returns.defVal;
if (defValue) {
} // else { // only if you depend on the `undefined` value:
//     defValue = undefined;
// }

, if ,

var defValue = this._oIn._mMet[sM].returns.defVal || undefined;

, , .defVal undefined ( 0, "", false, null),

var defValue = this._oIn._mMet[sM].returns.defVal;
0

, - , var, , ( . , . returnValue 0, null undefined, 0 false.

// some possible expensive operation you only want to do once
var myReturnVal = this._oIn._mMet[sM].returns.defVal;
if (myReturnVal) {
    var defValue = myReturnVal;
    // do more stuff
} else {
   // do other stuff
}

, . - .

// if myREturnValue is undefined/null, this will crash
myReturnVal.doSomething()
0

One common way to do it if clearer statements is to transfer the check to a method, for example. Thus, you make it more readable and extensible, without losing attention while reading the code. In my opionon it looks better. (Just an idea, a wrong implementation, you need to check the null value and get the correct value from getDefaultValue (this)).

if(returnsDefaultValue(this))
    vardefValue = getDefaultValue(this);


function returnsDefaultValue(self){
    return self._oIn._mMet[sM].returns.defVal ? true : false;
}
-1
source

All Articles