Is it ok to create global URL variables? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a number of scripts that I need to pass a url parameter to. I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
What I want to do is store the url within a global variable so that I have to change the url in 1 place to feed the various scripts downstream that rely on it.
I thought about a simple globals file that contains, for example:
var myURL = 'http://www.google.com'
I'll have additional urls, but I plan to follow in kind with those.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?

If you really have to have some global configuration, I'd stick it in an object / class so you could restrict your use of global variables to the minimum necessary, e.g.:
var Config = {
googleUrl: 'https://google.com',
otherUrl: 'http://example.com',
};
That would be better than having a global variable for each thing.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?
It might be worth explaining your use case a little more. For instance is it appropriate for these URLs to live in JavaScript configuration or do they belong to a specific UI component? If so should the UI component specify the URL on a HTML element as a data-attribute? If they belong with a specific JS module, should they be local variables for that module?
I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
Could you not use window.location.hostname for those?

I might be wrong, but I don't know why this should be a problem, as long as you are using constants.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
Edit:
But at the end you should avoid using global variables, because they could cause some problems at later debugging.

Related

How would a JS module be created? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a little confused on what to do here. I've seen a lot of people create modules in JS, but everyone usually does it differently. I've seen people wrap their WHOLE module in a (function(){})(); , or they declare an object literal, or do something crazy like window.Module = {};. I want to know what would be the best choice to be used (as in what you would think is most useful). Help would really be appreciated, and thanks.
There is only one official solution to create JavaScript modules. Anything else you have seen is either a polyfill for that solution, or a pale echo of the real thing.
The basic syntax is like so:
import otherStuff from "otherStuff.js";
var myThing = {};
myThing.stuff = function(){ /*...*/ };
myThing.do = function(){ otherStuff.doOther(); );
export default myThing;
It can get much more complicated, but the basics are:
Your module must be in a unique file. A file is a module.
Your module should probably export something, although this is not strictly necessary.
This is coming down the pipeline in JavaScript. Unfortunately, no one has been able to agree on the official specification of how to load the modules, so they are not on a track for any near-future release. That said, the specification is under development, and a polyfill that implements it has been created.
Your best bet to use the official module syntax is to run it through BabelJS and compile to a shim like Require (which uses the AMD format) so you can use it without the loader specification.
You can read more about the syntax here and here.
I would say : It depends on the final usage of your "module". If it's something that will be used internally, which means that no one else outside your business will use it, then anything can be used as long as you all agreed on the proper method. Otherwise, if it would be used by others : less global variables you create, better it is. As example, jQuery use "$" and "jQuery" as global variables (maybe others, but I'm not sure). When people adds modules to it, they always add them to window.jQuery.[Under jQuery var] where [Under jQuery var] shall be read on jQuery documentation for proper use.

