I am have two noderefs in alfresco javascript file which i am trying to compare as below.
if(personRef == userAsscNodeRef){
do something
}else{
do something else
}
It seems to be syntactically correct but always going to else part. I tried with strict equal i.e. === as well as adding .toString() to both noderefs but still same result.
How can it be possible?
Regards.
Assuming this is repo tier Javascript, you are really dealing with Java NodeRef objects and == behaves like it does in Java and compares identity. You want to compare equivalence, so use personRef.equals(userAssocNodeRef). Yes, pretty unexpected behavior. Beware of Strings and Date objects as well.
Use String():
if(String(personRef) == String(userAsscNodeRef)){
do something
}else{
do something else
}
Related
Given the type coercion and the performance issue, as a JS newbie, I've always tried to avoid using double equality and opted for triple equality instead.
However, when does it make sense to use double quality?
Short answer: it never makes sense to use == instead of ===.
Long answer: while it never makes sense, there are cases where you want to write less code, and you are sure about your input.
== is not that bad if you really understand what's truthy. There are some gotchas, for example [1] == true and [2] == false.
Remember that the principal aim of Javascript was to be an easy language to be used by web designers, that's one of the reasons behind all this stuff you encounter.
As a simple example, as Barmar said, the best approach is to use it to avoid converting data and check equality. Here is another example:
const deleteTodos = _ => {
if (howManyTasksToRemoveInput.value == tasks.length) {
warningLabel.innerHTML = "You can't remove all the list";
} else if (howManyTasksToRemoveInput.value > tasks.length) {
warningLabel.innerHTML = "You DEFINITELY can't remove more tasks than you have";
} else {
tasks.splice(0, +howManyTasksToRemoveInput.value);
}
}
There's one case where there's a clear benefit to using ==, which is foo == null: this is true if and only if foo === undefined || foo === null, a commonly useful test.
Even here, using something like node's isNullOrUndefined(foo) (which is implemented as return value == null;!) is a much clearer way to express the intent, if it's not an established practice in the code-base you're working in.
When you want to allow Javascript to convert types automatically. E.g.
if (someElement.value == 3)
value of an input is always a string. The == operator will automatically convert it to a number here, so you don't have to write
if (parseInt(someElement.value) === 3)
You should be careful, since some some of the automatic conversions may not do what you expect.
Note to people who pretend to be Moderators:
Do not dislike if you could not understand this question. It has enough information enough details and very useful to people who use font-icons in JS
I am trying to compare two strings that contain font-icons, but it is failed. I have tried comparing like below
a === b
a == b // Though Browser will do my conversion job
btoa(a) == btoa(b) // Browser scolded me.
Are there any alternative ways?
Fiddle
In your fiddle, element.innerText is returning undefined, hence it is failing.
Use element.textContent instead. Also, since your div contains , you'll need to take some extra precaution in some browsers since it might try and convert it into an object of some sort. (Currently happening on my browser)
I would like to know if leaving an empty if statement for certain situations as:
else if(typeof console === 'undefined'){}
Just to have the code bypass the rest of the function It is an accepted and safe way to work or there are other recommendation practices for these cases?. Thank you.
It's fine and safe to leave if branches empty, the only thing I would add is a comment:
else if(typeof console === 'undefined')
{
//explanation why nothing has to go here
}
Without seeing the rest of the code I'm unsure how you're using this to "bypass the rest of the function", there may be a better way to do this.
From what information you've provided me, I can glean that the answer is "no". It will work, but it's bad style. If you would like to bypass the rest of the function, why not return; or put most of the logic in the if statement that pertains to it so that there is no bypassing at all?
I just had a case in which I chose to use an empty if-statement (professional context). I must agree though, there definitely is a technically cleaner solution. Still, since in a professional context time is important too, I chose to use the empty if-statement in my case, so I wanted to share my train of thought with you.
In my case I'm patching existing code with a variable that is used to skip already existing nested if-statements. The main function keeps running before and after the statement.
Original Code:
if(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
// ... code continues with variables set inside the statements.
Now we want to add a global Parameter to not validate anything. What are my options and why do they suck?
Solution A sucks because much work and less easy to read:
if(!bValidateNothing && bValidateA){
}elseif(!bValidateNothing && bValidateB){
}elseif(!bValidateNothing && bValidateC){
}
Solution B sucks because empty if-statement:
if(bValidateNothing){
// empty
}elseif(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
Solution C sucks because it becomes too nested (in my case there have been some additional ifs in the original code):
if(!bValidateNothing){
if(bValidateA){
if(xx){
}elseif(xy){}
}elseif(bValidateB){
}elseif(bValidateC){
}
}
Solution D, the technically cleanest solution by adding additional functions, sucks because you need to split your code, which needs a lot of time, and may result in new errors.
(no pseudocode)
So, to answer the question "accepted and safe": it works, it's readable, safe and quick. Sometimes that has to be enough, considering the alternatives. If you have the time to avoid using it, I'd probably still recommend that instead.
Funny enough, the time I saved by using this quick way to implement my logic, has now been successfully spent adding my cents to this ten year old already answered question.
Just don't write a block for a case you don't want to handle.
If you only want to do something when console exists, then do that:
if(typeof console !== 'undefined'){
// your code
}
// else if(typeof console === 'undefined'){}
// you don't need that second part
Or maybe I didn't quite get your issue?
Same as Pioul's answer, but I'd add that imo checking existence in javascript looks much tidier with the !! (notnot) operator.
if(!!console){
// your code
}
// else if(!console){}
// you don't need that second part
Sometimes it is useful to have debugging information printed out:-
if(typeof console !== 'undefined'){
console.log("debug info");
}
Then, before releasing the code, simply comment out all the console.log's
// console.log("debug info");
This can be done with a macro.
It will leave an empty if statement. But this is not a compilation error so that's OK.
Note, that if you're going to comment out the line it is important that braces are used. Otherwise you'd have the next line dependent on the if statement which would be a bleeding shame.
Using an empty if statement can be a valid and accepted practice in certain situations.
For example, when working with a try-catch block, you may use an empty if statement to handle specific errors without disrupting the rest of the function. Additionally, it can be used for performance optimization by short-circuiting the evaluation of certain conditions.
Make sure that when using an empty if statement, it is properly commented to provide context and explanation for its use.
Example:
try {
// code that may throw an error
} catch (error) {
if(error instanceof SpecificError) {
// handle specific error without disrupting the rest of the function
}
}
Another example:
if(isFirstConditionTrue && isSecondConditionTrue && isThirdConditionTrue) {
// Do something
} else if(isFirstConditionTrue && isSecondConditionTrue) {
// Do nothing, because third condition is false
} else {
// handle other conditions
}
It's always a good practice to add comments explaining the purpose of each empty if statement and why you chose to use it in a certain scenario. It's not generally considered bad style as long as it serves a specific purpose and is well documented.
When running:
if (data.custaccount.webaddress) {
alert('found it');
}
I get the error
data.custaccount is undefined
The only way i can get around it seems to be with multiple IFs like so:
if (undefined != data && undefined != data.custaccount && undefined != data.custaccount.webaddress) {
alert('found it');
}
Is there any way i could do this more simply?
In php we'd normally use the isset(data.custaccount.webaddress) and that worked quite well. is there an equivalent in javascript (or jquery)?
We have used try / catch, but found that to slow down performance of the script considerably.
I've seen someone else asking something similar on http://verens.com/2005/07/25/isset-for-javascript/ without any success, but am hoping that stackoverflow will do it's normal job of saving the day :)
Thanks!!!
Justin
Of course you need to check if data is defined, before accessing data.custaccount.webaddress.
You can write that check more shorten like
if(data && data.custaccount && data.custaccount.webaddress){
}
You need to check for that!
You're right, using try/catch would be bad practice. Another way to lookup the object could be by using the in operator like
if('custaccount' in data && 'webaddress' in data.custaccount){
}
I have the following IF statement in javascript:
if ( !(cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'JustifyFull') )
Any suggestions on how it could be written in a cleaner way?
Thanks
if(!cmd.match(/^Justify(Left|Right|Center|Full)$/))
In response to a few comments you can also mimic your strict comparison with a small edit:
if( typeof cmd != 'String' || !cmd.match(/^Justify(Left|Right|Center|Full)$/))
This will react in the exact same way as your current code, ignoring anything that's not a string.
Personally I think it is highly unlikely that you will need it.
This sounds like a good situation to use a switch. Just be aware that switches only do equality checking (==) not identity checking (===), though this should be fine.
switch (cmd) {
case "JustifyLeft" :
case "JustifyRight" :
case "JustifyCenter" :
case "JustifyFull" :
// do something
break;
case "somethingElse" :
default:
// do something else
break;
}
I would create a IsJustifyCommand(s) method or create a command abstract class that has a IsJustifyCommand() method on it. Then the code will read like a description of what it is trying to do.
Using regex may be neat, but will lead to maintenance problems if someone that is not a hard-core JavaScript programmer has to work on the code. However if you have lots of cases when regex is a good solution, then use it, as anyone looking at the code will soon pick it up.
(However I am a C# programmer not a JavaScript programmer, but like most programmer I have to look at / edit JavaScript code sometimes. I think most JavaScript is maintained by none JavaScript programmers.)
I hate when something is written like that. First I look at the code and think "if cmd is equal to JustifyLeft or JustifyRight... then invert that and... if that's true do the thing.. so that means if it's JustifyLeft...". For me it takes alot of time and I have to re-read the line to be sure I got it right.
I think it's better to write.
if ((cmd !== 'JustifyLeft') && (cmd !== 'JustifyRight') && (cmd !== 'JustifyCenter') && (cmd !== 'JustifyFull'))
It might be a little more verbose but I find it easier to follow. I read it as "cmd can't be any of the Justify-strings". Checking a long boolean expression and then inverting the whole answer is irritating.
I like the solution from scragar, just wanted to give my thoughts about inverting a long boolean expression.