简体   繁体   中英

When should I use a variable vs a raw value?

When should I define a variable? Would it be faster to just have a raw value inside a if statement vs a variable for one time use? For example, a raw value:

if(variable == 503) {
    //run code 
} 

VS this:

if(variable == anotherVariable) {
    //run some code
}

I am looking for which one would be faster and more secure (in a if statement and in general).

I would say that depends on what the variable represents. If it is some global constant that will be reused in more than one place then definitely use a variable. Otherwise if it's a one time use value, there is not need for a variable.

What I tend to do is to start out with a value. Then as soon as I encounter another case where I reuse that same value, then I move it into a global(or the necessary scope) variable.

EDIT:

After some discussion in the comments, it is clear that on the long run it is preferable to write out values with descriptive variable names.

The rule of thumb is to always use descriptive names for variables and values (and possible add comments to them). However, it is at the discretion of the programmer to determine if there is enough context for a value to exist without a variable name. Do consider future developers reading your code and don't assume that they will obviously know what you are talking about (an easy mistake to make).

I suggest always using a descriptive name for such values. In this particular case, what does 503 mean?

I completely agree with the other answers - just try to give another inspiration... I remember when I started to code I was over engaged in micro optimization like which variable will perform better but after all I personally came up with this rules for my coding style explicitly about variables and function names also:

  1. Others also have coding styles. Learning from the experienced ones means using theirs experience on the one hand and getting closer to an -so to say- "global" style which leads to better readability among each others code.
  2. Choose names as discriptive as possible. Not only that it makes your code much more readable and maintable but also this leads to focus on functionality inside of the code structure itself.
  3. Stay consistent doesn't mean to be flexible anymore and not to develop your style after new experiences but its a good practice in general.
  4. Let the name tell you the type also.
  5. Let the name tell you the scope also.

So after this general rules here are some practical examples:

I just choosed an very abstract example to show the general functionality...

var _outerScope = 'I prefer to mark my variables with the most global scope with a leading underscore';

(function (){

    var innerScope      = 'while this variable has its scope inside of this function its just meant to be used in here'
    if (_outerScope !== innerScope) {
        'everything is a bit more clear';
    }

    var fSetAttrTitle   = function ( $Selector, iSelector ) {         // read as: "function set attribute title" awaits an "jQuery object" and "integer"
      sOriginalTitle = $Selector.attr('title');                       // ra: "string original title" = "jQuery object selectors attribute title"
      $Selector.attr('title', 'this container has id: ' + iSelector); // ra: "jQuery object selectors attribute title" = "this container has id: " plus "integer selector"
      return sOriginalTitle;                                          // ra: "return string original title"
    };

    var isIdSel2inArray = false;                       // this should be self explanatory
    var aSelector       = ['#sel1', '#sel2', '#sel3']; // ra: "array selector" = [...]
    var iSelector       = aSelector.length;            // ra: "integer selector" = length of "array selector" | normally i would use "i" instead of iSelector in this case but for illustration lets stay with it
    while ( iSelector-- )                       // ra: "iterate until iSelector is 0"
    {
      sSelector = aSelector[ iSelector ];              // ra: "string selector" is a piece out of "array selector" with number "integer selector"
      if (sSelector !== '#sel2') {                     // ra: "if string selector is not '#sel2' then array selector is return value of set attribute title"
        aSelector[ iSelector ] = fSetAttrTitle( jQuery( sSelector ), iSelector );
      } else {                                         // ra: "if string selector is '#sel2' then '#sel2' is in array"
        isIdSel2inArray = true;
      }
    }

    if (isIdSel2inArray === true) {
      alert('ra: "if boolean is id sel2 in array is true alert this text"');
    }

}).call(this);

if (typeof innerScope === 'undefined') {
    'Of course I can not use this variable here while it has no underscore '
    + 'its not in the outer scope but the next one has an underscore so it is '
    + 'save to use it here ' + (typeof _outerScope !== 'undefined');
}

hope its a bit inspiring :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM