The code below will produce 8 due to the fact the second declaration will override the first one. Yup! Makes total sense.   EXAMPLE 1  function foo(){     function bar() {         return 3;     }     return bar();     function bar() {         return 8;     } } console.log(foo()); // ---&gt; 8   The following code produces 3 which means that it is the first expression that is invoked.   EXAMPLE 2  function foo(){     var bar = function() {         return 3;     };     return bar();     var bar = function() {         return 8;     }; } console.log(foo()); // ---&gt; 3   I tend to conclude that in JavaScript, only the first declared variable is used as shown above. However, the code below produces 7 (hmmm... scratching my head)  EXAMPLE 3  var a = 4; var a = 7; console.log(a); //---&gt; 7   Eventually, I will be using let or const (to prevent declaring the same variable many times) to declare variables and not var but I'm trying to understand why the results produced in example 2 and 3 are so unpredictable. Thanks.
647
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.  The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.  The two ways are:  var functionOne = function() {     // Some code };     function functionTwo() {     // Some code }   What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
27078
I noticed for a while now the following syntax in some of our code:  if( NULL == var){    //... }   or  if( 0 == var){   //... }   and similar things.  Can someone please explain why did the person who wrote this choose this notation instead of the common var == 0 way)?  Is it a matter of style, or does it somehow affect performance?
8344
I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:  var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) {     var td = document.createElement('td');     var select = document.createElement('select');     select.setAttribute("...", "...");     select.onchange = function() {         onStatusChanged(select, callid, anotherid);     };     td.appendChild(select); }   When the onchange event is fired for a &lt;select&gt; element however, it seems like the same values are being passed to the onStatusChanged() method for every &lt;select&gt; in the table (I've verified that in each iteration of the loop, callid and anotherid are being given new, distinct values).   I suspect this is occuring because of the nature of how I am setting the event handler, with the select.onchange = function() syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by callid and anotherid is the value set in the last iteration, not the value set at the individual iteration.  Is there a way that I can copy the value of the parameters I am passing to onStatusChanged()?  I've changed the title to better reflect the question and the accepted answer.
203
I came across this code:  void f(const std::string &amp;s);   And then a call:  f( *((std::string*)NULL) );   And I was wondering what others think of this construction, it is used to signal that function f() should use some default value (which it computes) instead of some user provided value.  I am not sure what to think of it, it looks weird but what do you think of this construction?
71695
This code always works, even in different browsers:  function fooCheck() {   alert(internalFoo()); // We are using internalFoo() here...    return internalFoo(); // And here, even though it has not been defined...    function internalFoo() { return true; } //...until here! }  fooCheck();   I could not find a single reference to why it should work, though. I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.  Could someone please enlighten me?
12708
In python, you can have a function return multiple values.  Here's a contrived example:  def divide(x, y):     quotient = x/y     remainder = x % y     return quotient, remainder    (q, r) = divide(22, 7)   This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value.  Let's have X return that value also").  When should you draw the line and define a different method?
15222
After reading ilkkachu's answer to  I learned on the existence of the declare (with argument -n) shell built in.  help declare brings:     Set variable values and attributes.      Declare variables and give them attributes. If no NAMEs are given,   display the attributes and values of all variables.      -n ... make NAME a reference to the variable named by its value   I ask for a general explanation with an example regarding declare because I don't understand the man. I know what is a variable and expanding it but I still miss the man on declare (variable attribute?).  Maybe you'd like to explain this based on the code by ilkkachu in the answer:  #!/bin/bash function read_and_verify  {     read -p "Please enter value for '$1': " tmp1     read -p "Please repeat the value to verify: " tmp2     if [ "$tmp1" != "$tmp2" ]; then         echo "Values unmatched. Please try again."; return 2     else         declare -n ref="$1"         ref=$tmp1     fi }
23755
Generally, when using the conditional operator, here's the syntax:  int x = 6; int y = x == 6 ? 5 : 9;   Nothing fancy, pretty straight forward.  Now, let's try to use this when assigning a Lambda to a Func type. Let me explain:  Func&lt;Order, bool&gt; predicate = id == null     ? p =&gt; p.EmployeeID == null     : p =&gt; p.EmployeeID == id;   That's the same syntax, and should work? Right? For some reason that doesn't. The compiler gives this nice cryptic message:     Error  1   Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'   I then went ahead and changed the syntax and this way it did work:  Func&lt;Order, bool&gt; predicate = id == null     ? predicate = p =&gt; p.EmployeeID == null     : predicate = p =&gt; p.EmployeeID == id;   I'm just curious as to why it doesn't work the first way?  (Side note: I ended up not needing this code, as I found out that when comparing an int value against null, you just use object.Equals)
89259
In an academic text, I need to explain a section of a computer program. This section extends from line 10 to line 15 in the code. Is the following way to refer to these lines gramatically correct?   The scopes of the two declarations overlap from lines 10 to 15.   Or should I use one of these alternative forms:   The scopes of the two declarations overlap from line 10 to line 15. The scopes of the two declarations overlap in lines 10 to 15. Any other possibility?...   Because this need appears frequently in the text, this is not just a matter of choosing the safest approach. I woul like to know what is correct and what is not so that I can use some variation trhoughout the text.
23614
This question has bugged me for a while. I want to write a nested function, f(g(x)). If I naively enter it:  \begin{align}     f(g(x))=y \end{align}     The problem is that each and every parenthesis is the same size as all of the others. Shouldn't the outer parentheses be larger? But if I do this:  \begin{align}     f\left(g(x)\right)=y \end{align}     Now it looks even less like the functions are nested. What's the proper way to do this?
51606
Possible Duplicate:          This is something I haven't quite figured out yet, but I have been using function(){}() just because my VIM syntax highlight screws up if I add the parenthesis, although I've seen (function(){})() around many times, maybe its an IE thing?  edit:  var singleton = function() {     // code }();  var singleton = (function() {     // code })();
36147
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:  void methodName() {   int i = 7;   for (int j = 0; j &lt; 10; j++) {     int i = j * 2;   } }   Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school.  Perl can do this, as can Scheme, and even C.  Even PL/SQL supports this!  What's the rationale for this design decision for Java?  Edit: as somebody pointed out, Java does have block-scoping.  What's the name for the concept I'm asking about?  I wish I could remember more from those language-design classes. :)
29117
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.  First I tried this example in the console:  a = b = {}; a.foo = 'bar'; console.log(b.foo);   The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.  a = b = 'foo'; a = 'bar'; console.log(b);   That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.  Why does this happen?  N.B. This example could be simplified even more with the following code:    a = {}; b = a; a.foo = 'bar'; console.log(b.foo);  a = 'foo'; b = a; a = 'bar'; console.log(b);     (I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
58389
I'd like to write a function that I can call from a script with many different variables. For some reasons I'm having a lot of trouble doing this. Examples I've read always just use a global variable but that wouldn't make my code much more readable as far as I can see.  Intended usage example:  #!/bin/bash #myscript.sh var1=$1 var2=$2 var3=$3 var4=$4  add(){ result=$para1 + $para2 }  add $var1 $var2 add $var3 $var4 # end of the script  ./myscript.sh 1 2 3 4   I tried using $1 and such in the function, but then it just takes the global one the whole script was called from. Basically what I'm looking for is something like $1, $2 and so on but in the local context of a function. Like you know, functions work in any proper language.
20286
I have quickly read over the  documentation.  This kind of example has helped me to understand better, though:   delegate int del(int i); del myDelegate = x =&gt; x * x; int j = myDelegate(5); //j = 25   Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
3450
I've always wondered this - why can't you declare variables after a case label in a switch statement?  In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:  switch (val)   {   case VAL:     // This won't work   int newVal = 42;     break; case ANOTHER_VAL:     ...   break; }     The above gives me the following error (MSC):     initialization of 'newVal' is skipped by 'case' label   This seems to be a limitation in other languages too.  Why is this such a problem?
53521
What JavaScript keywords (function names, variables, etc) are reserved?