The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try and access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined
) identifier without an early error:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
(name is undefined)
You: What is name
? (*)
JavaScript: name
? What's a name
? I don't know what you're talking about. You haven't ever mentioned any name
before. Are you seeing some other scripting language on the (client-)side?
name = null;
You: What is name
?
JavaScript: I don't know.
In short; undefined
is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null
is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null
is not, conceptually, the same as false
or ""
or such, even if they equate after type casting, i.e.
name = false;
You: What is name
?
JavaScript: Boolean false.
name = '';
You: What is name
?
JavaScript: Empty string
*: name
in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
Best Answer
In your posts controller, you need to define
@posts
, which, based on the error you haven't.As
@posts
is not defined callingeach
on it will generateundefined method
each' for nil:NilClass`.