In PHP, say if I have code like this:
$aValue = functionThatReturnsAValue(); // the function might return a string or null;
$anotherValue = $aValue ? process($aValue) : null;
only for brievity (IDK is this a good practice or not and also regarding the performance, etc), I used to change the code like so:
$anotherValue = ($aValue = functionThatReturnsAValue()) ? process($aValue) : null;
My questions are:
Is this style even a good practice?
How can I use this with JavaScript? I wrote with same style but got error.
Thank you.
You could use a logical AND && and process only a given value.
If aValue is null or a falsy value, this value is assigned to anotherValue, otherwise, it takes the value of process(aValue).
anotherValue = (aValue = functionThatReturnsAValue()) && process(aValue);
Since aValue is the value returned from executing functionThatReturnsAValue(), You can try this
var anotherValue = (functionThatReturnsAValue()) ? process(functionThatReturnsAValue()) : null;
Related
I’m having trouble with the isNaN function is JavaScript. I have a variable, trc, which I know is not a number, but I want my code to be able to tell. Unfortunately, isNaN isn’t detecting that it’s not a number, yet when I use an alert to show the value of the variable, it is indeed not a number.
trc = parseInt(getCookie("trc"));
cnn = parseInt(getCookie("cnn"));
klove = parseInt(getCookie("klove"));
if (isNaN(trc)) {
trc = 0;
}
if (getCookie("trc") == undefined) {
trc = 0;
} else {
trc = parseInt(getCookie("trc"));
}
alert(trc);
BTW, I have a separate function, getCookie(), that I made myself to get the value of a cookie.
You should check value of trc before.
If trc is null, then isNaN(null) return false.
Edit:
parseInt method doesn't return null value, but trc can be modified by external code - therefore I recommend using namespaces e.g:
var namespace = namespace || {};
namespace.trc = .....
Hi Guys I’m having trouble trying to set a variable (val) to be one of 2 possible object attributes. The below code explains what I’m trying to do.
function myFnct(elem, imgSrcType) {
var val = imgSrcType == "bg" ? elem.style.backgroundImage : elem.src;
val = 'image.jpg'
}
I’m using a ternary operator to try and avoid having to write:
if (imgSrcType === "bg") {
elem.style.backgroundImage = "url('image.jpg')";
}
else {
elem.src = "image.jpg";
}
Basically the ‘val’ variable is not getting set correctly as I guess its something to do with elem object. I’m trying to avoid using the if statement as I will need to use it a few times within the function. And I’m trying to keep is as DRY as possible.
Any help getting it to work with the ternary operator method would be awesome!
if (imgSrcType === "bg") {
elem.style.backgroundImage = "url('image.jpg')";
}
else {
elem.src = "image.jpg";
}
ugly but working rewrite:
void (
imgSrcType === 'bg'
&& (elem.style.backgroundImage = "url('image.jpg')")
|| (elem.src = "image.jpg")
);
Equals:
void (
imgSrcType === 'bg'
? (elem.style.backgroundImage = "url('image.jpg')")
: (elem.src = "image.jpg")
);
So by adding parentheses (elem.src = "image.jpg") you can do the assignment. You can also use a comma to return something in a value assignment.
Using this knowledge, you could rewrite myFnct:
function myFnct(elem, imgSrcType) {
var val = (
void( imgSrcType == "bg"
? (elem.style.backgroundImage = "url('image.jpg')")
: (elem.src = "image.jpg") ), //<= ternary done - comma
'image.jpg'
);
//now val = 'image.jpg'
}
Note: this is all about what is possible. If you need/want to keep your code readable, using the if ... else statement is the better option.
Ternary operations can only assign their outcome to a single variable. They are useful if you are setting that single variable to different values depending on the result of a boolean expression. Since you are trying to assign the image URL to either the background-image or to the source, you cannot use a simple ternary operation. The other answers are using pretty complex/quasi-obfuscated code to accomplish what could be done with a simple if/else statement. Your code - especially for such a simple operation - should be easy to read. So, I recommend just sticking with the following:
function setImage(elem, imgSrcType)
{
var imgURL = "image.jpg";
if(imgSrcType == "bg")
{
elem.style.backgroundImage = "url('" + imgURL + "')";
}
else
{
elem.src = imgURL;
}
}
I'm writing a script that adds labels to things on a page using an element from an array based on part of the link... so my array looks like this:
var componentList[9] = "Sunnyseed"
var componentList[10] = "Echoberry"
var componentList[11] = "Riverstone"
var componentList[13] = "Auraglass"
var componentList[14] = "Skypollen"
You'll notice there is no '12'... I want the label to be 'Unknown' when the array item doesn't exist. Now, I can't exactly test my solution since I can't cause the target page to throw me a 12... so I was hoping somebody would tell me whether this will do what I want or not...
var component = ""
if(typeof componentList[critterIDval] == 'undefined'){
component="Unknown"
}
else{
component=componentList[critterIDval]
}
This is obviously not the full script, but it should be the important stuff... I just want to know if that will make it say 'Unknown' when the critterIDval is 12 - since it could take years to come across the situation for testing.
You're pretty much there. You're using a single-equals sign in your comparison, so that will mess it up, and I'm not sure you can create a JS array like that, but aside from that, you're good.
Here is the test I ran for it:
var componentList = [];
componentList[9] = "Sunnyseed";
componentList[10] = "Echoberry";
componentList[11] = "Riverstone";
componentList[13] = "Auraglass";
componentList[14] = "Skypollen";
for (var critterIDval = 9; critterIDval < 15; critterIDval++) {
if (typeof componentList[critterIDval] == 'undefined') { // double equals here
component = "Unknown";
} else {
component = componentList[critterIDval];
}
console.log(component);
}
It looks fine.
Though if you are sure that the value will never be an empty string(like componentList[14] = '';) then you can try
var component = componentList[critterIDval] || 'Unknown'
I want the label to be 'Unknown' when the array item doesn't exist.
The typeof operator does not tell you if a property exists or not as it returns undefined when the property doesn't exist but also when it does exist and has been assigned a the value undefined or simply created but hasn't been assigned a value.
There are two primary ways to test for the existence of a property: the in operator, which also looks on the [[Prototype]] chain and the hasOwnProperty method of all Objects. So
if (componentList.hasOwnProperty(critterIDval)) {
component = "Unknown"
} else {
component = componentList[critterIDval]
}
which you could also write as:
component = componentList.hasOwnProperty(critterIDval)? componentList[critterIDval] : 'unknown';
PS. there are other methods, such as looking at Object.keys(componentList) and componentList.propertyIsEnumerable(critterIDval), but the above are the most common.
Edit
If your requirement is not just to test for property existence but to also test for a "truthy" value, then:
if (componentList[critterIDval])
may be sufficient and will return false where the value is '' (empty string), 0, false, NaN, undefined or null.
Maybe just testing for a non–empty string or number will do:
if (/.+/.test(componentList[critterIDval]))
but that returns true for NaN, null and so on. So you need to specify what you are actually testing for, otherwise you may get undesired results for some values.
I have been reviewing other peoples javascript codes and noticed variable lines like this:
opacity = isIn ? 0 : 1;,
opacity = isIn ? opacity + gap : opacity - gap;,
var s = this == binary ? h(binary, f, change, text) : h(text, r, change2, binary);,
And other lines of code like that. How do they work? What type of variable are they?
Thank you so much!
This is a special form of if called a conditional (or ternary) operator:
var value = condition ? value_when_true : value_when_false;
If the condition evaluates to true, value will be assigned value_when_true, if not, value_when_false.
It is functionally the same as:
var value;
if (condition) {
value = value_when_true;
} else {
value = value_when_false;
}
See this MDN article for detailed description.
Its called ternary operators
http://msdn.microsoft.com/en-us/library/ie/be21c7hw%28v=vs.94%29.aspx
var s = (some_condition) ? if_true_value : if_false_value;
same as
if(some_condition){
s = if_true_value;
}else{
s = if_false_value;
}
I've seen this hovering around some javascript for a while now and was wondering what it meant.
In this code:
var topics = {};
jQuery.Topic = function( id ) {
var callbacks,
topic = id && topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
topics[ id ] = topic;
}
}
return topic;
};
why does the variable topic have id && before it?
The && operator results in its first operand if it is "falsy" and to the second operand if the first operand is not "falsy". So, you could read this code as:
Let topic be topics[id] if this function was given a parameter¹, or
undefined if not.
¹ Passing false or 0 or other falsy values as a parameter would cause topic to get
that value, but reading the code does not leave the impression that you are supposed to do
that.
What that line is doing is ensuring that id is a truthy value before attempting to use it. It's probably not a good idea here, as it would make topics[0] inaccessible.
The line topic = id && topics[id] is roughly equivalent to if( id) topic = topics[id]; else topic = id;