3

Some help needed with the Quiz:

Question 5:

function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = '11';
}
alert(typeof bar());

Q: What is alerted? A: function.

Based on this tutorial, even it does not say that clearly and this is probably my misinterpretation, I was expecting the following behavior, when bar() gets called:

  1. Function foo() added to the lexical environment of bar().
  2. var foo = '11'; overrides this definition, leaving foo undefined.
  3. When return foo; is executed, foo is undefined.

What happens in the initialization? Any links for good documentation?

Question 12:

String('Hello') === 'Hello';

Q: what is the result? A: true.

I thought String() would return an object and 'Hello' is a primitive string, thus the answer would be "false". Why is it "true"?

Question 20:

NaN === NaN;

Q: what is the result? A: false.

What is the logic? What happens here?

masa
  • 2,762
  • 3
  • 21
  • 32

2 Answers2

3

Question 5:

This is because of hoisting, I answer this here in more detail.

function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = '11';
}

Is semantically the same as:

function bar() {
    var foo = function(){}; // function declarations and 
                           // variable declarations are hoisted
    return foo;
    foo = 10;
    foo = '11';
}

Question 12:

Calling String on something as a function does not create a new object. Note it is not called as a constructor:

String("a"); // a primitive value type string "a"
new String("a"); // this creates a new string object

Quoting the specification:

When String is called as part of a new expression, it is a constructor: it initialises the newly created object.

Question 20:

Pretty much because the specification says so. NaN is not equal to anything, including itself. The rationale is not to get two miscalculations equal to each other by mistake.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Question 5: I understand hoisting, but what happens with the variable initialization? Is it simply so that because `foo` is already defined, `var foo = '11'` does not undefine it? – masa Aug 17 '14 at 08:06
  • @masa yes, precisely. `var a = 10; var a;console.log(a)` logs 10 – Benjamin Gruenbaum Aug 17 '14 at 08:12
1

I've done a video series of javascript in which I'm explaining David Sharrif's all javascript questions. Have a look at this playlist:

Solutions: David Sharrif Quiz

mehulmpt
  • 15,861
  • 12
  • 48
  • 88