2

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?

1
  • In the future it is preferable to ask and research one question at a time rather than multiple questions. Commented Aug 17, 2014 at 7:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 yes, precisely. var a = 10; var a;console.log(a) logs 10
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.