Why can a function call expression be assigned to a variable, but not the other way around?

This is a very basic JS question, but this "issue" drives me crazy.

From simple algebra I would expect that both first and the second statement are valid. But the second is always throwing "Invalid assignment" error.

Does anyone have a good explanation for it?

fieldname1 = document.getElementById("emailID1");
document.getElementById("emailID2") = fieldname2;

Thanks so much,

Upvotes: 1

Views: 108

Answers (3)

Hossein Zare
Hossein Zare

Reputation: 580

You can't assign a value to an object itself in this case.

document.getElementById("emailID2") = fieldname2;

As i guess you want to do something like this:

document.getElementById("emailID2").name = fieldname2;

Upvotes: 0

will-t-harris
will-t-harris

Reputation: 98

The assignment operator resolves the right side of the equal sign and stores it in the variable on the left side, which is what is happening in the first line.

The second line is basically trying to take the value of a variable fieldname2 and store it in a function call document.getElementById("emailID2")

JavaScript doesn't know how to resolve that at runtime, so it's throwing an invalid assignment operation.

There's more information on assignment from MDN here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators

Upvotes: 2

Pointy
Pointy

Reputation: 413702

Most common programming languages, including JavaScript, require that the left-hand side of an assignment (the "target") be something called an l-value. That means it's an expression that denotes a place to put a value. A simple variable name, or a reference to an object followed by .propertyName suffix, works as an l-value.

In your case, the function call return value is not an l-value, because JavaScript does not make that possible (some languages do). A function call is always an r-value, meaning something that appears on the right-hand side of an assignment.

Now, in your particular case, because getElementById() returns a reference to a DOM element, you can do something like this:

document.getElementById("something").name = "frederick";

The function still returns an r-value, but that .name works as a property reference and thus as an l-value.

Upvotes: 3

Related Questions