zhuanzhou
zhuanzhou

Reputation: 2453

function Values and Local Variables injavascript

var a = null;
function b() {return "B";}
(a || b)();

when i alert((a || b)());.it shows B. why? the return of a || b is true or false. why the above return B.

2:Local Variables

function power(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++)
result *= base;
return result;
}
power(2, 10);

a book says

if power were to call itself, that call would cause a new, distinct result variable to be created and used by the inner call and would leave the variable in the outer call untouched.

i can't follow it well, expect someone can explain it to me. many thanks

Upvotes: 0

Views: 60

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120516

1.

The return value of || is not boolean.

It is the first argument if it is truthy or the second argument if it is not.

So a || b is equivalent to a ? a : b and a && b is equivalent to a ? b : a.

2.

When power is called, a new frame is pushed onto the call stack to hold the paramaters and local variables like other languages. But JavaScript is a bit different from many languages in that when a function call results in a new function instance being created, the new function instance holds a reference to the stack frames on the stack when it is created. Since these stack frames hold locals, there is a different place in memory for functions created by different calls to the same function.

For example, in

function makeCounter() {
  var counter = 0;
  return function () { return counter++; };
}

var c1 = makeCounter();
var c2 = makeCounter();
c1(); c1(); c1();
c2(); c2();
alert(c1() + ", " + c2());  // -> 3, 2
alert(c1() + ", " + c2());  // -> 4, 3

makeCounter is first called to initialize c1. This creates a stack frame like { counter: 0 } which the first counter function points to. The second call to makeCounter used to initialize c2 creates a different stack frame.

So the code above is equivalent to

var c1SFrame = { counter: 0 };
var c2SFrame = { counter: 0 };
c1SFrame.counter++; c1SFrame.counter++; c1SFrame.counter++;
c2SFrame.counter++; c2SFrame.counter++; c2SFrame.counter++;
alert(c1SFrame++ + ", " + c2SFrame++);
alert(c1SFrame++ + ", " + c2SFrame++);

which should make it obvious why it alerts what it does.

Upvotes: 3

Related Questions