0

for a simple function such as

function foo(hash)
 {
   for(var k in hash){
    if (h.hasOwnProperty(k)){
        console.log('Key is: ' + k + ', value is: ' + h[k]);
    }
   }
}

if you passing an argument like

var m = new Object();
m['one'] = 1;
foo(m);

you will see the result on your console, but if you pass an argument like

foo(({} ['one'] =1));

or

foo((new Object()['one'] = 1));

it will no go through the for-loop, the expression

(new Object()['one'] = 1) == m

returns false while,

(new Object()['one'] = 1) == ({} ['one'] = 1)

return true

any ideas why not? Thanks!!!

1
  • 1
    I don't think it's the problem, but were you aware that == does type coercion? Use === instead. Commented Mar 26, 2012 at 0:53

2 Answers 2

2

This expression is an assignment so it will returned the assigned value, not a new object with a field called one with the value 1.

console.log(new Object()['one'] = 1); // outputs '1'

var m = new Object();
m.one = 1;
console.log(m); //outputs the object with its set property

//Here you are comparing the value 1, returned by the expression in parentheses, to an object
(new Object()['one'] = 1) == m
Sign up to request clarification or add additional context in comments.

Comments

2

The property assignment evaluates to the assigned value, not the object to which the property was assigned. From the ECMAScript (ECMA-262) spec:

11.13.1 Simple Assignment (=)

The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let rref be the result of evaluating AssignmentExpression.
  3. Let rval be GetValue(rref).
  4. Throw a SyntaxError exception if the following conditions are all true:
    • Type(lref) is Reference is true
    • IsStrictReference(lref) is true
    • Type(GetBase(lref)) is Environment Record
    • GetReferencedName(lref) is either "eval" or "arguments"
  5. Call PutValue(lref, rval).
  6. Return rval.

(emphasis added)

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.