2

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).

bjb568
  • 11,089
  • 11
  • 50
  • 71
computerquest
  • 677
  • 1
  • 6
  • 17
  • 1
    It doesn't make a difference. – SLaks Jul 17 '14 at 00:24
  • 4
    Magic numbers in source are generally a bad idea from a maintenance perspective. See this: http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad – Brad Jul 17 '14 at 00:26

3 Answers3

6

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).

Elmer
  • 809
  • 9
  • 15
  • 1
    This is the correct answer. I was in the middle of writing a long answer detailing many reasons why it's good to have a variable. But in the end it still all boils down to this. – jay_t55 Jul 17 '14 at 00:31
  • Having a variable (or a `const`!) with a name that means something (and a comment) is nearly *always* better than having a magic number in the code. Someone, maybe even you at a later time, will come across that number and won't know what it means. I agree with BitBlitz and Code-Apprentice. – Stephen P Jul 17 '14 at 00:51
  • Stephen I agree with you, on the long run having variables with descriptive names improves code readability and maintainability. Please read the comment I left under @Code-Apprentice's question. In there I suggested a scenario where the use of a variable might not be necessary. – Elmer Jul 17 '14 at 01:00
3

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

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 503 is a random number that I thought of. – computerquest Jul 17 '14 at 00:33
  • @computerquest In a more realistic example, the "503" will have some meaning and should be assigned to a variable which describes that meaning. – Code-Apprentice Jul 17 '14 at 00:34
  • I agree that most of time a descriptive name would be preferable. However, in some cases if the other variables are well named then value might make sense. For example if you have something like `if (http_response_code == '503')` the semantics are somewhat obvious. But as @Code-Apprentice says, descriptive names are nicer. – Elmer Jul 17 '14 at 00:35
  • @Elmer That's exactly what I thought the "503" meant in the OP. Having a descriptive name for the first variable definitely makes it more obvious and in this context, the "magic number" isn't a bad thing. – Code-Apprentice Jul 17 '14 at 00:46
  • 1
    @Elmer the semantics are obvious in your example as you say, but I don't know what error code a 503 is off the top of my head, so having a name for it would *still* be useful. – Stephen P Jul 17 '14 at 01:00
  • @StephenP that is a good point, sometimes it is erroneous to assume that the reader will have the correct context/information to decipher the meaning of the value. – Elmer Jul 17 '14 at 01:03
1

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 :)

Axel
  • 3,331
  • 11
  • 35
  • 58