Javascript Custom Variable Syntax instead of var use $ [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a javascript library and wanted to make a custom variable syntax so instead of using var use $ like php. To be clear I DO NOT want to use PHP. I am making a special library for public use.
I honestly don't care if you give me a function I just really need to use $ instead of var please I really need this.
var x = 10; // Normal JavaScript variable
$x = 10; // Custom Variable Syntax which is what I would like

JavaScript provides no means to extend the language in this way.
If you want to invent your own syntax, you'll need to design your own programming language and transpile it to JavaScript (as CoffeeScript does, for example).
(NB: $x is a valid identifier in JavaScript, you just can't cause any variable name starting with a $ to be inferred (by JS) as being a locally scoped variable when you assign something to it. $x = 10; would therefore throw an error (or create a global if you weren't using strict mode)).

JavaScript Syntax is not customization and keywords can not be overloaded.

Language is language, you can't jump over it's rules. But you can look around, use it's native possibilities.
As I know- there is no option to write
$x = 10;
in javascript. Just no.
But you can dance like jQuery ($ as alias of window.jQuery- that's not solution, but just first think about similar actions).
Can you tell more about that problem? Why do you need that? Maybe there's simpler way?

Related

Is it OK to use a function declaration for Javascript namespacing? [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 5 years ago.
Improve this question
Every time I see JS namespacing referenced it is implemented with an object expression. If I want to be sure that my namespace exists before it is assigned any properties, can I instantiate it by way of function declaration?
e.g.;
function namespace() {}
vs
let namespace = {};
The former being hoisted, and guaranteeing that properties I append to my namespace won't encounter an "undefined" error.
I know it works at least for my basic tests, but are there pros/cons to this?
Edit: Another example: https://jsbin.com/nuquxuxinu/edit?js,console
Edit: Bergi provided some good clarification, but I still need to be convinced as to why using a function as a namespace is a bad idea.
ANSWER: Since my question was marked as "opinion based" I can only deduce that there is no technical reason why you shouldn't use a function for a namespace.
No, you should not make your namespace object a function object unless you need it to be callable. If the function does nothing (like in your example), don't use a function.
Hoisting does not have any benefits for you. The variable declaration let namespace is hoisted just as well. What is actually important is that the members of your namespace are created before you use them, and they are created by assignment. Just put them in the right order in your file - first the namespace object instantiation, then the properties of that object (if they were not already created as part of it in an object literal), last the code that uses the namespace.

Is it ok to create global URL variables? [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 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.

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.

Should numbers be avoided in Javascript function names? [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 heard from a JS developer recently that you should avoid using numbers inside function names.
For example:
function test1test() {
// function body
}
I've never come across this before so I was wondering if it's true? If so, why?
There's nothing wrong with having numbers in your function name, it's just a little unconventional. The ultimate goal in function and variable naming is readability and clarity of code, so if you think including a number in your function name make the code more clear, you should make that a priority.
However, for maximum readibility and clarity in most cases, your function names should be camelCase verb phrases to follow the predominant convention.
For instance, you might want to name a function convertToMp3(), in which case it would be silly to instead name the function convertToMpThree(). But you should avoid using names like obj2Array() or format2(), because those don't make your code more clear.
Ok, I'm going to try to answer this in without a my-opinion base...
Refering to W3's article on Javascript's best practices, we find the following statement, regarding to names:
good variable and function names should be easy to understand and tell you what is going on — not more and not less. One trap to avoid is marrying values and functionality in names. A function called isLegalDrinkingAge() makes more sense than isOverEighteen() as the legal drinking age varies from country to country, and there are other things than drinking to consider that are limited by age.
Note the not more and not less. There's no reference on why it should matter to use or not a number in the naming of a function/variable. It is just a case of what will be easily understood when you/others read the code.
doesnt make sense to avoid this in general..
its rather a question of style and when it actually makes sence in your context
The only actual restriction is that you cannot start a member name with a number. Other than that, it's a matter of style. Having said that, I cannot think of a member in the standard library that has a number in it. It's certainly rare to need this, but it can be useful. No need to be too dogmatic about these kinds of things.

javascript code obfuscation tool [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a recommended javascript code obfuscation tool?
I have searched it in stackoverflow,and someone suggest the 'YUI compressor'.
However it just do the following:
remove the annotatation/white space/new line
replace local variable
or something ele.
But It does not replace the property of one object.
Say I have a code like this:
var a=obj.fun();
var b=obj.pro;
I want something like this:
var xxx,yy,zz;
xxx=obj['yy']();
yy=obj['zz'];
Then even people re-format my code,he can not even know the propery/methods of one object unless he re-do the method/property replacement.
This is just an example, I just want the tool do more obfuscation other than just compress.
Any suggestion?
Try the Google Closure Compiler. In advanced mode it also refactors parts of your code and creates some performance improvements that way.
Javascript is a dynamically typed language, interacting with the browser, so it's almost impossible to do a proper analysis to find where an object can pop up in the code.
For these reasons you cannot safely rename the properties of an object.
You should try the google closure compiler, it provides three levels of writing:
The first one is WHITESPACE_ONLY
The second one is SIMPLE_OPTIMIZATIONS
The third one is ADVANCED_OPTIMIZATIONS
WHITESPACE_ONLY removes comments, trim line breaks and unnecessary spaces. The output code is identical to the source JavaScript.
SIMPLE_OPTIMIZATIONS also renames local variable and function parameters.
ADVANCED_OPTIMIZATIONS is the most aggresive, besides the optimization in the above two levels, it also does:
global variable renaming
remove uncalled functions
function inlining
For the give example:
//INPUT CODE
function unusedFunction(note) {
alert(note['text']);
}
function displayNoteTitle(note) {
alert(note['title']);
}
var flowerNote = {};
flowerNote['title'] = "Flowers";
displayNoteTitle(flowerNote);
WHITESPACE_ONLY result is :
//WHITESPACE_ONLY OUTPUT CODE
function unusedFunction(note){alert(note["text"])}function displayNoteTitle(note){alert(note["title"])}var flowerNote={};flowerNote["title"]="Flowers";displayNoteTitle(flowerNote);
SIMPLE_OPTIMIZATIONS result is:
//SIMPLE_OPTIMIZATIONS OUTPUT CODE
function unusedFunction(a){alert(a.text)}function displayNoteTitle(a){alert(a.title)}var flowerNote={title:"Flowers"};displayNoteTitle(flowerNote);
ADVANCED_OPTIMIZATIONS result is:
//ADVANCED_OPTIMIZATIONS OUTPUT CODE
alert("Flowers");
I think the SIMPLE_OPTIMIZATIONS and ADVANCED_OPTIMIZATIONS meet your need.
with my limited knowledge on this subject. I would like to suggest the google closure compiler:
http://code.google.com/closure/compiler/docs/api-tutorial3.html
It says there that they do property renaming

Categories