Maybe I'm just too tired at the moment, but I can't find the reason why a plugin developer used the following construction:
jQuery.<myPlugin> || (function($)) {
var $.<myPlugin> = {
// plugin code goes here...
}
})(jQuery);
Of course this is a common construction, except for the use of || (OR operator as far as I know), which I don't understand.
Can you tell me why the developer used ||?
It would first check if jQuery.<myPlugin> exists, if not, it will continue to build the function.
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.
I develop a JavaScript module to prevent basic dom-based XSS on a client-side. I use a couple of standard functions: indexOf(), substring(), toString(), etc.
During a testing I found that some external JavaScript libraries sometimes can incorrectly override functions. For example, the following overriding of indexOf() function does not return -1 if an element is not present in the array:
; /* Start:/js/jquery.select.js*/
(function($){
//add class of js to html tag
$('html').addClass('js');
//create cross-browser indexOf
Array.prototype.indexOf = function (obj, start) {
for (var i = (start || 0); i < this.length; i++) {
if (this[i] == obj) {
return i;
}
}
}
So this new indexOf() can break ifStatement. The trivial example:
function protect(s){
...
if(sNodes.indexOf(node) !== -1) { {
/*injection found*/
sanitize(s);
...
}
}
Now indexOf() returns undefined if node is not present. In my case this can lead to false positive and sanitization of correct input data.
The script must be executed before and after DOMContentLoaded.
One note: I can not control environment where my. script will be used for sanitizing. It somethins like WAF and shoul work with any JavaScript application
My suggestions are the following:
Implement own versions of main critical functions (e.g., indexOf)
Save references to these function before they will be overrided and the use them:
Array.prototype._indexOf = Array.prototype._indexOf;
...
function sanitize(s){
...
if(sNodes.indexOf(node) !== -1) { {
/*injection found*/
sanitize(s);
...
}
}
Are they correct?
What are the best practices to deal with this issue?
Are my suggestions correct?
Yes. For solution 2, you might want to use var indexOf = Array.prototype.indexOf and then indexOf.call(sNodes, node) (if you trust that Function.prototype.call hasn't been messed with…) to avoid creating methods on builtin prototypes. And of course you need to ensure that your library is loaded before the malicious one.
What are the best practices to deal with this issue?
Ignore the issue. Write your code as you'd always do.
If you find another library that does such shit, a) file a bug with them and b) replace it with a better one. If anyone insists on using such a library, charge them extra.
If your actual goal is to prevent such issues entirely, use Caja.
I have some old JavaScript code that I can't change crashing on IE10 (I can change other script files).
Here is the crashing code:
if(isInternetExplorer && this.domElement.filters[0])
this.domElement.filters[0].play()
That code will not crash in ie8/9 because the DOM element has the non standard property "filters".
Here is the documentation to the filters property.
The only solution I can think of is to change the HtmlElement's prototype but I don't feel like it is actually possible or the good thing to do.
So how can I prevent IE10 from crashing when it tries to use the DomObject.filters property?
[EDIT]
I just found a 'solution'. This is also #JAM's solution.:
if (!HTMLDivElement.filters) {
HTMLDivElement.prototype.filters = [];
}
But I still feel bad about modifying a browser native object's prototype.
As you said, overriding the prototype of the object is one way of doing it; so if there is no other alternative you could try this:
Object.prototype.filters = Object.prototype.filters || []
Or even better (as you suggested your self):
HTMLDivElement.prototype.filters = HTMLDivElement.prototype.filters || []
This will set the filters property of the object, if it is non-existing.
Umm, use feature detection instead of browser detection? No isInternetExplorer please, but doesSupportFilters:
var el = this.domElement;
if (el.filters && el.filters.length && typeof el.filters[0].play == "function")
el.filters[0].play();
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.
I've come across the dollar sign function over the internets and decided to use it for a javascript toggle menu. However, the "$" symbol makes my code fail.
This is what I'm trying to use:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
function toggle(obj) {
var el = $(obj);
el.style.display = (el.style.display != 'none' ? 'none' : '' );
}
The $ from "function $(){" seems to break the code. How do you declare this function?
If I replace $ with "anything", it works, but not as a dollar function...
The dollar sign is not a standard Javascript function, but is part of a third party library.
There are two well-known libraries which use the dollar sign in this way.
The older one is called Prototype, but the one which is currently in vogue, and most likely to be the one you've seen in use is JQuery.
Both these libraries would be used by adding a <script> tag to your HTML page, to include the library code, after which you can use their functionality.
Most of the functionality of both these libraries is contained within their respective $() functions. In the case of JQuery, you can also refer to the $() function as jQuery() to prevent namespace clashes, in the event that you wanted to use both of them.
I suggest reading up on JQuery before continuing -- JQuery is very powerful, and adds a lot of functionality, but the coding style for writing JQuery code can be quite different from regular Javascript, and can take a bit of getting used to. And that's quite apart from learning the API and finding out what it can do.
To actually answer your question -- which is how to declare $ as a function name, I suggest having a look at the JQuery source code to see how they do it. However, I managed to produce a working $() function first time I tried, like this:
var $ = function() {alert('dollar works for me');}
$();
But to be honest, I wouldn't do that. If you really want to use the $() function in the way it's being used in other sites, you need to use JQuery. It does a whole lot more than just wrapping document.getElementById().
By the way, JQuery and Prototype are not the only similar libraries out there. If you're interested in this sort of thing, you may also want to look into MooTools, YUI, and a few others.
Hope that helps.
The $ sign is a notation for various javascript frameworks (prototype/jQuery). Since replacing it with "anything else" works, you most likely have a clash between that inline function and the framework you are using.
In itself, the notation and function is correct, as the following example shows.
Open a new tab/window and enter this on the address bar:
javascript:eval("function $() { alert('hi'); } $();");