Strange Javascript statement - javascript

if (1) {
google_conversion_value = 1;
}
What is the meaning of the above statement? I mean, this looks like it will always execute so why bother with the if statement?
updated: one reason might be remnants of scripting on the server side. Any other ideas?
updated2: could as easily change the value of the assignment without bothering with the if statement, no?

There are two likely explanations:
It's a leftover from debugging.
The file containing this code is generated dynamically and the original sourcecode contains something like if(<?php echo $some_stuff_enabled; ?>)
However, in the latter case it would have been cleaner to output that code block only if the condition is met - but maybe it's used in some crappy template engine that just allows replacements but no conditionals...

I've seen this before, and I've always assumed it was a remnant of some old condition that was no longer needed, but never removed. I can't see any actual reason to do something like that otherwise.

Potentially because the person writing the code wanted an easy way to turn it off and on again, this is especially useful if there is a lot of code inside the block (not the case here).
Another possibility is that the original programmer couldn't be bothered writing the logic or, more likely, it hadn't been specified so the "if" was left as a placeholder.

More than likely left in from a debug release or something similar. You're right, it will always execute. It could also have been done like this so that it can be easily enabled / disabled by setting the if to 0. Perhaps the developer intended to use it as a flag somewhere else in the code?

actually, this happens when the "if" condition is driven from server, so instead of doing the right thing and not produce the script when the condition is false, they do something like this:
if (<% if (my_server_condition) then Response.Write("1") else Response.Write("0") %>){
// code goes here
}

Perhaps the if statement used to check for a legitimate conditional, and then someone replaced it with a truthy value for testing/debugging/etc.
You're right, it will always execute because 1 is truthy. I would go through your source control history and investigate that line to see if it used to contain a real conditional. If the conditional was always 1, then it's likely a debugging statement. Otherwise someone might have meant for it to be a temporary change, and may not have meant to check that in (which could be bad).

I'm not sure where this code is from, but as you indicated it will always execute. As for why you'd do this, there are times where you want to see what the result of branch code would be, without having to setup an environment. In this case you can comment out the actual value and replace it with if(1) instead for testing:
// if( ... some hard to achieve condition )
if (1) {
// Now you can see what happens if this value is set quickly
google_conversion_value = 1;
}
Of course the problem with this is that it's sometimes easy to forget to remove the if(1) and uncomment the proper condition.

This is actually the javascript recommended by Google on http://support.google.com/adwords/bin/answer.py?hl=en&answer=1722054#nocomments (click on Step 2 for the sample HTML)

Related

Botpress concatenate variable, as argument, in execute code action form

I know if I pass {{variable}} (like a {{event.text}}) in args field of action form works fine.
But, when I try concatenate this variable with a another String, this not work.
Result in {{state.api_url}}/users string, and I need http//myapi.com/users
Is it possible?
I may have an extremely kludgy workaround for this based on bad javascript.
I was looking to iterate a temp variable downwards. I did the assignment in the raw code box for a transition
Good code like temp.variable==1 would be a true/false test.
But just using one equals sign performs the assignment.
So temp.variable=temp.variable-1 in the raw code box subtracted one from my (numeric value) variable.
This seems to return False for the purposes of the transition so it doesn't matter where you point it as long as it's in the chain.
It seems to work for me, anyway.
I'm properly not sure what your code would look like, perhaps you make a new variable then do a transition with
temp.variable_you_just_made=state.api_url+'/users'
then call that variable doing your url thing?
[Looking around I come to suspect the correct thing would be to make a new action https://botpress.io/docs/10.0/getting_started/trivia_actions/ but I am new to all this]

What does this syntax mean which likes `functionName: {}`?

I have found a piece of code in my company's project like the following:
while(condition){
code...
reloop: {
if(somethingIsTrue) {
break reloop;
}
}
code...
}
I don't understand what reloop does, can anyone give a simple explanation?
reloop: is a label. They are rarely used, and serve a very specific purpose: they let you break or continue outer loops from inner loops.
The article on MDN about labels explains this better.
Note that labels are very rarely used, and most of the time needing a label hints that your code is unclear, and should be restructured. I have never, not even once, used a label in javascript.
Avoid them unless they are truly the only clean solution to piece of code that proves difficult to write. Prefer, instead, splitting code into functions that you can return from.
reloop is a label for the block. The break command breaks out of the labelled block.
See eg https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

javascript expression expected

I am still new a Javascript tried earching and tried the development tool in Chrome, too see if I could find the problem.
Working in Intellij IDEA 13, Java, javascript and xhtml.
My problem is that I have a piece of javascript, then in IDEA when moused over, says that
Expression Expected
the javascript code looks the following
<script type="text/javascript>
function nameOfFunction(){
if(#{trendAnalysisLocationReportController.model.showTargetLine}){
this.cfg.series[this.cfg.data.length-1].pointLabels = {
show: false
};
}
}
<\script>
the method in the if sentence is a java method with a boolean return value.
the error is shown when hovering
'#{'
if Had a look at the following questions, before :
Expected Expression
boolean in an if statement
But didnt get me a solution.
what Iam I doing wrong ?
It looks as though the problem is the part that you've got within the #{...} block. Without knowing the context, it's hard to be sure, but is this something in a view/JSP page that's supposed to be replaced with a property at runtime? The if block will expect the part inside the brackets to be a boolean value, so if that's rendered to either 'true' or 'false' it would execute at runtime but would likely show the error you're seeing in your IDE as it's not actually a valid piece of JavaScript. If, on the other hand, you're expecting to be able to call your Java method/property from your JavaScript code, you're going to need to do something that requests that value from the server-side code - AJAX or similar.
Also worth noting that we can't see what this.cfg is supposed to represent. If that's your entire script block, then there's nothing that defines the cfg object within the current scope.
One last thing, you should change the <\script> end element to as it won't be understood properly by some browsers.

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

javascript leaving an empty if statement

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.

Categories

Resources