I have to use this.state.<name> multiple times, how should I replace it with a simple variable name? Like we use global variables in other languages such as C, C++.
#Thomas yes, but there are a lot of functions in my code and even many items inside state for which i want shorter alias. So it is not ideal to do it with "const" in all functions. so by the word "globally", i meant how to declare those shorter alias only once ?
you can't. Javascript simply doesn't provide that feature.
JavaScript as a Language doesn't have the compile-step where these aliases would be filled in with the real commands.
There are preprocessors, like babel for wich you could write a plugin.
There are task-runner like gulp for wich you could write a script to build that aliasing syntax (although it's most likely not valid JS)
You can check out sweet.js maybe its functionalities already get you covered.
But maybe you'd consider learning JavaScript; realizing that JavaScript is not C and that you can't just transfer your coding style 1:1.
imo. the best Solution to get a bunch of shorter handles is Object destructuring. But this ain't aliases either; you need to understand what JS does here, and what the limits to this are.
Don't be too lazy to write a few more characters. Every modern JS IDE has an autocompletiton feature.
You can so something like this in render.
const { name } = this.state;
return(
<div>{name}</div>
)
Now you can use it just with name as many times you want in render as well you can do in methods.
It is not like creating alias but we can optimize code.
Related
This question is about ES6 not about global variables.
When the new ES2015 export or export default were introduced. They were made so that you can import/get the same variables, values or items somewhere else using import. So I have a simple question. Why should we use export and import instead of just making a simple object of a class and getting items through it or just making static or global variables?
I know the fact that it can be used to make your code much cleaner and also to put the code easily into multiple files but let's just assume we have first.js and second.js and we have a variable called names in the first.js that we want to get in the second.js. Now you can either do that with import and export or by making an object in the second.js and accessing our variable by that object. So why is it better to use export and import?
export was introduced to be used alongside import (you need to explicitly declare what you need to later import), as part of the ES2015 module standard.
Before these standard modules were implemented, splitting up Javascript code into multiple files and not have all objects pollute the global object was only possible using sort short of non-standard module definition and/or module loaders like RequireJS. The simplest case was to wrap your code in Immediately Invoked Functions. ES6/2015 just standardize Javascipt modules.
Now you asked why not just have Javascript objects even in many files? The answer to that is namespacing
Actually - you make a good point.
namespace stuff is in C++. There are lots of people who think it is cool to have a namespace indicator in front of everything they use.
So, instead of saying { cout << my_string << endl; }, their whole program has { std::cout << my_string << std::endl; }.
Sometimes you see stuff like { disk::io::byte::bit::atom::neutron::quark::say_hi(2) }. And, the guy who wrote that thinks he's a super developer.
But, as they are purist, it more likely you will see { std::cout << myString << endl; } because camel case is so much more preferential than human readable strings.
Now, in node.js I am always doing something like const ClassFromMod = require('mod-with-class'). In the file, you have to say module.exports = ClassDeclaredInHere. I always do this, because really, is there any other way provided?
Or you can do this const {ClassFromMod} = require('mod-with-class').
Then you have to have, module.exports.ClassFromMod = ClassDeclaredInHere.
So, doing the same thing in the browser is sort of OK. But, now global contexts and local contexts are harder to work with - really. Just a little harder sharing things between modules when you have to. But, not to worry almost all of the time people partitions their modules just right. That's because they are people - in fact the sort of people who are more cautious than those in charge of nuclear reactors - because those people do some web programming. So, no Chernobyl when it comes to partitioning modules. Right?
Now, you can get your hands into a class def. And, the class is itself something of a namespace.
So, then why is there not a global registry of classes? Only that maybe different companies (individual developers) will use the same name for two remotely different classes. But, likely there would be some way around that.
One way might be to assign classes to uses (sort of name spacey). But, it might be more categorical. Like "engine" for something with a car feature, or "engine" for something that runs a script. Programming languages might have something like "talking about cars here". What would that be like?
start>> talking about cars <
let bval = engine.rev()
if ( bval ) {
<about scripts> engine.run("small program")
}
<<stop talking about car
That's an idea. Looking at it, I don' like it. It's sort of like "with" that lots of languages use.
So, with new strictures imposed on the programming environments, you get bugs and scope troubles that add to your long long long day. But, you should get that your question drawn from clear thinking is in some sense being steamrolled by a small group of people who can. And, you can take out the trash for them.
So, what about identifying objects by features and enabling sort of a flat namespace management? Could be driven by AI. Could have been done thirty years ago. But, now is now. But, the future exists for correcting the mistakes of the past.
is it possible to create your own condition/control flow syntax in js? for example:
when( condition ) {
// execute code
}
this would add some sort of listener to a variable/object and execute whenever the condition is true.
I may just have to create my own programming language.
This is actually two questions:
Can syntax be added to JavaScript directly?
Can I set up code that runs when a condition changes?
The answer to the first is no. You can use preprocessing like sweet.js macros to accomplish that but its non-trivial.
The answer to 2 is yes, you can accomplish this in any ES 5 compliant environment (IE 9+):
var condition = {val: null};
Object.defineProperty(condition, "isTrue", {
set: function(val) {
if (val && !this.val) {
runSomeCodeYouWantRun();
}
this.val = val;
},
get: function() {
return this.val;
}
});
So whenever any code changes condition.isTrue the specified code will be run if the change is truthy. But for situations like this I prefer less ad-hoc approach. ES 2015 Proxy traps make this much cleaner (IMHO) but support isn't quite there yet. What you really are looking for here to get the job done today is an Observable.
Also note that writing a language to solve a problem like this is roughly equivalent to building a car out of spare parts to drive to the store for groceries. Just buy a car.
Welcome to the wonderful world of JavaScript transpilers.
JavaScript in and of itself does not have any utilities for creating your own syntax. In response to this, many tools exist online and in the NPM repositories that add just this sort of feature to JS by translating it to browser-compatible JavaScript. Here's a small sampling:
Babel.js adds ES6 syntax to ES5 JavaScript
Browserify adds Node.JS's require() functionality
Uglify.JS compresses JS into the smallest form possible that will still execute the same way
TypeScript (while more technically its own language) adds static type-checking to JavaScript
All of these transpilers, however different, all work the same way: they parse the source file(s) to an abstract syntax tree (or AST), run some transformations on that tree, and then spit out the resulting JavaScript file. If you wanted to create your own special syntax in JavaScript, you would do more or less the same thing. (Uglify.JS stands out as being particularly customizable in this regard).
All of that said, none of these transpilers fundamentally change the way that JavaScript works - you still have to translate whatever fancy syntax you want to use into plain, browser-executable JavaScript. This means that although you will be able to write your when(){} block syntax, the expression inside the parentheses cannot be a simple Boolean expression, but must involve something like an Observable object that inserts a callback (Knockout.JS does have a tool for doing this out of an expression built from its Observables).
I am writing a lot of Javascript code these days and I am making good use of JQuery. I am wondering if it is considered evil to create strange global variable names. I know that a lot of Javascript frameworks such as JQuery use the dollar character; $, but that greatly simplifies code as it can do so many things.
I am thinking of creating a $$ global variable in my code which would be defined as below:
function $$(tagName)
{
return $('<' + tagName + ' />');
}
The benefit of this is that my code has (1) abstracted out the logic of creating a new element, (2) made the code more concise, and lastly (3) I can almost create html elements within Javascript as concisely as html itself because JQuery has so many other selectors to chain off:
$$('div').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$$('ul').append(
$$('li').text('first'),
$$('li').text('second'),
$$('li').text('third')
);
);
Do you believe the above approach of creating $$ is legitimate or would you regard it as a no-no?
This is of course an opinion, but if I was new to your application, I would have to go look up what that function does in order to understand the code. Also, the function is simple enough that other developers would likely not bother using it, so you'd end up with a mix of techniques which is confusing.. And really, is this so bad?
$('<div/>').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$('<ul/>').append(
$('<li/>').text('first'),
$('<li/>').text('second'),
$('<li/>').text('third')
)
);
I prefer a clear, meaningful, self-documenting name over JQuery style $ any day of the year.
Also I find it confusing that the same name has different meanings depending on the context it is used in. Like $ in JQuery or this in javascript and will avoid using them as much as I can.
EDIT: In my opinion it should be up to the user to decide whether he wants to use a shorthand name for the framework he uses. It requires only one line of code:
var $ = jQuery;
When I look at pages with jQuery in it, all I see is a big mess flooded with dollar signs that do different things in different places. If the library had used meaningful names for the functions it offers it would be a lot easier to decipher other peoples code. Javascript is already difficult and unreadable as a language itself.
Personally I don't think it's adding that much functionality to account for the "namespace pollution", not to mention the possible confusion of people reading your code that aren't familiar with your method.
It's just saving a trivial couple of characters on each invocation of the method, so in that respect it can only be considered a form of syntactic sugar. And the cons outweigh the pros, in my opinion.
It would be good if you take a look at the construction of e.g. jQuery .
It does'nt work with several global variables/functions, there is only one global object required "jQuery" .
Everything else are properties of this one object, so they have minified naming-conflicts.
In the special case of $$ : maybe sometimes you need to work with prototypejs, but you cant, because prototypejs already uses $$.
So my suggestion: create one global object, your own "library" , give it a distinct name, and let your functions/variables be member of this object.
I don't think it's "evil" in general, but if you're going to pop something into the global namespace with a "distinguished" name it might be better if it were something a little more interesting. For your purposes, given your example code, the jQuery micro-template system would probably be a better approach anyway.
I want to know if there exists a tool to help in reversing a compressed javascript that has obscure variable names. I am not looking for a pretty-printing beautifier, but for a tool that actually knows how to change & propagate variable name choices.
Let me be more specific :
- some of the functions belong to the 'public' API and i want to impose readable argument names in their prototypes
- there are intermediary variables for document, window and other browser idioms
I would like to give this knowledge to the tool and then let it create another javascript where the knowledge would have been correctly propagated.
thanks
Jerome Wagner
Sounds like maybe you need a javascript refactoring tool. Something that could refactor javascript, i.e take a javascript file and rename variables.
Here are some plugins for IDE's:
http://www.brics.dk/jsrefactor/index.html
http://www.jetbrains.com/editors/javascript_editor.jsp?ide=idea#JavaScript%5Frefactoring
If you are trying to do this programatically, then this may not be the best solution for you.
I was looking at an answer to an SO question today where the variable names are ua, rv, etc. And I thought, "Man, when will people learn to use full-size variable names, memory is not a problem any more" but then, it is Javascript so it has to come across the wire and perhaps long variable names even slow down interpretation.
Is using short variable names in Javascript premature optimization?
While I'm here, are there any libraries for Rails or PHP that will compress Javscript on the fly, so I can keep my Javascript with long names on the server?
The only reason to use short variable names in JS is to save bytes over the wire. However, developing like that is ridiculous. Do they write JS without whitespace, too? There are tools which optimize finished JS. Crockford's is one of the most popular (though it does not shorten variable names). I can't recall offhand one that does obfuscate/shorten variable names, but they do exist and it's not that hard to write one, either. Google Closure is a very impressive JavaScript compiler that turns this:
var myFunction = function(arg1, arg2) {
var foo = getValue(arg2);
for(var count = 0; count < arg1.length; count++) {
alert(foo);
}
};
into this:
function a(b,c){var d=e(c);for(var f=0;f<b.length;f++){alert(d)}}
Dont use short variable names for optimization, during development. That would severely decrease readability. Compress your JS/CSS files at compile/deploy time, using something like YUI Compressor.
People use short variable names in javascript purely to save on bandwidth. It does not affect execution speed of the javascript. And I don't know about rails or PHP libraries, but there are certainly tools out there that can compress your javascript files (by renaming variables to be shorter and removing unnecessary whitespace).
We have not any reason to use not readable code at development.
As the other answers, I think you have a lot of resources to save bandwith and make happy the user with a fast load of the page.
Check these articles:
close-look-into-include-javascript-compression
Production-Grade-JS
I normal development, most of these answers are correct. There is no reason to use non-descriptive variable names.
However, when writing answers and examples on SO, variables don't necessarily mean anything in particular. They're just there for demonstration purposes, and have no need for any semantic meaning.