1. Know thy core tenets
Javascript can feel a little weird when coming from other server-side programming languages. In most newcomer’s opinion it is messy, verbose, and requires petty rules for things like semi-colons, curly brackets, etc; but I think it’s best to not try and compare Javascript to other languages you’re familiar with.
It’s an event driven language which is a little atypical from what you’re probably used to. Really most JS can be boiled down into these three things 1. the DOM selector 2. the event listener and 3. the method to be run when that event happens; those are the core tenets of JS.
2. Always use the same data types (stings, integers, etc)
Another complaint that people have about JS is that it doesn’t have many rules regarding data types. In a language like Ruby if you have something like this –
a = '10'
b = a + 20
puts b // no implicit conversion of Fixnum into String
you will get a quick error saying that essentially you can’t add an integer and a string together. This is usually preferred and is the whole “fail fast and fail loud” approach. The alternative in Javascript would look something like this –
var a = '10';
var b = a + 20;
console.log(b); // 1020
This could be very hard to diagnose in practice. I’ve probably spent hours tracking down where I went wrong only to find out I was incorrectly trying to add a string into an integer.
3. Understand the role of asynchronous functions
One thing you’re almost guaranteed to see more of coming from an environment like Rails is the use of asynchronous functions. These asynchronous functions, also known as AJAX, are crucial to the rise of Javascript in recent years, and they allow us to do great things with our web app to make it look and feel more like a desktop application.
AJAX can also be a source of pain when you originally start sprinkling it into your web app however. The pain point for most newcomers is understanding how it fits in with the normal order of operations. The short answer is – it doesn’t. When I initiate an AJAX call to create a new record in the database, for example, anything after the end of the AJAX function begins immediately without waiting for the AJAX call to return its results. Therefore its important to include anything thats relies on that returned data to be placed inside the AJAX function.
4. Settle on a convention and stay organized
Javascript is something I’ve jokingly referred to as the wild west. There are seemingly new frameworks added every day and it can be quite overwhelming https://goo.gl/TJpYNJ. Not only that but the language is pretty devoid of any set standard or convention when it comes to structuring your code and staying organized.
I’ve seen so many variations on JS coding styling and organization. Ultimately you will likely get to choose your own convention and they will likely change over time, but its important to try and stick to something. Javascript can get unwieldy real quick so a little organization will go a long way.
5. Get comfortable with Object-Oriented Javascript
If you decide to go with one of the new popular JS frameworks for your next project then this will likely be handled for you but if you do the go-it-alone approach I’d highly recommend learning Object-Oriented Javascript. Its not the easiest thing to throw on your plate when you are trying to learn JS at the start but as soon as your .js files routinely start reaching hundreds of lines of code its time to give it a look.
OOJS allows you to group like-minded logic into a series of methods that can be called from other methods and will go the furthest in helping you better organize your code. Many great tutorials will help you make the transition from a procedural style of JS to a more organized OOJS http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
6. Know your scope
One of the hardest pieces to grasp when switching to Object-Oriented Javascript is the use of “this” and understanding scope and how/when scope changes. This is one of the things that you just kind of get better with over time, its not terribly difficult to figure out. The key thing is that tools like “debugger;” and “console.log(this);” are your friend and will really help you when you’re confused.
Just remember that scope or “this” is going to be the most recent function() that was declared unless stated otherwise. If you want “this” to reference the main object and not the most recent AJAX call its not too difficult –
MyApp = {
sayHello: function() {
console.log('hello');
},
getPerson: function() {
var self = this;
$.ajax({
method: "GET",
url: "/myapp/get_person",
datatype: 'jsonp'
}).success(function(data){
self.sayHello();
// or
this.sayHello();
}.bind(this));
}
}
MyApp.sayHello();
Here we did two options for reassigning “this” to the scope of the main MyApp object, but you will only need one option not two. The first that I set “self = this” and called self instead of this, I’ve also seen “_this” before but its the same idea we are just assigning this to a variable that won’t be changed later on like “this” will. The other issue is to use “.bind(this)” which will override “this” from the ajax call with that of the main object. This approach is generally cleaner looking in my opinion but it also overwrites the other “this” which would be a problem if you needed both scopes.
7. Avoid cheap hacks like setTimeout
Running into your first asynchronous issue or something like an exponentially increasing event occurrence will surely drive you mad, but this is a good chance to break it down and truly learn the language and better understand why it works the way that it does.
Something like –
setTimeout(function() {
something();
}, 100);
is a tempting hack to deal with an asynchronous issue, but many times it is not dealing with the root cause of the problem and may actually fail when your internet speed or your app’s server is running slow.
Another common issue I see a lot with newcomers is attaching a new event listener to the same selector with every new click. This will produce an exponential number of methods run we each subsequent click. It is sometimes easy to hack your way around this problem when you’re not sure what’s going on but its way better to figure out the actual cause of the problem.
8. Leave the styling to CSS
This one is a bit of a pet peeve of mine. Generally I prefer to leave the styling to CSS and the animations / scripting / interactivity to JS. Sometimes a JS styling hack is unavoidable but I still see it used way more than it should be to handle the styling of a web app. It is a huge pain for another person to track down when they’re coming behind you to fix something.
9. Debugger is your friend
The entire Google Chrome developer tool kit is so vital in my day-to-day job, its so crucial that you learn it in my opinion (or an equivalent in another browser), and just learning how to stick a “console.log()” is not enough. Tools like “debugger;” and breakpoints are lifesavers and are really important when getting into Object-Oriented Javascript.
10. Always keep learning
The state of Javascript is always changing so its very important that you always stay learning. Perhaps just as, if not more, importantly is that you don’t go all in on every JS fad and learn to separate the facts from the hype. The JS framework landscape is changing at a rapid pace and you want to be weary on picking the next Betamax as a developer or a lemon of a car as an entrepreneur. It could easily end up costing you a lot of time and money.
Good luck and get really good at learning how to learn because it never stops.