title: Variable caching in JavaScript vs. other languages
body: <p>Someone recently told me that this is bad:</p>
  
  <pre><code>var el = $("#myID");
  $(el).addClass("a");
  $(el).addClass("b");
  $(el).addClass("c");
  </code></pre>
  
  <p>and that it should be cached like so:</p>
  
  <pre><code>var $el = $("#myID");
  $el.addClass("a");
  $el.addClass("b");
  $el.addClass("c");
  </code></pre>
  
  <p>So, my question is, why doesn't it get optimized automatically? In Java and other languages I <em>think</em> that the compiler is smart enough to do the caching itself. </p>
  
  <p>i.e., this:</p>
  
  <pre><code>// myList is a List&lt;String&gt;
  String str = myList.get(0);
  String trimmed = str.trim();
  String sub = str.substring(0, 5);
  boolean abc = str.startsWith("abc");
  </code></pre>
  
  <p>is no more efficient than this:</p>
  
  <pre><code>String trimmed = myList.get(0).trim();
  String sub = myList.get(0).substring(0, 5);
  boolean abc = myList.get(0).startsWith("abc");
  </code></pre>
  
  <p>Can anyone who knows more about compilers give me some insight here? Is JavaScript just stupid like that? Or is it also true for Java/others?</p>