Create a global library in javascript, holding both state and behaviour [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to create a globally-accessible library myLib in Javascript. My library should do the following
Keep a somewhat persistent variable myLib.tax.
-- It should survive through the handling of a typical browser user event, at least in simple cases. I don't care if it survives longer than that or not.
-- external code should be able to set the value of this variable, either through a setter or otherwise.
Has a function myLib.applyTax(var price).
-- return value is price + myLib.tax.
-- I don't care what it does if either price or tax is not a number.
Lastly, a brief example of how to call this from another file, in such a way that:
-- for example, file A might set the value of the tax, then file B might apply the.
-- this works even though files A and B are unrelated.
The purpose of this question is for me to understand code and state encapsulation and how to use them from elsewhere.
EDIT: For the benefit of anyone seeing this later, what I did not understand when asking this question is that referring from javascript file A.js to javascript file B.js is a difficult problem unless that is enabled externally, for example in the html. For more detail, see How do I include a JavaScript file in another JavaScript file?
From your comments I see you would implement a Singleton Pattern in C# through static methods and data.
In Javascript you can do the same by managing the closures and putting that data into the outermost one, which would then be accessible to all code due to lexical scoping.
But I'd rather avoid singletons every day. Instead, use dependency injection as follows. This is just an example to show the technique, you'll have to code an actual solution yourself.
var lex = (function () {
var privatedata;
function privatemethod()
{
}
return {
publicmethod1: function (arg1, arg2) { ... },
publicmethod2: function (arg1, arg2) { ... },
getPublicData: function () { ... }
};
}());
This incapsulated object is then injected wherever you need it:
function consumerCode(lexicon)
{
...
}
consumerCode(lex); // injects the lex instance into the consumer code
By having only one instance and passing that same instance around wherever you need it, you will have pretty much what you were asking for.
This technique is not limited Javascript but also useful in C#. But in Javascript with loose typing it is especially powerful.

Organizing large javascript files [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.
I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).
Right now, I have my code organized into objects, like so:
var ProductPage = {
addToCartBtn: "#add-to-cart",
init: function() {
ProductPage.initAddToCartPopup();
ProductPage.initSidebar();
...
},
...
};
Then, I call ProductPage.init() on $(document).ready.
My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:
(function ($) {
...
})(jQuery);
Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.
validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.
You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.
You can use require.js for dependency management.

How many Vars is too many in JS? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a page I am building, and our solution to a problem involved wrapping some code inside a function then calling that when required.
Now the page is growing, and each item has its own function. According to D. Crockford each function is put in a VAR anyway so:
function functionName(){}
is equivalent to:
var var1 = functionName(){}
So now we have LOTS of vars in the page (I have also written them specifically in the latter format as Mr. Crockford promotes) and I am getting worried this creates too many variables (not sure this will cause any issues, performance or otherwise). I am thinking of making a single Object Literal and adding each function as a value to a key. This I think will reduce all these vars into a single manageable unit and reduce the amount of variables I am using (and avoid any potential issues) - or will it?
Thanks!
var keyword is actually being used in order to manage variable scope.
Not using var keyword makes the variable a global one. The memory occupied by the variables are cleared when the variable isn't used anymore. Most of the modern browsers contains a garbage collector responsible for freeing up the unused spaces. So it's suggested that using var keyword in blocks would make your js interpreter search less for the variable, otherwise it will search the whole document in order to get the value.
In performance terms it doesn't matter, you can use as many variables as you want, the performance only will be affected by the tasks performed in the function.
As you keep increasing the variables, the heap limit set by the relevant JS engine will come into play.
For eg - V8 engine seems to have it set to 1.4 GB
If you do ever run out of that, it's high time you recheck the code & stop blaming JS.
On a serious note, from a practical point of view, that's an enormous limit, which tells you that you don't need to worry about it so much.
Besides your friendly neighborhood GC will always keep cleaning up & ensure you live lavishly with variables.
Encapsulating your code in a namespace is a good idea but you won't save memory or get a performance boost that way. From performance perspective both ways you've shown are the same.
There is a convention to avoid nameclashing however based on reverted domain - imagine a JS lib made for SO:
// The following two lines are to protect namespace from overwriting and allow to
// extend them easily
if (!com) var com = {};
if (!com.stackoverflow) com.stackoverflow = {};
com.stackoverflow.renderSomething = function(){
// Some very clever code here
};
There is nothing else you can gain this way but it's worth to organize your code this way.
And just to clarify:
function functionName(){};
is almost the same as
var functionName = function(){};
Almost because in the first form functionName is defined at parse-time and the latter form defines functionName at run-time.

Passing JavaScript data to page, best practices? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a web application where I need to pass some user data to the JS application on page load. I've identified 3 different approaches, and am wondering what is the best practice with regards to this. The data is not particularly sensitive, but it would be best it is somewhat more secure compare to others.
1. Asynchronously load the data
Using something like $.ajax(). I don't like this approach because it usually leads to the whole "loading" phenomenon and I would like to avoid. Have the data ready than make a separate call.
2. Burn the data into the page.
This can be achieved by doing something like this
<script>
var userdata = { somekey: somevalue }
</script>
3. Make a request using script tags
This can be achieved by doing something like this
<script src="server/getdata"></script>
I understand that this is somewhat like the 1st approach since it makes another get request to the server.
My question is, is any of the 3 approaches above different, or better in terms of security. I understand that all 3 methods are not particularly secure, especially since it can be easily sniffed either way, but is any of the above method a better practice than the other 2, and why?
Of the ones you've given, 2 is best, for just the reasons you said. However, I would not add a new global for it. Rather, I would do:
<script type="text/javascript" src="application.js"></script>
to create someGlobal (among other things) then:
<script>
someGlobal.userdata = { somekey: somevalue }
</script>
Another couple methods with the same advantages are:
data attributes. These are the data- ones. You can put arbitrary data, associated with particular elements (sometimes particular elements make sense; otherwise, you can use body).
Hidden form fields.

Categories