I am trying to resolve a issue in wordpress and being a noob, i was stumped when faced with the following code (the last part in bold which consists of typeof). Can anyone explain it to me in simple english?
<input id="et_pb_number" type="text" class="regular-text" value="<%= typeof( et_pb_number ) !== 'undefined' ? et_pb_number : '' %>" />
From my understanding, does it mean that something (assuming javascript) will check the type of the variable (et_pb_number) and see if it is undefined, and then what happen next?
what should i do if i don't want it to check the type of the value?
the surrounding part is not directly related to typeof. It's the Ternary Operator expression ? when-true : when-false
These two are exactly the same:
// ternary form
var test = typeof( et_pb_number ) !== 'undefined' ? et_pb_number : '';
console.log(test);
// if else block form
var test;
if (typeof et_pb_number !== 'undefined') {
test = et_pb_number;
} else {
test = "";
}
console.log(test);
The Ternary operator exists in many programming languages and can technically used exactly as if/else - but be careful! It is (as you experienced yourself) sometimes hard to read. One convention is, to only use it to return one or the other based on some condition (it's used in that way in your example). In a manner of speaking: this should (usually) only be used if it has no side-effects other than returning one value.
You could technically totally do this, but i would not recommend it (again: for understandability reasons. Technically it's just fine):
// don't do this (unless you have a really really really good reason.
var someValue = true;
someValue ? $('body').html('Hello') : $('body').html('World')
That example would change the outside world directly.