The following code is not mine. Created by Microsoft Azure for window.appInsights. This code works in Edge & IE, but fails in Chrome (throws "SyntaxError: expected expression, got '&&'" in the console). Firefox complains about it, but works anyway.
Can someone explain to me what this is doing (attempting to do)? I've not seen something like this before.
if (true === && "" !== "") {
UPDATE
Thank you all for your answers. I thought it was poorly written code, but wanted to be sure it didn't contain a coding shorthand I wasn't aware of. Your answers cleared that up for me !
It probably is a mistake . It shouldn't work. === is a binary operator and therefore expects 2 operands not 1. && is not an expression neither a valid identifier.
Read it in english. if true is strictly equal to or empty string is strictly not equal to empty string
i wonder what "" !== "" is trying to do since it will always evaluate to false lol
Related
I have the following code amd it gives me compilation error:
for(var i in test){
(this.watcherFailureCount> 10) && break
}
However the following works:
if(this.watcherFailureCount> 10)
{
break
}
Am I missing anything here? why the first one is not working for me?
The && tries to evaluate your expression and cast its return value to boolean. The break you use is a keyword that controls the loop and should not be used in expressions.
Some languages allow that but it just seems that js doesn’t. And to be fair it is ok not to because is missleading. Imagine conditions like: a && b && break && c && d = a.
There is no real benefit in the first option unless you codegolf or something, and if you codegolf you chosed the wrong language :).
Dont fully understand what youre trying to achieve here however impretty sure the first code snippet is incorrect syntax.
If you want that as an inline if statement try:
if(this.watcherFailureCount>10)break;
However ensure if you are using break that it is inside of some form of code loop like a while or a for loop. And using && with break is invalid as break cannot be a true or false statement so it cant be used like that.
When passing the following code to jshint, it considers the linebreak in the if-condition to be bad, saying "Bad line breaking before '&&'."
if (1 == 1
&& true) {
console.log("hello world");
}
However, having the linebreak after '&&' is fine.
if (1 == 1 &&
true) {
console.log("hello world");
}
Why does jshint consider the first to be wrong and the latter to be right?
According to a discussion on GitHub:
This may cause problems like semi colon insertion and old javascript parsers breaking. Please check a large range of browsers.
This check can be disabled with laxbreak:true.
The laxbreak option is on its way to deprecation, but I'm not sure if the default jshint behavior will change.
The creator of JSHint probably doesn't like this kind of wrapping and prefers the && in the first line which seems to be much more common:
The primary reasoning behind this convention is that the operator makes it clear that the line is a continuation of the preceding line. With the operator before the line break, this is much harder to spot.
Actually there's an issue about exactly what you are asking about on Github: https://github.com/jshint/jshint/issues/557
I find the code below , but I can't understand this.
if (!-[1, ] && !window.XMLHttpRequest) {
document.execCommand("BackgroundImageCache", false, true);
}
What does if(!-[1,]) mean ? Thanks
It's a hack to detect old Internet Explorer. -[1,] is -1 in modern browsers (so false with !) but NaN in old IE (true negated). The first version to return correct result is IE9.
That exact code will never yield anything other than false, so it is nonsensical as entered. I assume that this is rendered output and that depending on some serverside variable, it may sometimes be something different.
Seeing as it uses window.XMLHttpRequest, I realize it could also be some poor form of browser check. [1,] creates an array, but the trailing comma will make the array treated differently in Chrome and Internet Explorer. Chrome will recognize this as an array of only one number, which could be implicitly cast to a number, whereas IE will consider it to be an array containing two items, which can't be cast to a number.
-[1,0] will yield NaN in all browsers. -[1] will yield -1 in all browsers. Hence -[1,] will yield NaN in IE (and hence execute the code), and -1 in other browsers (and not execute the code).
This is a terrible hack. Don't use it.
If you want to find out whether window.XMLHttpRequest will work, test for that specifically, and not for anything else.
This is particularly bad code:
-[1, ] Results to the number -1.
!-[1, ] would always be false.
Since the [] implies an array, this is bad, cause if you had more than one value in that array, the - would give you a NaN.
I'm trying to create an assert method in Javascript. I've been struggling with arguments.callee.caller and friends for a while, but I can't find a way to reliably get the full text of the calling function and find which match in that text called the current function.
I want to be able to use my function like this:
var four = 5;
function calculate4() { return 6; }
assert(4 == 2 + 3);
assert(4 == four);
assert(4 == calculate4());
assert(4 != 3 && 2 < 1)
and get output like this:
Assertion 4 == 2 + 3 failed.
Assertion 4 == four failed.
Assertion 4 == calculate4() failed.
Assertion 4 != 3 && 2
Right now, I can't get much beyond Assertion false failed. which isn't very useful...
I'd like to avoid passing in extra parameters (such as this) because I want to keep the assert code as clean as possible and because it will be typed many, many times. I don't really mind making it a string, but I'm concerned about issues of scoping when trying to eval() that string. If I have no other options, or if my concerns are ill-founded, please say so.
I'm running this in an .hta application on Windows, so it's really jscript and I have full access to the filesystem, ActiveX etc. so system specific solutions are fine (as long as they don't require Firebug etc.). However, I'd prefer a general solution.
There's no reliable way you can do this passing only a single argument. Even with eval, the variables used would be out of scope. Parsing arguments.caller would work if arguments.caller made only one call to assert, by searching for it and parsing the argument expression. Unfortunately, none of the proprietary tools available to you will help.
I ended up using the following function, which allows me to optionally duplicate the text of the assertion as a second argument. It seemed simplest.
function assert(expression, message)
{
if (!expression) {
if (message + "" != "undefined" && message + "" != "") {
document.write("<h2>Assertion <pre>" +
message +
"</pre> failed.</h2><br>");
} else {
document.write("<h2>Assertion failed.</h2><br>");
}
}
}
Maybe that helps someone. There are probably better methods available, but this worked for me.
Note that I've only been programming in Javascript for three days, so there's probably a number of improvements that could be made.
It is actually possible, at least in browsers and Node.js. I don't know about .hta applications.
Modern browsers, Node.js and hopefully your environment put a stack property on error objects, containing a stack trace. You can construct a new error, and then parse out the file path to the file containing the assert() call, as well as the line number and column number (if available) of the call. Then read the source file, and cut out the assert expression at the given position.
Construct an error
Parse error.stack, to get filepath, lineNumber and columnNumber
Read the file at filepath
Cut out the bits you want near lineNumber and columnNumber in file
I've written such an assert function, called yaba, that might get you going.
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.