Reputation: 2915
I want to know that is there any better method to do :
var name = $('input').attr("name") != "undefined" ? $('input').attr("name") : "";
Here i am reading the name
attribute of input
. My problem is when i read the name
for newly created text
element, then it was undefined
. So for not showing undefined
to the user i have to put this check.Now i have to ready so many properties and in all of then the same problem exist so that`s why i want to know that, Is there any better way to deal will this?
Upvotes: 2
Views: 65
Reputation: 38468
You don't have to explicitly compare it to undefined. undefined will return false when used in an if statement. By using OR operation you can assign empty string in that case.
var name = $('input').attr("name") || '';
Also undefined and "undefined"
are not equal in JavaScript. Your original code would already get false negatives.
Upvotes: 5
Reputation:
Short circuit evaluation: (I love this in JS)
var name = $('input').attr("name") || '';
Upvotes: 3