Ask Slashdot: Making JavaScript Tolerable For a Dyed-in-the-Wool C/C++/Java Guy?
DocDyson writes "I'm a dyed-in-the-wool C/C++/Java developer with over 20 years of experience. I'm making a good living and having fun doing back-end Java work right now, but I strongly believe in being a generalist, so I'm finally trying to learn the HTML5/CSS3/JavaScript future of the Web. However, I find JavaScript's weak typing and dynamic nature difficult to adapt to because I'm so used to strongly-typed, compiled languages with lots of compile-time error-checking and help from the IDE. Does anyone out there who has made this transition have any tips in terms of the best tools and libraries to use to make JavaScript more palatable to us old-school developers?"
Probably gonna get flamed for this, but my advice.. don't fight it! When in Rome.. etc.
Javascript isn't meant to be done like c++ or Java, so don't try! Think about the mess you get when an assembly guy tries his hand at Java. It's the same deal. It's a whole different mindset, and if you fight it you'll just end up with a big mess and a lot of wasted time.
That said, some stuff does transfer over. You can still go through proper requirements, design and testing. Basic principles like encapsulation and reuse still sorta apply (and are highly recommended imo). Before doing anything that seems like a common use case, check to see if someone has already done it (but don't blindly use it.. a lot of really shitty stuff out there.. but some gems too!).
You could try a language that compiles to JS/etc.
My friend uses HaXe for all of his server development (http://haxe.org/doc/why).
Troll is not a replacement for I disagree.
try playing with javascriptmvc
I suggest reading this book, it's gotten a lot of good reviews, I've seen a lot of people recommend it to people starting out with JS.
It explains a subset of Javascript that's simple to use, and also the most used in practice.
My advice?
Scotch.
Lots and lots and lots of scotch.
Preferably something that burns horribly on the way down and leaves you with a miserable hang over. Only because you've got to look forward to something that hurts less than JS development at the end of the day.
Non impediti ratione cogitationus.
Most "old school" programmers have some interpreted language in their toolkit. People who think "old" means 40 probably have Python/Perl/etc. People who are really old probably had Basic/Awk/etc. So, nothing to do with how long you've been programming, more to do with how narrow your background is. As with learning any new language, there's no getting around the basic advice of: Write More Code.
Have you tried Dart? It's like JavaScript but with optional typing, and it compiles down to JavaScript.
This depends - are you looking to learn the new coding methods to remain competitive in the workplace, or just for fun?
Honestly if you make a living doing this then you need to adapt. You need to get over your preconceptions and accept the changes to the way computing works. There are millions of programmers out there, if you want to stay employed you need to show that you're adaptable to the new technologies while applying all of the tried-and-true knowledge and experience from your past. It's hard enough to get a job when you're more than a decade out of school.
Trust me, I understand where you're coming from. I hate the inefficiencies of the languages these days. I dislike the general idea of doing anything other than a script in a scripted language. However my (perhaps anachronistic) viewpoints don't have many applicable places anymore. Unfortunately the tradeoff between RAD and proper coding often leans a little too far to the RAD side, necessitating the use of many types of languages and tools that you will undoubtedly not enjoy.
Not only will you be a lot more productive, but you'll be a lot more marketable if you just succumb to the "dark side" that is today's trend in programming languages.
If God gave us curiosity
Vodka, tequila, whiskey, sake, etc. choose your poison or mix them up for extra "tolerability"
let go, my man... breath the untyped air.
Real tip: "use strict" at the top of your code and and write using assert() methods. A little more tedious, but your used to that, right? Being "dyed-in-the-wool" and all...
CS majors know the time/space tradeoff, but they never get taught the 3rd, crucial, tradeoff of the set: comprehension!
While it won't get you over the loosely typed nature of the language, it will make things a bit more manageable. You can write nice terse code which accomplishes oodles, as opposed to hand rolling everything. There is something nice to javascripting. I find it a nice respite. JQuery makes it beautiful.
Adapt to it anyway. Do it by trying harder. The language isn't going to adapt to you.
I have no particular love of Javascript, but when I work in it, I write Javascript. When I use Python, I write Python, not Java. When I use C++, I write C++, not C.
It's hard. It's annoying. But the idea is that you write the language like a "native". If you're really a generalist, it's not such a big deal. Read plenty of good Javascript to learn the idioms common to the language, and go from there.
I could write for loops using counters and statements terminating with semicolons in Python. But I don't. I use iterators, list comprehensions, and so on. Because that's how Python code is written.
The way I see it, the goal of learning a new language is the same whether it's a programming language or a spoken language - to be able to do useful things with it, and ideally come off as a native speaker. Look at it as a matter of pride.
I have developed a truly marvelous proof of this comment, which this signature is too narrow to contain.
Know the language well, sometimes you *want* wierd things to happen. But know the limitations. Also practice safe and defensive coding. Use facilities you have to minimize side effects. Test early and test often. BTW, both C and C++ can really bite you. So I find it odd this question is being asked. These habits should already have been developed. I've been there so I know.
putting the 'B' in LGBTQ+
...so give up on it.
Try search about Douglas Crockford, he has amazing talks at yui theater and developed tools like jslint and a debugger one.
I am also C++ guy and I really hate Javascript. It is not a language. It is a hack. Some programmer got drunk and designed it over the weekend just to make fun of his half-brained manager.
Javascript is a multiplatform piece of sh@#$.
Why bother making the transition? You're background sounds like mine - C, C++ then Java - and based on a few years of dealing wih Perl I'd never willingly use a weakly typed language. Many errors in statically typed languages can be caught by the compiler, static analysis tools or nowadays by the IDE. Whereas with crap like Perl, JavaScript or *spit* PHP, such tools are hindered by the language and often by the libraries to the point where you'll drown in warnings that may or not be of genuine concern. In short, your existing skills are in demand, so leave the crap languages to the script kids.
I'm a c++ / Java guy that has worked with dhtml for around 10 years. The answer is both simple and complicated. For the most part, as you have realized, JS is a very dumbed down Java like language. It is about as strict as PHP (not as forgiving), and you can easily get going in the wrong direction trying to do seemingly simple things (like, getting the value of a select box). For the most part you can fake OO and more or less port over best practices from it's stricter big brother. I more often than not attempt to take the same approaches for JS as I would Java (albeit, it is not always possible or correct in the ways you are used to). Obviously you are not going to be setting up abstract classes or casting complex integers, but the pragmatics of programming are non-the-less the same. In fact, as a simple scripting mechanism over the dom, you shouldn't have to do any complicated data structure work (this is what the back end if for). So, the simple answer is to keep it simple, the complex answer is to attempt to follow best practices and use as little javascript as possible to achieve the desired effect. Just be glad you are not learning this 5-10 years ago, you would be spending half your time testing between browsers and the other half making your JS code look hideous.
First, get thee Aptana for development.
Second, download thee jQuery. I would also recommend jQuery Mobile and jQuery.tools.
Third, dig around in jquery until you find qunit for unit testing.
Fourth, do a refresher on Lisp and functional languages. They say that javascript got it's fathers curly braces and it's mothers lexical scope. It may *look* like C/C++/Java, but under the hood is ActionScript ala Scheme ala Lisp. And it a very real difference which gets played out in copious usage of events and callback functions. As a refresher, the HTML5 paradigm is basically an MVC paradigm, where HTML is handling the Model, CSS is handling the View, and Javascript is handling all the controller functions. Phrased differently, the HTML is describing the What is displayed; CSS is describing How it should be displayed, and Javascript is describing When it should be displayed. And the When gets implemented as callbacks and events. And it just so happens that functional languages are ideally suited for that kind of work (ala lambda calculus, etc).
Lastly, if you're brave, check out Node.js.
My preference is vodka and lime...
Lime cancels out the harshness of the vodka, vodka cancels out the sourness of the lime, and the alcohol dulls the soul crushing pain of javascript.
Use good stuff for the first glass or two (grey goose is my preference).. then use the shitty stuff for the rest of the evening if you are cheap (polar ice is great for this!).
Use GWT. It generates Javascript from Java.
It's an attempt to make Javascript more Java-like. To be honest, I've only scanned the docs and haven't used it yet, but plan to.
If anyone has some real-world experience they'd like to share, I'd love to hear about it.
http://echo.nextapp.com/site/corejs
The day I trust others to write code better than me is the day my work becomes just good enough. There is not a lot of vertical mobility writing good enough code.
JavaScript can do amazing things, but it's a total disaster if you're coming from a more traditionalist background.
Let me give you a taste of what's to come for you :).
Let's say you have an Applet/ActiveX Control/Plugin of some type that your company has built and needs to be scriptable from JS, and it must also be able to call into JS (JavaScript devs can register for events, notifications, console/logging messages, et cetera...)
You add a new feature to your Company's doohickey. Now you need to test it properly.
Your customer set requires that you need to test on OSX Snow Leopard, OSX Lion, Windows XP, Vista, Win 7, OpenSUSE, Redhat, and Ubuntu. On each of these operating systems you need to test on the most popular browsers, so you get jiggy with Safari, Firefox, Opera, IE7, IE8, IE9, Konquerer, et cetera... Then you, depending upon the plugin's architecture, need to test on both 32-bit and 64-bit versions of the plugin in each browser on each operating system.
That's not even getting started with Mobile, or JRE versions, or different deployment types, code signing, et cetera, ad nauseum, ad infinitum.
If you think you don't need to test like that, you're in for a rude awakening my friend... For example, this very testing led to our discovering that in Firefox, on Windows 7 rapid LiveConnect usage between an Applet and JavaScript is perfectly fine if the applet has focus, or another windows has focus, but causes total freezing of Firefox/Java Plugin IF THE FOCUS GOES TO ANOTHER ELEMENT ON THE SAME WEB PAGE. How's that for crazy sh**? :) LOL.
Anyhow.
Browser application development is a nightmare.
I would pay good money for them to rip JavaScript out and everyone get together (yeah, I know, pipe dream) and come up with a client side scripting language that rocked oldSk00l.
Loading...
If you wanted to learn dynamic typing from Java, why not try Groovy
Write in Java, compile to JavaScript using GWT.
JavaScript "features" (weak typing, undeclared variables, ...) cause only bugs.
My advice is;
Learn perl, learn to love perl.
After this any programming language will seem tolerable to you.
In fact, you may consider them as yet another of the many possible ways to do it.
If my comment didn't sound as good in your head as it did in mine, then I guess we all know who's to blame
I think GWT is actually a reasonable tool for writing code that compiles to Javascript. This makes a lot of sense if you're writing your server code in Java, since your server and client code can all live within the same source tree and be edited with the same IDE in the same language. Significantly, this also allows you to debug your code using your Java debugger (read up on 'hosted mode' if you want to understand that witchcraft) while it's running in your browser. GWT also de-fangs the javascript event model that often leads to memory leaks. It might be of benefit to some people that by default (you can turn it off) the emitted JS code is heavily obfuscated. GWT is mature and well-supported, and integrates simply with vanilla JS code if you wish to.
Available for GWT is GWTQuery, which is (you've probably guessed) a jQuery clone for GWT, including events, effects, etc...
The Dojo Toolkit definitely makes javascript feel a little more friendly.
You can write in a type-ified version of javascript with a 'compiler' which statically checks your types and creates a minified javascript 'binary' for you to serve:
http://code.google.com/closure/compiler/
http://www.amazon.com/Closure-Definitive-Guide-Michael-Bolin/dp/1449381871
Or you can use GWT, and write java which compiles to javascript:
http://code.google.com/webtoolkit/
Or if you want to be on the cutting edge you can try DART, which is a whole new language, which compiles to javascript.
http://www.dartlang.org/
My tip is to never let yourself remain attached to a particular subset of languages for 20 years. Absorb all crazy things, because it makes you better in all languages.
Try LISP sometime.
There are many tool kits like jQuery which have zillions of plug-ins that already do most of the bread and butter functionality you'll ever need. There's little point in cutting javascript yourself for most things, not unless you're a professional in the language and need to.
I'm just going the other way. Building my first app in C++ using Qt. Which basically goes like this: OMG you piped a literal string without it being a genuine QString into my label ... KERNEL PANIC! CRASH! 10 bazillion compiler errors. ... WTF?
Of course this sucks. However I'm well seasoned enough to know that when building a non-trivial application, it's exactly this sort of thing that will save my sanity in the long run.
With dynamically typed languages it's the exact opposite. Try building an IDE in JS. It has been done, but it need a solid amount of thorough planning and the one or other hack/stunt. However, writing a little script in JS is like having awesome sex compared to doing the same 'three-liner' in C++ which is like masturbating with a cheese grater in comparison. And still uses 30 lines.
All I can say is go with the flow. Wrap your head around dyn typing if you are not used to thinking in it and eventually you'll see the beauty in JS which blows C++ out of the water in the areas it is meant for.
Keep up with the spirit and good luck. ... And now excuse me, I have to set up my little QWidget 20-something lines of code with 20 typecasts strewn about just to get the bloody label to show a simple literal when I click a menu entry.
My 2 cents.
We suffer more in our imagination than in reality. - Seneca
http://code.google.com/closure/compiler/ It's exactly what you're looking for. It does type checking, it checks syntax and variable reference, it does file dependancy, and has a great inheritance system so you can get back to your Java/C++ ways. It's just awesome.
Firebug is a great tool for working with JS in all situations.
Dynamic languages have different strengths and weaknesses than static languages. The best advice I can give you is: deal with it.
Best practice in a dynamic language includes automated unit tests for your code, for example. I don't use JavaScript so I can't tell you all the best practices and developer idioms for JavaScript, but I have heard that the best book is the O'Reilly reference book and that anything by Crockford is worth reading.
Note that lots of other Slashdotters are already giving you very similar advice to what I wrote.
P.S. Hmm, doing a Google search for "JavaScript best practices" found this: http://www.javascripttoolbox.com/bestpractices/
steveha
lf(1): it's like ls(1) but sorts filenames by extension, tersely
Javascript is not perfect but more importantly, it's not OOP. Forget OOP, see it for what it actually is and it turns into a pretty decent little languange actually. If you are a C++/Java head that is hard to do but just the act of seeing code as prototypes, without the OO paradigm, is a worthy exercise. You gain a cool way to view problems and it changes the way you code OOP to boot. ++ imho.
Nan-in, a Japanese master during the Meiji era (1868-1912), received a university professor who came to inquire about Zen.
Nan-in served tea. He poured his visitor's cup full, and then kept on pouring.
The professor watched the overflow until he no longer could restrain himself. "It is overfull. No more will go in!"
"Like this cup," Nan-in said, "you are full of your own opinions and speculations. How can I show you Zen unless you first empty your cup?"
You're right, Javascript is a way different style of coding than C/C++/Java, but that's OK. So is Lisp. Surely you wouldn't feel wounded by having to learn Lisp. Use the different style to develop a new facet to your perspective on programming. Duck typing is pretty well respected in academic OOP, so it's not like you're going to be learning GOTO statements or anything.
Debugging is a bit harder, but that's OK, fire up Firefox, go to "Tools >> Web Developer >> Web Console." That'll give you most of what you're looking for (use console.log("message") to write to the console). You can check out Firebug also, if you want something a bit heavier. I personally ditched Firebug as soon as Firefox's Web Console got good enough, because I found Firebug a bit too clunky, but lots of people swear by it.
Leave the preconceptions and stereotypes behind, check out Wikipedia on Duck Typing and give it a go. Don't sweat it when you make noob mistakes -- you're supposed to do that when you're a noob to a language. Give it a crack, have fun with it, relax, it's really not a bad language once you get into it.
Stop-Prism.org: Opt Out of Surveillance
Learn Perl first. Or maybe LISP. That way you'll get rid of the statically-typed mindset. :)
Java/ECMAscript is Perl/Python in C++/Java clothes. Don't even think about C++ or Java. It doesn't work that way.
thegodmovie.com - watch it
Take a look at Sencha / ExtJS... It's aimed squarely at enterprise-level developers/engineers, not the script-kiddies that rant and rave about the cool shit they can do because they've overwritten a 'built-in' type. It should work with Google Closure, as well...
IDEs are in terrible shape. There's WebStorm and Aptana... neither of which hold a candle to what you're used to, but it's better than notepad/textmate. I'm an linux/eclipse guy, but can't get used to the ways that Aptana breaks shit, so I tend to jump back and forth between WebStorm and SublimeText (it looks nice, but it's not 'all there').
There are some good books out there, JS: The Good Parts, Eloquent Javascript (free)... and I'm starting on Test-Driven Javascript Development, though I can't say if it's any good yet...
I'd recommend doing a little bit on the side, get your feet wet, but don't commit yet. Thinks have changed a lot in the last year or two, and nearly everyone and their dog is becoming an HTML5/JS Dev. You're behind the curve already, and will have a hard time getting ahead, so I'd wait until the editors and browser compatibility is better before diving in.... don't ignore it, and if you can find someone who will pay you to torture yourself, do it... but don't be too anxious.
Dynamic languages actually have strict, static rules behind them which implement their dynamic features. If you learn those rules then you may be in more familiar territory. Weak typing is really just a list of rules for automatic type conversion.
I'm a C++ guy and here's how I got conversant with Javascript:
1) Get "Javascript: The Definitive Guide", by Flanagan, published by O'Reilly.
2) Read the chapters on Objects, Functions, Classes and Constructors.
3) Wrap your head around closures.
4) Understand the concept of function prototypes.
It's different than strongly typed languages. Just about everything is an "object" in Javascript. Including functions. Learn the subtle difference between defining and declaring a function - and it's nothing like what that means in C++.
Take from C++ the concept that you can have objects which have methods and properties. Then open your mind and read those chapters I mentioned. And don't try to apply any more C++/strongly-typed preconceptions. The "Definitive Guide" was not pleasure reading. It's not informal and humorous. It's dense. And it's geared towards those with some programming experience. But read those chapters and I think you'll be most effectively able to leverage your experience with strongly typed languages into Javascript.
I think Javascript is great and it is object oriented so you can get jiggy with it.
Also - give yourself an assignment with it and start hacking away.
I have 20 years of C under my belt, 15 of those paid. I currently spend the vast majority of my time writing JS, and I love it.
Back in the good old days, we didn't pick C because of it's great syntax, or the warnings from the compilers (which have gotten much better in the last 20 years!). We picked it because it fast, portable (enough), available, and you could use it to do the stuff we were interested in.
Well, times have changed. JS and CPUs are now fast enough that execution time is not were "fast" usually matters: *developer* time is. JS syntax is good enough. Runtime warnings are getting good enough if you're writing ES5 strict code. Most importantly, if you're writing code for the web, you pretty much have to pick JavaScript. (Just like writing X11 code 15 years ago pretty much meant C++).
Syntax -- "go with the flow, my man". It's juicy, delicious. Don't be limited by the lack of types: embrace the flexibility. Prototypal inheritance is awesome in its simplicity, shallow object hierarchies make for easy reasoning. Make you *get* closures.
Functions are first-class members, like strings and arrays and objects. Sure, their literal syntax is longer than "", [] or {}, but function(){} is still a literal.
Just as the developer who thinks GNU make is some kind of super-shell is doomed to failure, so will the developer who thinks JS is a variation of something else.
JS isn't the new C. It's not the new Java. Or C++. Or Scheme. Or Perl. Or Python. Or Logo. Or BASIC. It's JS.
I currently write a LOT of day-to-day mundane code in JS. Some exciting code, too. I write web pages, validate forms, load modules (CommonJS), and design object exchange protocols and the applications which use them. That's on the web browser.
On the web server, I'm using it kinda like 1995's PERL. I query databases, do CGIs. I can call into POSIX. I write daemons, and "shell scripts". Some week I'll spend a few days and make my CGIs faster than CGIs. Remember mod_perl? Same deal. Mast fast_cgi. I dunno, performance metrics say I don't need to quite yet.
It's a hell of a language. But if you really want to work with it, you have to "get it". Be comfortable with it's multi-faceted layer. Understand that it's "functional", "object oriented", and "imperative", all at the same time.
In C, the Zen boils down to "everything is just a number". That's why string operations are so easy in C once you "get it". In C, the Zen boils down "everything is just a jsval". So, it's IS typed -- everything is the same variadic type. Get over writing reams of code to make your little soldiers walk the goose step, and just tell them where to go. They'll get there.
Do daemons dream of electric sleep()?
If you *really* want to learn the screwball, loosey-goosey mess that is Javascript/HTML/CSS, then you just need to dive it and embrace the chaos. If you just want to be able to write web apps while leveraging your back-end Java skills, then check out frameworks like Vaadin.
Javascript is a powerful complement to PHP, databases and server-based functionality. To do AJAX for example, you have to create the XMLHttpRequest object - created in Javacript in the browser - to send data to the server. And the browser is a very powerful engine. It should be exploited. It can pick up some of the server processing. I hear what you're saying about your code being totally exposed, but you can always keep the proprietary stuff on the server and send down the HTML only in those cases.
This is book is worth every penny and more (~$18 on amazon).
,closures, etc.)
Like the submitter, I come from C/C++/Java background and always despised Javascript whenever I had to deal with it. I picked up this book a few months ago and can confidently say that this book completely changed my view of Javascript. Javascript is a quirky language, and has some really bad parts (the book has a chapter dedicated to the bad parts). This book clearly explains common misconceptions about the language, as well as all the things a programmer used to a more traditional language needs to look out for. The book explains how Javascript works under the hood in great detail (the prototype-chain, functional scope, type conversion and equality, first class objects/functions
This is a book for programmers, it's not a cookbook or how-to, and you need a good understanding of programming for it to be useful. That being said, for programmers coming from more traditional languages to Javascript, this book is exactly what you're looking for. I can honestly say that in a few short months Javascript has gone from one of my most hated languages to one of my favourites. The language is incredibly powerful and expressive once you get a good understanding of how it works and why.
I'm an old timer like you. I made the jump about 2 years ago and I have to admit the jump was difficult at first because I kept trying to fight it. What! You don't know until you run you script and it doesn't work that you have a typo? How weird. Once you get over this you realize, hey, this is kind of cool, I can go into a web browser and it tells me what is wrong, much more so than the c/c++ compiler ever did.
My recommendations:
use http://www.w3schools.com/ as your go to website for reference.
Get used to both Chrome's development tools as well as Firebug in Firefox. You debugger is your browser tools, not an ide.
Learn jQuery, even if you think you don't need it you WILL use it if you get seriously into javascript.
There are several patterns that simulate data encapsulation, google it and read about them.
Closure is your friend. It is a very weird concept but once you use it you can't live without it because it allows encapsulation.
If you are curious how something is done on a website, right click on it select "Inspect Element" in chrome or FF, go to the script tab and look at the source, this was weird to me, hey all your source is available to look at. If the source is minimized ie9 will even unminimize it for you.
Your ide is nothing more than a text editor, not better than vi, notepad, you pick, though eclipse/Netbeans/DevStudio all give you things like code completion.
After my 2 years of working with javascript, I can honestly say it is kind of fun and maybe even rewarding...Do I miss the tough technical problems from C/C++, of course but you know what javascript gives you a whole new set of problems (my favorite is tracking down things where an if statement doesn't work because it is comparing a string instead of a number and doesn't tell you, so 3 == 3 will return false).
GWT lets you write your front end in Java using widgets. It compiles your code to Javascript taking care of any variations needed to work on the different browsers.
You install the GWT plugin to your browser, and whamo, you can trace through your front end code in eclipse, without needing to redeploy changes to the server. Beautiful!
I replaced a JSF/Facelets/RichFaces/JavaScript/AJAX/HTML/XML/CSS implementation with GWT and saw a massive performance increase coupled with humongous decrease in complexity.
I honestly feel sorry for any poor sucker stuck in AJAX/JavaScript/CSS/HTML hell. Let Google take care of browser compatibility problems and get to use Java on both the front and back ends. What more do you want?
If you're an "old school developer" you use vi, in a telnet window. You don't get 'help' from an IDE.
I want to delete my account but Slashdot doesn't allow it.
for (x=0; x lessthan 10; x++) //sorry, can do lt in comment
{
square[x] = x*x;
}
That's a for loop, while this:
square = [x*x for x in range(10)]
is a list comprehension in Python.
You can write it like a for loop - and I did when I was first learning Python - but it sucks to do that. This is probably what the GP was alluding to. If you really know a language you don't want to read crap written by people who think they're all the same with different syntax. This of course is but a single small example.
A language is not evil because it isn't strongly typed. Just because a language offers that option doesn't mean that you have to use it though. There are a lot of things that languages offer that aren't the best tool in all cases. This is where coding standards come in really helpful :)
That being said, I think that these could help you out:
JavaScript has been around for a long time and has lots of books and articles written. This is a huge benefit. I personally think that JavaScript Patterns by Stoyan Stefanov is a good quick read to show you how to implement popular design patterns in JavaScript. A deeper discussion can be found in his book Object-Oriented JavaScript.
jQuery is the answer to everything.
Yes, that is what Java script code looks like.
slashdot troll = you make a compelling argument I do not like the implications of.
I never really understood the objection to loosely-typed or untyped languages. I go back and forth between C/C++ and PHP and Javascript all the time, and it never even phased me.
The key to dealing with untyped languages is to focus not on what you have, but what you need. If you absolutely have to have an integer, not a string carrying a series of numbers, make it an integer and use it. If you need a string and a number won't do, make it a string. Stop focusing on the correctness of the typing and just focus on what you need at that particular point in the code.
By the same token, this is identical to the advice I give to beginning programmers struggling with C pointers. Stop focusing on Lvalue / Rvalue and just focus on what you have and what you need. If you have a pointer and you need the value, prefix with an asterisk. If you have a value and you need a pointer, put an ampersand in front of it. It's really that simple.
People who say "sheeple" have about as much sophistication as an AOL user, and in fact are probably actually AOL users.
Javascript is a complete clusterfuck. Its dead zombie hand is dragging down the whole web.
Stay away! Keep to languages where it's actually possible to write good code.
Or get your brain removed and join the rest of the morons drowning the world in ever more stupid broken javascript code.
I am not sure if anyone on the thread has mentioned node.js (some folks here can probably explain this better than me) , but node.js is an incredible hybrid of a robust python-esque interpreter with the syntax of JavaScript. Node.js's primary use is for networked computing. However, If you want to practice learning JavaScript, it will be a lot of fun hacking within node.js since it allows you to do so much more stuff outside the browser.
Brendan Eich: Hey, I added a nifty new scripting language to Netscape!
Marc Andreessen: You mean you implemented Java natively in the browser?
Brendan Eich: No, That didn't work out. I had to scrap that idea.
Marc Andreessen: What, Java Scrapped?
The latest ECMAScript standard includes the 'use strict' pragma, which is one step towards what you're looking for.
Also, I was playing with Visual Studio 11 Express preview and it includes some decent code completion for JavaScript, which maybe fulfills some of your IDE stuff; though admittedly I haven't put it through its paces to see how well it does JavaScript code completion. Eclipse for JavaScript developers might do the same, I honestly haven't used it in a while for JavaScript writing. (I still prefer Vi for coding, versus an IDE, fyi).
Use the tools in Chrome or Firebug for Firefox to help with debugging.
You won't find the same advantages of compile-time error checking that you currently have but it also forces you to become more disciplined about thinking through your code and test cases when writing JavaScript. Obviously, the tradeoff is that if you don't test for it you won't find the error until someone finds it in the live environment.
Others have pointed out jQuery and I'll echo that. However, if you're like me you'll want to learn some of the underlying bits or the "why" something works and then augmenting with jQuery and other libraries. You'll want jQuery for most of the frontend work that you do.
And finally, I can't talk JavaScript without shamelessly plugging my book, JavaScript Step by Step.
Steve
For me, the best practice I find is to have a demarcation between your code, and whatever language/libraries you are interfacing with. Understand the contracts of your own code and make sure nothing that passes through the border violates the contracts. That way, within your own code, you can assume certain type information will always hold true. I find it works whether the program's type system is formal or informal*.
* I prefer to use the formal/informal distinction for type systems instead of static/dynamic, because if you think about it, "static" and "dynamic" is actually about the implementation of the type system, whereas "formal" and "informal" tells you the class the rules of type conformance in a language are: whether something is spec'd out in advance (which is possible in static or dynamic languages), or if there is some delayed type comparison calculation (which is also possible in both static or dynamic languages).
Those who do not learn from commit history are doomed to regress it.
Stop building narratives like "I'm an X type of guy trying to do Y." That's bound to increase your frustration with what are most likely going to be the normal road bumps in learning to do things differently. Think "different tools and methods for different jobs."
Instead of asking "how do I make working in toy language like Javascript tolerable for *real* programmer like me," you should be asking "how do the very best Javascript programmers do what they do?"
And don't think of yourself as "dyed in the wool" anything. Think of yourself as a versatile person who likes learning about new ways of doing things, because you've got a *lot* more to learn than just the Javascript *language* if you want to actually *use* Javascript. You've got to learn about DOM and CSS and HTTP and web application architecture and security. Once you learn about those things and learn how to actually do something useful with Javascript, you'll be in a much better position to make an *informed* critique the design of the language, popular libraries and frameworks like JQuery, and common Javascript idioms. It makes no sense to approach mastering the whole Javascript ecosystem with preconceived notions about its shortcomings. You aren't qualified to judge yet.
Learning a new kind of tool means learning new kinds of skills and strategies. Some aspects of the tool will seem like major problems with the tool until those good habits become second nature. For example novice Java programmers tend to create code that allocates unnecessary strings inside loops, when they should be using a StringBuilder. The result is the programmer thinks that it's Java that's slow, when it's really their ignorance of efficient Java programming idioms that's to blame.
Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
Your post reads a lot like all those people who hate PHP. "It has all these things wrong with it!" Well, actually, no it doesn't - because most of them aren't a problem to the people busy using it effectively. JavaScript doesn't have 'inferior' abstractions: it has *different* ones.
I have programmed a lot over the decades in both strongly typed and weakly typed languages - too many to name. I've come to Java in the last few years after a much longer time in JavaScript and PHP (and others) and have experienced the reverse of the OP's problem. But it's only a problem if you let it be a problem. Solving problems in an untyped language has some fundamental differences to a typed language. Get over that and a lot of the perceived 'problems' Just Go Away.
While it doesn't have the prettiest of built in widgets, the real power of Dojo is as a framework, namely the widget framework. It get's you thinking of your javascript as components and adds a certain sense of object oriented-ness to javascript. Additionally, a framework like dojo will offer various functions for common operations (like cloning nodes, dynamically adding to the DOM) easier by abstracting out the cross-browser complexities. As a server side Java developer a toolkit like Dojo has actually made me look forward and enjoy writing Javascript.
It's called Google Web Toolkit.
... And now excuse me, I have to set up my little QWidget 20-something lines of code with 20 typecasts strewn about just to get the bloody label to show a simple literal when I click a menu entry.
You're doing it wrong
http://stackoverflow.com/questions/1814189/how-to-change-string-into-qstring
I'll probably get nailed for this but... Sorry, unless you're re a slack programmer who needs the language and editor to make up for your lack of discipline, you should be able to program well regardless. You profess to be an experienced C programmer, but complain about weak typing and the need for lots of compile-time checking and help from the IDE. What C compiler have you been using? I'm sure people can write novels about the crap you can get away with in C. Back in college (1980s), the K&R C compiler on the BSD/VAX system let me cast on the left of the equals sign. As for compile-time error-checking and IDE, I used (and still use) Emacs. Stop your whining and start using your brain.
It must have been something you assimilated. . . .
I have a similar background. More Java then c however. The one thing that makes JavaScript semi readable and maintainable across people and time, is a good framework like jQuery.
Please get off the intarwebs... your clear and concise explanations of matters is undesired here in this wretched hives of memes and flamewars.
Seriously though, you're totally right. It's different. It's not inferior, it's different.
People who complain about this or that language being a piece of crap because of X and Y, are usually deadset in one particular mode of thinking, and cannot adapt. The question the original author should have been asking was not "how can I make this tolerable", but rather, "how can I best learn the correct way to use this tool?"
To put things in perspective, I was already doing a lot of crazy command-line parsing before I ever started using C. And when I started using C, I was upset, because I knew what I wanted to do, and I could easily accomplish it in BASIC, but C was different. The whole paradigm was new to me, and I had to learn to adapt. I haven't forgotten that, and I try to keep myself from becoming entrenched in any particular mode of thinking... it leads to inflexibly dictating that all else is inferior.
WARNING! This girl exceeds the MAXIMUM SAFE standards established by the FDA for BRATTINESS
My latest endeavor with JS made me very upset. JS does not do integer arithmetic well. Example to do a proper integer addition that is reliable I have to do the following: a + b | 0 or it could end up with decimal values. It wasted several hour of my time to find that one out.
I go out of my way to complicate the simple things, so that I can simplify the complicated things.
Start here
http://addyosmani.com/blog/short-musings-on-javascript-mv-tech-stacks/
Then go here
http://dailyjs.com/2010/02/18/framework/
And continue reading
http://dailyjs.com/tags.html#lmaf
Then read up on AMD and CommonJS along with RequireJS and Node (server side JS).
You will want to understand JSON intimately.
You can't avoid Jquery but its no longer essential with Underscore and Backbone libraries.
Dojo and ExtJs are also interesting.
There is a History of JavaScript series on DailyJS as well that will prove useful.
Good luck.
A fool throws a stone into a well and a thousand sages can not remove it.
the gwt compiler compiles java into javascript.
Work in Eclipse? Compile to JavaScript? Deploy wherever?
Oh the humanity....
As someone whom has spent several months with perl, and some time with javascript, perl provides large amount of power/terseness, if you can handle the complexity of the entire perl language, which is VERY challenging to do.
As for javascript, it does not offer the power of perl, and it is still unfriendly. I do not like javascript.
Javascript has closures and none of the other languages have them, sorry buddy, Javascript has superior abstractions.
Slashdot is proof that Sturgeon's Law applies to mankind.
I used to do a lot of Perl development but now-a-days I am doing heavy JavaScript work. My advice for someone starting out is that, initially, avoid libraries like jQuery until you get a good understanding of core JavaScript functionality. As a for instance, learn about how JavaScript prototype inheritance works (not the Prototype library, but the property). Also learn about closures as they are very powerful when used correctly. The following is a good article about the inheritance in JavaScript:
http://phrogz.net/js/c lasses/OOPinJS2.html
Chrome, Firefox, and even IE8/IE9 now have a JavaScript console that you can log to, this makes debugging worlds easier than it used to be back in the old days. Also, Firebug in Firefox and the built in debugging tools in Chrome/Safari/Webkit are very nice debugging tools that can be used to easily step through code and see what is going on.
Once you get used to debugging and some of the advanced features of JavaScript, then I would recommend starting to get familiar with a library such as jQuery or Dojo. If you know what the core of JavaScript does well, then you will know when to leverage a library method or a native method (because sometimes doing things the native way is faster). If you start doing jQuery, I would suggest reading an article about how to write it cleanly. jQuery is a nice library, but in the wrong hands can make for some very ugly code.
I used to really dislike JavaScript, but now that I have gotten to know the language well, it really is a nice little scripting language. I sometimes feel it gets a bad wrap.
you want google web toolkit. it will allow you to stay in the shit world of single-inheritance java that you are used to dealing with, as well as give you a decent widget toolkit to work with. when you wake up from the insanity of fighting with java, and are happy to program in a decent compact language like python, there's always pyjamas. the advantage of taking this route is that the widget set API of pyjamas is near-identical to that of GWT 1.5, with bits of 1.6 and 1.7 thrown in.
Java has better closures. Clunky, sure, but not broken.
Scala has better closures. Closures you can love.
Haskell has total awesomeness oozing out of its handling of closures.
Javascript is retarded in all ways. It's just flabbergasting that anyone defends it.
As a C++ guy who moved to Python, the best advice I can give is: Unit tests are your type checker, compiler, and then some. You will thank me later when you decide to refactor a large code base.
Writing any code more than 1000 lines in a dynamically typed language, without tests, is pretty much shooting yourself in the foot.
Finally, fall back to your common CS abstractions. The data structures are the same (lists, maps, structs, etc). It's still imperative code for the most part. The only thing to really 'learn' is the code-is-data mindset.
http://jsclass.jcoglan.com/
somebody beat me to the perfect opening line, but I'll use it again anyway..
I'll probably get flamed for this, but, don't even try!
That is, don't look at it as a transition. They are not used for the same things. Javascript is interesting yes from the perspective of just learning something different from what you are used to. I personally love learning new languages even if I don't ever use them.
I would recommend you play around with it, check out some of the libraries like jQuery or Prototype which make Javascript much more fun. But don't think you're going to transition away from Java any time soon, or at all. My recommendation? As a web guy originally (well, C and Assembly really, but web professionally) who's moving towards Java, I would say look into mobile app development on android. I have quite more enjoyed Java and Android dev than I ever did Javascript. But maybe I'm just too nostalgic for my Amiga C programming days..
-- Senior Software Engineer, Attorney appearance services, locallawyerapp.com.
JQuery and a REPL.
One of the things you really miss with JavaScript is a compiler. Something to check your entire program for obvious errors. That's where unit tests come in. If you have Significant unit test coverage, you can run your unit tests instead of running your compiler. Unit tests nearly double in value (IMO) when used with a dynamic language that has no compiler.
using the Wt C++ Web Toolkit.
Javascript has closures and none of the other languages have them
All mainstream languages except for Java have lambdas/closures (and Java is getting them in the upcoming release).
For that matter, most languages that do have lambdas, provide syntax for them that is considerably less verbose than that of JS - which makes a lot of sense when you actually start using lambdas heavily. To give an example with fold used to sum a sequence (assuming fold is a member function in all cases, for the sake of uniformity, and ignoring the ability to treat operator itself as a binary function in languages that support it):
I HATE ExtJS. Yet another chance for some fail offshort dev to put together something that works, but terribly.
The dynamic typing is what bothers you? I mean, I would have complained about the DOM, or the fucked up object model, or the fact that there's no good way to debug it, or the fact that you have to write 4 different versions of your program just to cover the major browsers even when you're fully taking advantage of things like jquery that are supposed to be browser-agnostic..
Since it is weakly typed, Javascript can be very difficult to debug, in areas deep in your code. You can ease your transition by writing unit tests for all your Javascript code. Get comfortable with a Javascript unit testing framework, and write tests first. Then, when you are debugging problems in your tests, you will be training yourself to recognize the common problems that occur in Javascript code.
I'll agree with the parent; although, I've not read that book. Generally a book written for somebody of a particular background more useful.
Similar background for me (but 15 years ago;) although, if you have discipline and comment your code the typing issues are not a problem. I'm spoiled now; I like prefer javascript (if it only had named parameters...) If you like inheritance you will not be so happy and the performance loss from overusing the prototype system. If you are doing some major work that requires accessibility you can't. In some ways javascript reminds me more of Perl...
I recommend NOT using jQuery or most libraries. If you are just looking to expand don't attach yourself to a library that may fall out of favor when you need to do serious work later (and something else is popular.) Most these libraries are ways to hack pathetic browsers like IE6 which replace the API with different one - meaning you are not learning the standards. Not to mention javascript is used outside the browser. You can find a document.getElementBySelector() library out there and use that until DOM3 finally adds that officially (why it didn't make it to DOM2 I'd like to know!)
No need to learn browser related hacks; unless you have to deal with the problem today; in which case a library of hacks may be useful, possibly just for finding the 1 hack you need in the source code.
Democracy Now! - uncensored, anti-establishment news
This man has done more for my understanding of JavaScript than anyone else. My abilities took a huge leap after reading his clear and deep explanations that get to the heart of JavaScript's design:
Douglas Crockford's JavaScript articles
He covers prototypical inheritence, classical inheritence, how to create private members, closures, engine performance, and other widely misunderstood aspects of javascript. HIGHLY recommended.
LS
There is a fine line between being a cultivated citizen and being someone else's crop. - A. J. Patrick Liszkie
I clicked on this story thinking "this should be great, I'll get to see the state of the art in Javascript IDE support".
Imagine my horror when I had to wade through pages and pages of language war, before I found your educational post. I'm downloading Aptana to check out now, thanks.
P.S. for those wondering there is a Mac version. The main screenshot looks awfully "Windows" so I wasn't sure they supported the Mac.
Also the hint on reading up on Lisp is very good. I've been doing JavaScript off and on for some time, just looking for a better IDE...
"There is more worth loving than we have strength to love." - Brian Jay Stanley
I've been coding for 25+ years. I've coded in many languages from assembly to java to C#, etc, but HTML and Javascript are my bread and butter. I've been coding Javascript for 15 years. It is the best (really the only) language for running code inside a web browser, and web browsers are ubiquitous - and that is a good thing when trying to get people to run your software. It's a good thing to learn, and you should feel good about your decision to learn it.
Here are some tips I can give you from my 15 years of experince with Javascript.
First, about static / dynamic typed variables. I've never really had a bug in maybe 14 out of 15 years of coding Javascript that was caused by a problem with the wrong variable type. That isn't to say that I'm not sometimes being dumb when concatenating a few things together, but I wouldn't really call it a bug - it's part of programming any language. You might expect a compiler to throw an error if you have the wrong type, and it will when the code runs - which is every time you refresh your browser if you are executing the code you are writing. You should be refreshing and testing the code OFTEN while writing it, in some environments you could have the browser refresh and run the new code every time you hit save if you like. I sometimes code directly inside the browser and run code as often as I like, if there's a problem it's very easy to find and fix.
But, your variables aren't likely to spontaneously switch to a type you can't deal with in your code. It just never happens that I expect a number and get a string, especially when I'm coding algorithms that don't rely on dynamic typing or concatenating strings and numbers, which is practically 100% likely when coding algorithms. If you are writing encryption code or something complex that uses a lot of math, you won't run into a problem with dynamic typing. You just will not. If you do then you really should reevaluate your coding standards. Because it just doesn't happen. Ever. There are some cases to be careful of and a few quirks you'll learn in time (and they are documented endlessly on the web). You'll learn when to expect an undefined and when to expect a null, and it's really not that difficult. Sometimes things return NaN, and that's fine too. If you are getting NaN and you don't expect it, then it is likely a problem with your code and understanding of javascript, and not Javascript itself.
You should be careful to use var for variables inside a function to prevent global namespace collision. I use the 'object literal' design pattern quite often to 'namespace' my javascript code and it works nicely to keep the code tidy. Messy/bad code will have function variables leaking out to the global scope. You will see a lot of this if you look at code on random websites.
Never use 'eval'. Just don't. Read about it if you don't believe me.
Using the object literal pattern is also good practice because you should be using JSON as a data format wherever possible. Do not use XML. Never never never use XML for something you can do with JSON. Trust me, JSON is your friend in the world of web development.
Coding abilities are not equal, and coding styles are a big part of how people run into problems with Javascript. Messy coder, messy code. Not enough deliberate thought. I've seen it time and time and time again from new coders. I would have a problem too being new to other languages that I don't know, at first, until reading enough code to figure out what is good code and what is sloppy/bad code and which coding styles to adopt. That is something you must do to learn Javascript, and there are so many examples out there, there is no excuse.
The first thing you do want to do is use 1TBS indent style http://en.wikipedia.org/wiki/Indent_style#Variant:_1TBS - following this pattern will prevent you from a few common mistakes people make when coding Javascript, like using semicolons at the end of every line.
you developed a style for those other languages. and you based that style on the strengths of the language -- I hope.
the only thing that you need to do is to see what javascript does that your other languages can't feasibly do at all. And here's the example:
window.parent.self.document.body.frames['headerFrame'].contentWindow.parent.document.body.getElementById("eNavBar-26s-t").offsetParent.children[7].style.top = "35.4cm";
it's all about the most efficient way to develop using the DOM. forget about processor efficiency, it's about developer speed. forget about the ability to create complex structures, they are already there. the DOM is as complicated as the above, and moreso. There is already an API to an application (the browser itself) and you've got huge structures tto play with, and they matter in real time.
the above snippet navigates from virtually no where through window placement and size through child and parent windows and embedded browsers, both into and out of embedded browsers, to a specific element then to related elements then to an unrelated element, then moves it to a location that may or may not be relative to other locations.
so in that above case, you're going through the presentation layer (the web page html), the network layer (tcp/ip), the window layer (the tab and chrome and buttons), and the content layer (your actual content between html tags). and you can set anything along any one of them, and it just changes, magically.
it's data-centric programming. you aren't calling functions and issuing commands. you're just changing data structures, that's it. something else (the browser), is monitoring those changes and acting of its own free will.
cool or not, it's wildly different than instructing a computer to do things. you're not. you're just manipulating one huge data structure -- and it's nested, and hyper linked, and looped.
c and java aren't very good at playing with unbalanced crazy data structures. perl is (see auto-vivification), and javascript is.
now, the fun stuff that you'll get to in javascript is the world of polymorphism. if you wanted to use javascript for non-web stuff, you'd go ape shit over the ways in which javascript can do really cool things with prototyping and inheritance. and the fact that it all becomes visual too is really fancy compared to the java or c equivalents. but most web programming doesn't use that sort of thing, so you won't be quite that happy most of the time.
think about linked lists without have to handle them yourself, then think about hyperlinking in data structures the way the web hyperlinks urls. it's not about programming the way you're used to. it's not the same. they call it programming, it's not. it's not even scripting, because you're doing nothing more than changing an existing data structure. everything's a utility function that you write to change the existing data structure.
it's not programming, and it's not scripting. it's scripted mark-up, which is exactly what it is. it's taking html markup, and describing the way it should change dynamically. it's dumb-fk stupid, and it's really basic simple, quite frankly, LOGO was more effortful to code, but because you have so much output and control over levels of interaction with living users, it's fun.
but it's not interesting at the programming level. it's not about that.
so how should you do it? have a browser window open at all times. change one line, hit refresh, see the change. it's not about the code. the code isn't cool. the output is cool. look at the output, not at the code. you should refresh about 100 times per hour of coding. you should make yourself small output consoles to watch variables and track output as you need it. you should be staring at the output, not at the code.
One shot to start the day.
One shot every 1 to 1.5 hours afterwards.
Anyone asks, then it is cough medicine (white or red galliano is good for this - it even smells like cough syrup and has just about the same effect..).
Black galliano samuca if you need to attend a meeting where discussing code and related solutions is required.
Save the scotch / whiskey / etc for when you get home.
Drink 1 glass of water 45 to 55 minutes after taking a shot of sambuca.
It makes the whole world a happier place, and in time you will start not to notice so much.
If you ever go back to real coding just decrease the dosage until you can handle reality in an unaugmented state again.
I have no sense of humour any more. But. They can't take my sambuca way from me (mostly because they haven't figured that I have it on my desk always)
>> And now excuse me, I have to set up my little QWidget 20-something lines of code with 20 typecasts strewn about just to get the bloody label to show a simple literal when I click a menu entry.
Having developed with Qt for many years, you're doing it wrong. Seriously.
Douglas Crockford's JavaScript
JavaScript: The Definitive Guide
I don't know how to rate the utility of this recommendation, because I am for the first time in my life learning how to code, but I'm doing so here. www.codeacademy.com. Every week they release new lessons and projects in JavaScript, and eventually will cover Ruby and Python as well, and it's free. I hope this is of some use to you.
Get off my lawn!
The key, as others have said already, is to stop fighting it.
JavaScript, as it was seen five years ago, was just an ugly language with horrible conventions. Then some very smart people looked at how to embrace those conventions and start doing utterly cool things that you can't do in other languages.
Learn from what they've done. Look at the cool tricks you can perform when everything is a hashmap, is an array, is an object. Look at how stupidly easy it becomes to do concepts that are endlessly painful in other languages. Have fun with it.
If you can see JavaScript for what it's become, you can have a huge amount of fun. The same part of your brain that has fun with optical illusions, M.C. Escher and even Jon Carmack's ability to break all the rules set before him to create amazing code that does amazing things, the nerd part that liked the idea of Neo bending reality? Don't fight it, revel in it. JavaScript, as it's become over the last few years, is an amazing playground.
So where do you learn to have fun poking all of those holes in reality? I learned a lot by looking at the uncompressed jQuery code and figuring out how they did things smarter than I knew how. I've also found two great O'Reilly books... Douglas Crockford's (learn that name) JavaScript, The Good Parts and Stoyan Stefanov's JavaScript Patterns.
JavaScript, The Good Parts will give you a really solid understanding of what JavaScript really is, how it can be used for evil (the old assumption) but also a lot about how it can be used for good (what we've all been discovering over the last few years).
JavaScript Patterns is fascinating because Stefanov certainly covers the standard patterns you should already be used to (Factories, Builders, etc.) but then, and this is key, recognizes that JavaScript functions in sufficiently unique ways it's worthy of having its own patterns considered.
Both of those books, plus the jQuery code, will give you a real sense of how it's possible to play in JavaScript's playground. When you're aching for structure again and miss having a compiler tell you you're an idiot and you've done everything wrong... Run it through jslint. JSLint is brutal. It's not there to be your friend. But use it constantly and it'll turn you in to a way better JavaScript coder. Now you get to code fantastic rule breaking whilst still keeping it clean and intelligently structured anyway.
It's not C/C++. But, let yourself think in the new ways JavaScript offers and it's incredibly refreshing.
In all these years and hours spent in compiler madness and dependency hell you never wondered if there had to be a better way? Keeping track of memory and pointers, or objects and threads? Compiling code? yuck. You may have to drop some acid or go off to an ashram and THEN you'll be ready to embrace the psychodelic world of callbacks and prototypes and json.
Some more serious advice: CSS and HTML are best left to specialists or you'll lose the little hair you have left. You will want a basic understanding, in particular, how they relate to the document object in js. MSDN and Mozilla have decent refrences, as does W3schools.
As for js, don't let the similarities with Java or C fool you. You'll only be wishing for native inheritance and type safety which you will never have. You'll have to embrace some new paradigms. Given your background, and after reading up on the language, I suggest you examine the sources for YUI3 or jQuery or preferably both. Then examine the source for Facebook's all.js to grok the Hacker Way to JavaScript. That will give you a good sense for the cabilities of the language and how to interact with the aforementioned document object to manipulate a webpage. You'll also have an understanding of three of the most important js libraries to know.
As a language, Javascript is easy. The hassles all come from dealing with the environment it runs in, which is usually a browser. You're making calls to a big, frequently updated, multi-platform thing that almost works. As someone else pointed out, the big headache is testing. Cross-browser compatibility is getting better; you can probably ignore the horror that was Internet Explorer 6 for any new work.
The big difference for someone coming from C is that you don't have to devote half of your attention to worrying about the two big headaches in C - "who owns what", and "how big is this array".You can afford to be more aggressive about data structure design.
Javascript is uglier than Python but less ugly than Perl. The JIT compilers are now quite good, and performance is better than you might expect. A huge number of people program in Javascript (although many of them not very well) so it's not a particularly valuable skill.
I'm currently writing in Javascript (browser add-ons), Python (server-side) and C/C++ (embedded control). After decades of C/C++, I think we should have moved to something better by now for low-level programming. Python is clean, but the implementations are slow. Javascript is in the middle, and adequate for what it's usually used for.
GWT (Google Web Toolkit). Write/debug in Java (Eclipse), have the final GUI working in browser.
No sip no deep! Perfect article. Thanks. The last paragraph impressed me the most. It ringed a bell from something familiar on hahaped.
From the source: Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products at Google, including Google AdWords and Orkut. It's open source, completely free, and used by thousands of developers around the world. You'll still need javascript eventually, but about 99% of my current (quite large) html5 web project is written in GWT. 10's of thousands of lines of code and hundreds of thousands of users, and it's quite rare that anything actually breaks. Go static typing and Eclipse tooling!
I guess C++ isn't a mainstream language anymore. Go figure.
And I already used all my fucking mod points.
Fuck the funny mod, this post should have been informative/insightful.
I would personally recommend a shot of Stroh 80, but like the original asker, I'm old and can't do that stuff anymore. But it still smells ohh so good. But alas I'm relegated to the likes of Kaiun, Jack, The Macallan, and similar as my regular grog. (And no that's not a mix.)
Wow. Lisp has closures, and it dates back to 1958. Not that I like Lisp a whole lot. I prefer to have syntax beyond parenthesis.
When I need closures and a functional programming paradigm, I usually turn to OCaml myself. (Cue hated from the lisp crowd)
Seriously, programming language preference is like editor preference. It has a lot to do with what you are most used to, and a lot to do with how your mind happens to be most comfortable thinking.
I prefer the much shorted debugging period afforded by strongly typed statically typed languages, even though it forces me to jump through some hoops that a weakly typed dynamically typed language would save me form. Personally, I've coded in C, Java, C++, Perl, Python, OCaml, Lisp, Scheme, PHP, Prolog, Javascript (very little) and Basic. Among these, Perl, Ocaml, Lisp, and Scheme all make extensive use of closures. Others may as well. (I just haven't used closures in more than those 4)
In life, not all of your questions will be answered; all of your answers will be questioned.
I guess C++ isn't a mainstream language anymore. Go figure.
Actually, C++ has it since C++11... but with typed arguments of course:
# C++
xs.fold( [](int x, int y) { return x + y; } );
Of course, both Javascript and C++ are still much less powerful than any variant of LISP.
I've been coding for 25 years and don;t have any problems with JavaScript/PHP/HTML compared to C/C++ etc...
It's all about your mindset, it doesn't matter wether the language is strongly typed or not, yes a strongly typed language will find a lot of your bugs at compile time, however if you are introducing lots of bugs into your code then you need to learn to code better, that's not a good excuse for not liking JavaScript.
A bad workman will always blame his tools.
95% of the bugs in my code are logic related where I haven't thought things through properly but then when you have algorithms that can run to several hundred lines of code it's easy for that to happen, a compiler does squat to help with logic, I can look at JavaScript or any other code I have written and I know exactly what each variable is used for, mainly because of how I write my variable names, strong typing within the language makes no difference to me and I have never understood that argument.
Then next time take a look at LibreOffice. The macros can be coded in Javascript or Python.
Beta is broken and the link to classic doesn't work. Stop wasting our time or there won't be anybody left here.
AFAIK, this is a Object Pascal ~(Delphi, Free Pascal) to Javascript "compiler".
http://op4js.optimalesystemer.no/about/
Example of creating a custom GUI control:
http://op4js.optimalesystemer.no/2011/10/05/your-first-op4js-custom-control/
Hivemind harvest in progress..
Let's leave the advantages and disadvantages of the language features aside for a moment and approach it from an alternative perspective such as how a programmer can accomplish tasks and feel confident their code is solid.
In his native environment, code is developed and compiled and once it is in compiled form, the state of the code is more or less known (assuming he used decent practices such as unit tests and such). He is transitioning to an environment where the state of the code is entirely unknown and even until recently with the much more strict definitions of how HTML5 should be represented in DOM, the state of the runtime was extremely hard to know.
I think what he is looking for which would make the world of difference is if he attempts to adopt the test driven development style of coding. This way, as he codes, instead of compiling, he would instead execute his tests to make sure his code is sound. Of course, test driven development can drive many people utterly insane, especially since a person finds themselves wanting to write tests to test their tests. But using test driven development, you can press a key in the IDE and get the feeling that you have compiled successfully or failed in a given case.
Languages like EcmaScript which (similar to Ruby and most other interpreted languages) are a nightmare to people who expect their code to be compiled and that all link issues are sure to be resolved at compile time. Also, the dynamic nature of languages like EcmaScript can make a long term C++/Java programmer extremely grumpy since we old fellas see many of the techniques employed in these languages are hackish... as if the language was made more dynamic to avoid adding basic features which function better in compiled environments.
The real answer to the issues here is that using other languages that compile to EcmaScript is a great idea for people who don't like the dynamic prototyped nature of Ecma. There are some great solutions for C# and for Java to Javascript out there. The problem with those systems is that their learning curve can be high since C++ developers often don't like having to depend on weird tools for things like UI.
Of course, it would be best to learn to program in Javascript if that's the user's goal, but depending on what you're coding Javascript can often be a suboptimal solution. I personally have been coding an H.264 codec that will run in Javascript, WebCL and WebGL when it is done and frankly, Javascript is a truly terrible language for this, so I'm experimenting with moving the code to something strongly typed and compiles to Javascript.
http://typedjs.com/ will make some of the debugging more bearable.
Would you like fries with that?
And of course Objective-C 2.0:
# Obj-C [xs fold:^(int x, int y) { return x + y; });
C++ closures are what happens to a beautiful abstraction after it goes through mordor. It becomes an orkish, vile thing more fit to hurt the user and confuse him than to achieve something of good and beauty.
I mean, where's your GC?
Everyone that has modded this one up should feel ashamed because it is not "informative" it is just plain wrong. No arguing. A 10 second web search would have made that clear.
Yes, yes. I must be new here.
Jack of all trades, master of none. If you are making a decent living doing what you do, on platforms that don't look like they are going anywhere for the next 20 years or so, why change?
I code in lots of everything. Most of my work is database oriented, so I do a lot of SQL, MySQL and Access query writing. I also work on the interfaces for these databases, some are web based and others are application based. So, I work a lot with PHP, C++ and Java too. In my experience (which is comparable to your own in terms of length) I find that because I do all these things that I tend to lose specialist jobs. People who want an application done entirely in C++ have said to me in the past that they are worried that my company would not be able to handle a large project of that nature.
When you specialize you open the door to larger earning potential. When you specialize in generalized disciplines (as I do) you open the doors to more work, but less quality work. The trade off, in my experience, is not worth it. I have learned a lot more, spread myself out and not focused on a specific discipline and the result is likely an identical earnings potential but with more effort put in to get there.
Javascript (aka ecmascript) is friendly to those who want to implement scripting in their application not to those who want to write scripts... got it?
Makes a lot more sense now doesn't it?
I agree, it was flammish to say JS has inferior abstractions. It DOES have LESS abstractions. But the few it has are actually more powerful and general than Java's. In other words JS is more orthogonal than Java, you do more with less, which is a good thing, and I say this as a harsh critic of JS!
But typechecking is one of those things that, while dynamic programmers like me shrug, does make a lot more sense than I usually accept. If static type checking is for you, JS isn't. However it is possible to compile Java to JS, there are several implementations but the best one is Google's Google Web Toolkit which is exactly that. A Java environment that compiles to Javascript.
But... the future refused to change.
JS solution may be the most verbose, but I'd argue that it's the easiest to read, learn and understand, since it doesn't introduce more language grammar.
I know you said to ignore the operator-as-function thing, but it looks so nice in Ruby:
Not that Ruby is very functional, sadly.
> I mean, where's your GC?
std::shared_ptr f = std::make_shared();
Understand the Javascript language, because it is a simple, yet powerfull language on its own. So, before digging deeper into libraries and tools, take some time to read the javascript garden, which will give you the dirty parts: http://bonsaiden.github.com/JavaScript-Garden/ And, as previous posters already said, the Crockford site which will give you good insight into good practices and useful patterns: http://www.crockford.com/
Ada is strongly typed. C is not.
But in any case the advise for living with Java script is the same advise I give people that are used to C++ and trying to get used to the 'strong' typing of Ada. You really need to work on thinking in your new language and not cling to first thinking of the solution in your old language in your head and then translating. There is not really any magic to doing this other than writing a lot of code AND trying to not let emotion get in the way.. Once you've picked up the tool, use it.
--- Liberty in our Lifetime
I've been using coffeescript for a while now, and quite surprised it hasn't been mentioned yet.
http://coffeescript.org/
1. Read everything Douglas Crockford has on his JavaScript website. Use his jslint program. Down the road, read the code of his jslint program, I suppose. Buy and read his book. It's also available for the Kindle. Read the whole book twice. Basically, the lesson is don't make JS try to be Java, it only causes headaches.
2. Get a good JavaScript book for the language itself, this listing of JavaScript book reviews recommends the Wrox book, but I haven't read it, I use the 6th edition of the Flanagan book. See the link.
3. It's a language that, along with HTML and CSS, needs you to have a great memory or a good IDE that will prompt you for the allowable names. You can get a version of Eclipse pre-built for JavaScript, and you can get the Active State Komodo Edit program, both free. They say the Komodo IDE is even better, but it's expensive and probably not as complete as the (free) Eclipse.
4. You can get a version that runs on your desktop like a shell or perl/ruby/python will, but it isn't necessary. I know you can easily get a version of Mozilla SpiderMonkey that will do that.
5. Don't use the double-equals comparison operator, it's too confusing. Use the triple-equals operator ( "===" ), it's a pain to type but it's more straightforward.
6. Be wary form whence you copy. There's a lot of terrible code out there.
7. Use jQuery after your first two or three practice web pages, and after you've got CSS under control. This means also get a good CSS book. I guess start with the 'Lie and Boss' book, even though it's old.
I18N == Intergalacticization
You meant 'moobs'?
No sig today...
Precisely! :-) That's not a GC. I'm tempted to say something about what happens to a GC when it is subjected to the horrors of mordor, but I think I'll refrain.
In my opinion you are a poor programmer. Don't take it personally as 99% of programmers today rely on compilers to double-check their work. When I started out in the 70's we were taught how to program without errors. The reason being was that it took time and money to complete a compilation. While compile times are extremely fast relative to historical comparisons, and dependent upon other factors, in fact each compile costs you more time than you realize as you stop developing/thinking, click the buttons, wait to see if the slot machine gives you three cherries or lemons. When you get lemons your mind starts racing to find a solution to the new problem and it is distracted from the goal.
While this all may be true, I agree that Javascript and the likes suck and are annoying at best to program in. For if you are going to have it loosy-goosy when it comes to errors Javascript development environments/tools need to provide some better error messages.
Being a generalist isn't about knowing lots of languages: it's about knowing a lot of different ways of doing things. As long as you restrict yourself to the paradigms of C and C++/Java, you won't be able to do that. Bite the bullet and learn the JS way of doing things, and while you're at it, pick up things like Scheme and Haskell. Heck; even AWK could be interesting for this exercise.
Every new way you learn of doing things and approaching problems will make you a better programmer in all of the languages you know. That incudes C and C++/Java, and it also includes JS/HTML/CSS. It's also what being a generalist is really all about.
I suggest Eclipse IDE for JavaScript Web Developers: http://www.eclipse.org/downloads/packages/eclipse-ide-javascript-web-developers/heliosr
and Chromium Eclipse Debugger: http://code.google.com/p/chromedevtools/
Everyone else seems too busy engaged in the language flame war to answer your question
Smalltalk been around for quite a while. At least a decade longer than Java.
Try CoffeeScript. It's well designed, very easy to learn and highly efficient. It compiles to JavaScript and is easy to debug.
I prefer to have syntax beyond parenthesis.
What other syntax do you need? Some people are never satisfied.
It's the values that are typed, not the variables. That's common for dynamic languages. Some people are quite accustomed to this. You can be, too, if you want.
now we need to go OSS in diesel cars
Sigh. Just because a language has hot over-hyped feature "x" (which in this case is closures), doesn't mean it's a *good* language. JavaScript is certainly usable, but it's not a good language. I think of it like FORTRAN. A lot of awesome apps were done in it, but at a cost... It's time consuming and error prone compared to other languages. It'll need to be supported for a long time, but for new development it needs to be replaced with something modern.
It's not a bias. Javascript has inferior abstractions. Fact.
I may lower my standards and use it when forced, but I am painfully aware that I am stooping low to do so.
The OP will have his arse reamed by JS over and over because a real language does not do the things JS does. And that's just the published spec. What any actual browser does is pretty much completely random. Trying to use JS for anything real is a hopeless task.
I find JavaScript to be very powerful when used intelligently. I've used about every language out there and I've been programming for over 30 years.
You probably just suck.
Learn Perl
The day I trust others to write code better than me is the day my work becomes just good enough. There is not a lot of vertical mobility writing good enough code.
The attitude that you are a better coder than all your peers does not go over well when you start working as part of a team. If you want a long successful career as a coder you need to get used to working in a team, and that often means relying on other peoples code to work. You may even one day become a technical lead where you have to trust other people to write code, that means also letting them make their own mistakes and learn from them.
I dont read
The lack of GC - or even some approximation - is what makes C++11 lambdas completely horrible. The language does nothing to ensure that your bound variables actually persist for the lifetime of the closure. You are required to use smart pointers for all of them. This is trivial stuff for the compiler to do (in Objective-C, for example, block variables - including C values and structures - are automatically moved to the heap when required by a block persisting) and a pain for the programmer to do. So, of course, C++ makes the programmer do it...
I am TheRaven on Soylent News
Google Web Toolkit runs on JavaScript, but you (the programmer) use Java instead. It makes life much, much easier...
google provides gwt, you write your code in java, it compiles to javascript for all browsers. worth a look if u want web programming with java. it does have its quirky moments.
further gwt coupled with something like sencha gxt lets you write web applications not possible easily with the likes of jquery etc.
As always learn the basics of all the usual suspects, learn at least one if depth, preferably more than one
Then use the most appropriate one for the current project ...
The OP is of the "I'm a C/C++ programmer, how do I use Javascript to program in C++ ..." school ...
Puteulanus fenestra mortis
I can't really help with the strongly typed bit. But for a C++/Java guy doing GUI work I think you might like the QooXDoo library. It sort of compiles the javascript with a python script. The python compiler script will catch some mis-typing errors but certainly not all, you still have to be on your toes. However, what I really like about QooXDoo is that it frames HTML GUI development in a style that is reminiscent of Java or C++ widget libraries. The system has really allowed me to be productive at a level I would not have been able to tolerate previously.
JavaScript is little more than an ugly bandaid - don't go there.
You're falling into the trap of trying to make it into what it is not. You can turn screws with a pocket knife and you can carve with a screw driver. You won't get good results.
Dynamic typing was hard to do when your code was translated to hardware machine language, since different data value types had to be handled by different sequences of code. Static typing is actually the legacy approach, and the crutch upon which weaker coding-time validation methods depend on.
now we need to go OSS in diesel cars
I don't quite understand what the trouble is. If you truly are an "experiencd" java/c/c++ developer, then you should also be fluent in shell scripting and perl from all the debug/build/log parse utilities you've written to make your life easier (and that have a similar paradigm).
That is, unless you developed only on Windows, in which case there is a much bigger problem that needs to be corrected first, before you even *think* about tackling the "future" through iTechnology.
while(1) attack(People.Sandy);
Define "less powerful". There's nothing that can be done in one language that can't be done in the other.
Perhaps you actually mean expressive or something like that? That's quite possible, but they're different tools for different problems.
OP here. Wow! Thanks for the amazing and insightful responses, everyone.
As I read the comments, many of them reminded me of an old programmer's aphorism: "You can program in assembly in any language." I need to stop trying to program in Java in JavaScript, get past the superficial syntactic similarities, and immerse myself in JavaScript and its paradigm to learn to "speak it like a native."
I had already discovered Douglas Crockford's JavaScript: The Good Parts and jQuery but I will grab some of other books and learning resources. The explanation of how the various other frameworks, like MooTools, CoreJS, Dojo, ExtJS, etc., relate to each other was also helpful in understanding the overall JS ecosystem.
Finally, I will grab JSLint, JSCoverage, and QUnit (as one poster said, "QUnit is now your compiler"). I've been oscillating between Komodo and WebStorm, but neither feels quite right for me so will give Aptana a look.
Again, thanks for all the feedback!
To each their own. To me, GC is what happens when memory management is dragged through mordor.
I've programmed in countless languages over many a year, and never once have I missed GC in C++, whereas I've many times been annoyed by it in other languages. But then, I'm a bit of a control freak. So yeah, to each their own, no need to make derisive or condescending remarks about a language just because you don't like it.
I was the same as you. Embrace it. And use backbone.js.
I learned C/C++ and Java first. Then PHP/Javascript. I remember weak/no typing feeling so strange! It took me a while just to 'get it'. Now I program C# at work but still code PHP from time to time at home. I miss weak typing! Strong typing really does suck IMHO. It seems like 2/3 of my code now is just checking that data will 'fit' in another type, casting it, checking that the casting succeded...
I know a lot of people defend strong typing because it is supposed to somehow save them from writing bugs. The excuse I usually hear is something about you might 'forget' what type a variable is and try to misuse it. It seems to me you should know what that variable represents before you try to use it for anything and the 'type' should come naturally from there!
One of my favorite patterns in PHP is to fetch a list of things by id number. Then I have an accessor that first checks to see if what is stored is a number or an object. If it's a number it fetches whatever information that id represents, wraps it in an object and puts it back in the very same variable that used to hold the id. Then it just returns the contents of the variable. If it is already an object it can skip the fetching and just return the object. Of course you can implement Lazy Fetching in a strongly typed language too but I just like that neatness of having one variable which holds either the id or the object rather than two of two different types. So long as I only access it through my accessor method (which PHP has __get and __set for which I really like) I don't have to ever think about what is actually stored there. It will be an object if and when I need it.
Of course I'm on a tangent now, you are less likely to do something like this in javascript but my point is that loose typing can be really nice once you get used to it.
Indeed. It should damn well be compulsory for every programmer to learn at least two programming paradigms. And I don't mean just the theory of them, but actual practical knowledge and experience with at least one language adhering to the paradigm in question. While I don't presently do much functional programming at work, for instance, I find my time with Haskell invaluable and very enriching. I'd be a worse programmer for not having that knowledge, even in my present line of work.
The shit are you talking about. C / C++ and Java do not have closures. Period. They have things that sorta kinda resemble closures but they are not them.
Slashdot is proof that Sturgeon's Law applies to mankind.
Closures are the mother of all abstractions. Any other abstractions can be made from them, so maybe you should learn yourself some comp sci before you sigh.
Slashdot is proof that Sturgeon's Law applies to mankind.
I implicitly meant "of the languages you were discussing" which are C C++ and Java. Sorry I wasn't verbose enough to keep the context fresh for ya.
Slashdot is proof that Sturgeon's Law applies to mankind.
I was using Javascript in 96... cool kids like me use facelets and a component library.
Primefaces is pretty good. (there's also richfaces and icefaces)
Javascript is just something you spackle the cracks with now. (Like a key blocker or something)
Javascript was always a bitch to get it to work against multiple browsers and AJAX made it more nasty.
But if you use a component library it takes care of all that for you.
Then you can concentrate on the design and less about what's going on under the hood.
You're doing it wrong
1.) No kidding. I just started using C++/Qt a week ago, you remember?
2.) I was exaggerating little for the fun and effect. But I think you understand. :-)
Still, thanks for the heads-up.
I'm a lot on Google and stackoverflow these days anyway, as you can imagine.
Got a fresh copy of this 1000 page beast sitting on my night-table and OReillys C++ Cookbook should be arriving today, and I'll have a lot of refactoring to do before I can call my little first C++ app finished and not totally embarrassing to show to a Qt/C++ expert. ... I'm currently trying to wrap my head around Signals and Slots, after years of only knowing Events and Listeners. I still don't get it, but people tell me once you do it's awesome and you don't want to go back. Sort of like using Git instead of Subversion. Ergo: Lots of work to do. ... *promises to stop doing /. for the day*
We suffer more in our imagination than in reality. - Seneca
I use Google's Closure Compiler to check usage in a fashion similar to how a traditional compiler would. It's found a lot of errors for me over the last few years.
Another benefit is it makes your code compressed, and makes it a teeny bit harder to copy without authorization.
Someone may have said this.. but check out Coffee Script.. its a higher level language that compiles INTO javascript.. with its own make files and coding conventions.. the plus side is it makes OOP in js not make you want to kill yourself. there are a few things it adds that makes it worth using, a foreach loop, some scope switching stuff.. but all in all its a REALLY simple language and you could learn it in a couple hours.
JSF 2.0 or Java FX are java framework to make client side "view" portable.
The Project Avatar will port your view to any html 5 compliant browser, for any kind of device (intelligent phone, tablet, mac, windows, linux, over the web and so on).
Unless you really need to use it (because someone ask you to for your living), you would be in better shape to use JAVA stuff to make anything you want to "port" over any device without major pain.
RIA and Web 2.0 apps don't need to have spaghetti JS and html to be maintained... they can be JAVA apps that are easier to maintain over the long run with a working corporate giving you the tools to port your app to the new "shitty" device UI of the month.
For garbage applications, that have short lifespan, it's really fine. But for big fat corporate applications, it's the kind of mess (JS + html) that any developer want to "flee" for greener pasture.
I recently was on a project where I wrote a CAD package in C#, C++, Flash, and Javascript. With so many different UI's I had to keep things as similar as possible, and what I learned was that if you code JS in a certain way -- using only a subset of what it is capable of, you can treat it just like OO and keep your code and methodologies portable.
1) If you are writing a web app, make it one HTML page. This breaks the forward and back buttons, but sometimes this is okay, and you can trap events and take control of them if this is a super critical issue.
2) Once your app is one page, then you can think of it like a normal event-driven Windows app. It works just like WinForms, Swing, etc! State is kept on the client side, you get button click events, and you modify the HTML DOM to pop up windows, add controls etc.
3) Make separate little HTML + JS files as your "controls". Make say datagrid.html with all the datagrid functionality right in it. When you want to popup a datagrid control, dynamically load datagrid.html with jQuery and write it into the page. The inline JS will come right with it! Presto, you have controls!
4) Aside from loading the initial HTML page, subsequent controls, only use the server connection for data! Do everything via web-services.
5) Don't use the full on prototype-system. Use it only to emulate OO. Classic inheritance is a subset of prototypical inheritance, so if done correct, everything works exactly the same way.
At this point your JS app will look exactly like a conventional database driven client-side app! I ported 99% of my code line-for-line, keeping all the same class names etc, and was able to use this technique to keep a roughly 20,000 lines code-base consistant across C#, JS, and Actionscript. If you think of HTML+JS as MXML+AS or XAML+C#, it will behave exactly the same way!
Beyond the mental shift, I find the sticking point for most people is correctly implementing #5, so to help, here are 3 files showing inheritence:
1. VectorNd.js - an Nth dimensional base close for Vector2d, 3d, etc - http://pastebin.com/NFD34Hcp
2. Vector3d.js - a strictly 3D subclass of VectorNd - http://pastebin.com/B7henwas
3. The clone() function used by Vector3d.js - http://pastebin.com/Bd3QRqGE
Once you wrap your head around it, the inheritance model described above is exactly analogous to traditional OO, and you can even have getters / setters in JS. The old-fashioned event-driven Windows-style app has been around since the dawn of the UI, and despite HTML5's painful birth, I'm convinced HTML5 applications will work their way back to something like it, because it is the most logical way to handle the problem.
I feel some harsh flames coming on, but before you mod me down, please keep in mind this was an honest attempt to answer the author's question as he asked it :)
I think it is an old-school problem, and can be solved in an old-school way. Write everything in Notepad for a month. No IDE, no auto-complete, no projects. JavaScript will instantly make sense, or at least more so than it does now.
I think it's the Java that spoils the fun. Going C/C++ to JavaScript was not an issue for me, but that's because I do a lot of editing outside of an IDE anyway. But that's just my experience.
Write a basic HTML page, seed it with expected data, then write your script around it. Load it locally and run it in IE/FireFox/whatever. Then take your functions and put them in your project. Advantage - you only need a few more unexpected data points to make it into a unit test page.
Yes write more code, but do it differently. Solve a non-javascript problem in javascript, just because it's there. Make a random dice tossing page that actually shows dice that look like dice. But do it in a simple text editor. Get used to the language, how it "feels" to type it, how it looks when it's correct and when it's not.
As a long-time C/OC/C++ guy, I regularly get horrified by JS.
However, JS works for the limited context of a Web browser. I'm not thrilled with the way it handles OOP, and I think it's awkward, but I've gotten pretty good at messing with it.
Here's a bit of code that I love to show C++ folks. It demonstrates exactly how primitive JS is, compared to C++:
<script type="text/javascript">
function HiDare() { alert ('Hi Dare!' ); };
function DisplayHiDare () { alert ( HiDare ) };
DisplayHiDare();
</script>
Coders will understand instantly, and ROTFL.
"For every complex problem there is an answer that is clear, simple, and wrong."
-H. L. Mencken
The web is a weakly typed floppy mess built on a flawed stateless protocol, but it's OUR mess ;-)
Chrome tools, STS and Closure tools minimise the pain.
I've been responsible for maintaining CAD software with client apps in C++ / C# / JS / Flash. Because I found commonality between all these languages, I was able to port the code quickly and easily. Some tips:
1. Keep all the state on the client side. This means put everything on one HTML page, then manipulate the DOM to add controls, etc
2. Create a set of HTML+JS controls (say datagrid.html for example), then use jQuery to load instances of these controls into the DOM
3. Aside from the initial page load and loading of your controls, the only other reason to call to the server is to save & load data via webservices
4. Classical inheritance is a subset of prototypical inheritance, therefor you can emulate it perfectly. See the below examples:
Base class: http://pastie.org/3341844
Subclass: http://pastie.org/3341846
Clone function: http://pastie.org/3341847
If you think of HTML+JS just like you would MXML+AS or XAML+C#, then your app works the exact same way! HTML5 doesn't have to be any difference from the traditional model, you just have to tinker around with it more to achieve the similarity, since there isn't really a built-in concept of controls. Lastly, install Chrome. Since there is no compile-time, this is your new IDE. If you go into "developer tools" you have all the traditional stuff: call stack, break points, watch window etc. You still have to write your code in notepad without auto-complete, but everything else you do right in the browser. You can even use the watch window to inspect what methods are on an object, so you can use this as a sort of "manual" auto-complete!
PS, before I get modded down, please see that this was an honest attempt to directly answer the author's question.
Javascript is just messy. When you intersperse it with html, it is just like the bad old days of interspersing your layout with the html. CSS was created to separate the layout from the html. Javascript libraries do the same thing. Look into JQuery. The separation of the Javascript from the html makes it a lot easier to see what is going on. Also, use debugging tools like Firebug and Firequery to track down what is going on in the code. Good luck.
Ever heard of C#, Objective C, Ruby to name a few
Proper lexical closures (such as exist in Scheme and JavaScript) cannot be implemented in Java or C++.
you had me at #!
This is trivial stuff for the compiler to do (in Objective-C, for example, block variables - including C values and structures - are automatically moved to the heap when required by a block persisting) and a pain for the programmer to do. So, of course, C++ makes the programmer do it
It's trivial, but it's also observable. One of the more common causes of leaks in C# 2.0+ is when a local variable is lifted to heap because it was captured by a closure, and a reference to said closure is left around even though it won't ever be run. With shared_ptrs, it's even worse, because you can also get a cyclical dependency that way.
Anyway, C++ mantra is "you don't pay for what you don't use". This means that, if your lambda never outlives the local scope (and most of them - when used as predicates or mappers for std::find_if, std::transform, std::aggregate etc - do not), it should not wrap locals into smart pointers, because that would needlessly decrease perf. On the other hand, they haven't yet come up with a good way to deduce this sort of thing automatically for the most general case. Hence, it's left as a choice to the programmer.
Are you seriously suggesting that introducing a single new piece of punctuation, like an arrow, makes PL significantly harder to learn and understand?
If so, then I think we should throw a+=1 and a++ out of JS, as well, on the grounds that a=a+1 is the easiest to read, learn and understand...
Seriously, though, syntax is by far the simplest part of learning a new language. It's the concepts that are toughest. Once you actually understand what lambdas do - and you need to understand it for JS just as well as for any other language - it doesn't matter much how they're written down.
OP's use of the word tolerable makes it obvious that OP is not focused on how to use Javascript, but instead is focused on the hurdles of change. Fact is Javascript is not a hard language to use, and looks mostly identical to Java. That's not the problem and the OP knows it. The problem is the OP wants to do something the Java/C/C++ way as opposed to just doing it. I call this mindset hacker-bushido. So OP, you might have spent years practicing the precise way to cut a piece of bamboo with a sword, but now you're using a spear. Don't focus on using the spear the way you learned to use a sword, just kill people with it.
Ruby is very functional - idiomatic programming in Ruby strongly encourages using higher-order functions and closures...
I suspect what you meant to say is that it's not pure - i.e. allows and encourages mutable state and intrinsic object identity?
I don't think C is worth investigating in this context, since it's explicitly a lower-level language. That it lacks closures is kinda by design, it would simply be too "magical" for C.
C++ has lambdas as of C++11.
Not to detract from the desire to expand your toolbox, but have you considered http://www.webtoolkit.eu/wt as stepping stone into web application development? It essentially abstracts much of the CSS/DOM/HTML/Javascript hijinks away and allows you to think and develop in C++. It's modeled after the well known Qt framework.
In Objective-C blocks, locals that are bound are referenced indirectly via a pointer. This is pretty cheap in the on-stack case - the variable and the pointer will be in the same cache line - and when the block is copied (which happens automatically in ARC mode when you assign a pointer to it to the heap or a global) so the general solution works quite nicely. It is still possible to construct cyclic dependencies if the a bound variable references the block, but it's nontrivial.
I don't think 'you don't pay for what you don't use' is really the C++ mantra. Having worked on C++ compiler and library implementation, I would say that the real mantra is 'no feature may go into the language if it decreases microbenchmark results, even if it will make large projects faster'.
I am TheRaven on Soylent News
Matz has said several times that he doesn't like functional programming much and has no intention of adding things like ZF-expressions (list comprehensions), operator currying, all that stuff.
You're right that it has nice support for closures.
In Objective-C blocks, locals that are bound are referenced indirectly via a pointer. This is pretty cheap in the on-stack case - the variable and the pointer will be in the same cache line - and when the block is copied (which happens automatically in ARC mode when you assign a pointer to it to the heap or a global) so the general solution works quite nicely.
Do you mean that the stack frame has a pointer to a memory location that's placed on the heap, and said pointer is what's captured by the closure? If so, then "pretty cheap" is still arguable. For one thing, you still have the expense of a heap allocation/deallocation - both time-wise, and also memory expense due to heap metadata. For another, you have those refcount updates.
It also leads to the next interesting question: how many heap allocations do you use for this? It's tempting to collect all captured locals and shove them off into a single struict to save on allocations. But now, if you have more than one lambda in the scope, and those lambdas reference different sets of locals, they will both hold a reference to the same struct. If one lambda references a large object (say, a collection), but has a short lifetime - e.g. does not outlive its scope, a fairly typical case - and then another lambda has a long lifetime (say, an event handler) but only references a single local int - that second lambda ends up holding the vector also because it shared allocation with the int that it needs. On the other hand, if you split captured locals into several structs, you get more allocations and more refcount updates.
C# implements something similar - it shoves all captured locals into a single class, and puts a reference to that class on the stack, and that's what all lambdas in the scope reference. As a result, the problem described above - memory "leak" when you have more than one lambda, and they end up sharing all captured variables in that scope even if they don't use it - is not uncommon.
In C++, on the other hand, I can make my own decisions. If I want a shared-closure-for-all-locals, I define a local struct and put in a shared_ptr referencing it, then capture that from my lambdas. Note that lifetime implications are explicit in this decision - lambdas are clearly capturing the whole thing, not individual fields, so it stays alive for as long as they stay alive. On the other hand, I could instead have separate shared_ptrs per each captured local, where that makes more sense.
I'm not saying it's a huge difference, but there certainly is one.
Python is my favorite language of choice, but I very often remember wrong the exact lambda syntax when I've had to use it, and by extension often avoid using it for that very reason. And the first time I read it in use I felt overwhelmed and had to google it. However first time I read the JS syntax in some jquery code I immediately understood that I was passing an anonymous function with access to local scope. Didn't even have to learn or know about any "lambda concept".
Also in python, a++ is in fact not allowed precisely because a+=1 or a=a+1 is easier to read, learn and understand :)
It's the same old argument over what exactly "functional programming" really is, I guess.
However first time I read the JS syntax in some jquery code I immediately understood that I was passing an anonymous function with access to local scope. Didn't even have to learn or know about any "lambda concept".
That is because you understand what an "anonymous function" is, and how it works with respect to variables that are declared outside its scope - that's precisely what I meant by "lambda concept". For someone coming from, say, C, which doesn't even have nested functions, it's much harder to comprehend.
Also in python, a++ is in fact not allowed precisely because a+=1 or a=a+1 is easier to read, learn and understand :)
Perhaps, but how far are you willing to push it? The next logical step is to drop a+=1 for a=a+1. Then maybe to drop + altogether since we already have functions, so it becomes a=add(a, 1); etc. Another example is "for", "foreach" and equivalent statements - surely you can just use "while" instead?..
At some point you have to draw the line. And simple, straightforward syntactic sugar for heavily used constructs - which is precisely what "a => a + 1" is relative to "function(a) { return a + 1; }", at least if you heavily promote the use of high-order functions elsewhere - is always worth including.
I would say C is worth discussing considering the story is about a guy who is all C, C++, Java and some rhodes scholar AC up there said JS has inferior abstractions.
Also please make sure not to conflate lambdas with closures. It's pedantic but they are different animals. I don't know enough about C++11 'cause I had the good sense to flee from that shit in the 90's so I can't speak to the implementation of it's lambdas to know if they can close over free variables. Java, for instance has anonymous inner classes which can behave like lambdas, in a manner of speaking, but you are explicitly forbidden from closure.
Slashdot is proof that Sturgeon's Law applies to mankind.
My advice: forget about types. You are wrong to think that types are a debugging feature. They are not. Types were originally included for use in programming languages where there was no automatic memory alliocation and when memory usage had to be manually managed. With a VM language like javascript, this is no longer necessary, Some dynamically typed languages such as perl really have just one scalar type, a string, and there are several data structures and there are references and objects. All of the size types are simply unnecessary and actually created more complicated code. The size types do not prevent a wide variety of coding errors and really just not something that one needs to think a necessary thing to have for debugging.in Perl, in fact, is a much safer language than C because it lacks C's buffer overrun craziness, as well as cleaner code with less unnecessary typing mess to worry about. Perl automatically sizes its strings for data.
... but real programmers use butterflies.
C++11 lambdas close over free variables, but you pick the exact nature of that closure yourself. You can "capture by value", meaning the local is simply copied into the lambda; or you can "capture by reference", meaning that the lambda will reference the variable in outer scope. You can mutate the variable inside the lambda in any case (unlike Java's anon inner classes, which only capture finals), but when you capture by value, it's the copy that is mutated. On the other hand, C++ doesn't do anything special to extend lifetime of captured variables - so if you capture byref and then the variable goes out of scope, you can't legally access it anymore - if you need this, you use a smart pointer instead, and capture that by value.
Also, I wouldn't say that Java anon inner classes are "forbidden from closure". They are more limited in terms of what they close over - in particular, they only close over finals, not just any random local. But I don't see how that makes them not closures - after all, in Haskell, all variables are "final" in a similar sense, yet Haskell lambdas are most definitely closures. There is an argument that AICs are not true closures because they don't close over everything that's available in the scope in which they are created - i.e. you can't write any random code at the point where AIC is instantiated, then move it inside AIC and have it working in the same exact way. But that involves more than variables - for it to work, it'd have to also close over the context of "return", "continue" and "break". If you use that definition to determine whether something is a true closure, than JS doesn't have closures, either, since it doesn't handle any of those.
The real problem with AICs is that they are extremely verbose to be used with higher-order functions conveniently.
After Erlang's dynamic runtimes, JavaScript comes across as a strongly typed language in comparison! :P
I do not fail; I succeed at finding out what does not work.
I didn't find javascript to be unbearable. It didn't take to much time, and I learned how to make it do what I wanted. The ugly parts were all DOM related, and even that wasn't too bad once I got the basics. Most of the nasty issues had fairly straightforward workarounds once I found out they were there (for example, the relationship between DOM modifications being posted and when an event completes between browsers). Now there is jquery, which has pretty much hidden all the ugly DOM nasties, and makes javascript nice in most regards. I still dislike the OO model, but I can deal with it.
That said, CSS is an absolute abomination. I can't say anything positive about it. The general idea about separating the content from the layout is a good one. The problem is that CSS is so fundamentally broken that probably 4/5ths of everything I want to do, requires some nasty hack or is simply impossible without using javascript to position something on the fly. I guess my problem is that i've used so many GUI and print layout engines, that I expect there is a way to do things that I imagine, rather than trying to fit my ideas in the constraints of CSS. Nor do I like sprinkling divs all over the place to work around asymmetries in what attributes can be applied to existing tags. Worse yet, are the divs that need to be sprinkled as tag holders. Plus, the fact that I need to use a CSS preprocessor, for basic things seems insane. I also hate its inability to explicitly reference a parent or siblings with respect to simple layout concepts like rightof/leftof, instead requiring layer over layer of divs. I shouldn't have to screw around with the markup to do simple layout changes. I could probably write a hundred page book without even trying, on things that are wrong with CSS.
Frankly, I was so sick of it, I wrote a layout engine in javascript, that entirely replaced HTML and CSS, with a generic set of XML tags more based on traditional GUI concepts. I learned a whole crap load about javascript and the DOM doing it too. The sad part, is that I never really finished it. Its good enough to draw some simple overlapping windows, and allow the user to reposition them, click buttons, draw things, etc, but its not really good enough for prime time. A big portion of the problem is that its hard to do fast flicker free animation and drawing simply from JS. Sure I can draw a region, and a scroll bar, but when the user scrolls the region, it should be nearly as fast as doing it with just a normal browser and HTML. Doing all the drawing/layout with javascript makes this nearly impossible. Then the single threaded nature of the event system in all the browsers also tends to cause input lag if the redraw process gets involved.
Basically, in the end, there is a reason flash, silverlight, java web start, and random other plugins still exist. Doing heavyweight UI's using JS/HTML/CSS/etc is a PITA.
My GC? My precious!
Lexical closures in LISP date back to the 1984 release of Scheme. The original LISP had dynamic scoping, which isn't the same thing.
Try runtime debugging with firebug. There is no substitute.
Use Sencha's Ext JS 4 library. Awesome.
"However, I find JavaScript's weak typing and dynamic nature difficult to adapt to because I'm so used to strongly-typed, compiled languages with lots of compile-time error-checking and help from the IDE"
In other words: "Despite my 20 years of experience I've never been a particularly good developer because without my tools doing half the work for me I'd be all but useless to my employer. I can't really think for myself, have poor fundamentals and therefore when confronted with a technology that requires I actually have a clue, it's difficult for me."
Isn't it ironic that it takes something like JavaScript that so many still incorrectly consider a bicycle with training wheels to expose those that don't really know what they're doing?
I have 25+ years of experience and I can get the job done with multiple languages of multiple kinds on multiple platforms equally well. Know why? I actually know what I'm doing! Tools can make me more efficient, sure, but I don't *need* them to work well (and frequently I prefer *not* having an IDE constantly thinking for me). I learned a new language (Lua) in the past few weeks to the point where I'm now developing a highly complex mobile app with it and that's not at all unusual, transitioning to a new technology. Not hard to jump around like that when you're a *real* developer.
(Disclaimer: obviously I don't personally know the OP, so take this more as a condemnation of a far too many developers in general these days, not specifically of this guy... I'll give him the benefit of the doubt since I don't know him)
If a pion (n-) collides with a proton in the woods & noone is there to hear it, does lamdba decay into the source pa
Yea, I know you are an old-skool C/C++ Unix neckbeard that has to sit in the presence in Javascript code.
Pull up your big girl panties, quit bitching and get back to work.
This sig is not paradoxical or ironic.
How is Ruby not very functional? How much Ruby have you done? OO features and procedural features are optional. You can operate strictly on lambdas and local variables if you wish.
Brian Fundakowski Feldman
My opinion is similar to many of these professionals who deal with JS on a daily basis, however, to be clear I do NOT professionally write JS nor do I really know HOW.
However, I would suggest to you that you look not at how JS can be converted to your current programming style, but rather investigate the fundamental differences between your current programing languages and JS. As a C++ developer you are using a language designed to compile and run on the computers CPU. It has so many functions build in for fast easy programming. Yes, everything on a computer runs on the CPU, but that is not how I would think of JS as functioning. The languages you are used to compile to machine/byte code that is literally in direct interface with the CPU in an efficient manner. Think of Javascripts' "CPU" to be the browser it is running in. It is not "compiled" making it VERY difficult to efficiently check for errors in the code. You distribute it as source and unlike cross-platform languages that compile to byte code run on a powerful processor, it is run by the browser. This makes it very powerful insomuch as your code can execute on ANY platform with a web browser. However, you must respect that comes with limitations. Do not think you can use your C++/Java "tricks" to make elegant JS code.
JS was never intended to make desktop applications the way C++/Java are. It's (original [probably open to debate]) propose is to modify a web page. Well it is possible to make an entire web based application with Javascript, you do not need to. You are free to make server side back ends in anything you wish. Use JS for what it is GOOD at. You wouldn't make a Java applet to just change the background color of a web page, but JS does it quickly, efficiently, and elegantly. Because that's what it was designed to do.
I know this is probably not what you would like to hear, but I'd suggest simply learning JS in the same way that you learned your first language. Drill down into the APIs and explore what is possible. Learn "new" tricks. Truly amazing web pages can be build with it, but you can't bring the mentality of a web page being just the same old GUI front end to your application. Will you need to do "real" logic in JS for a web page? YES. Remember though that your logic is being processed by a web browser with a limited API and not a full fledged operating system. By remembering what the language was designed for it will be easier to understand it's limitations and what it should be used for.
In the current day programing world it is easy and fluid to mix different languages. If you really CAN'T get your head around doing logic in JS, just learn to write your interface in it. Use a back end. JS is not like the languages you are used to because it wasn't designed around the same mentality. Learn it for what it is and do what you can with it. If it ends up being too much for you just use a CMS for your web development, Joomla or Drupal. Let them handle the dirty work and program in the way you are used to. HTML5 et al. may be the future of the web, but other methods will be around for a long time. Maybe you should just wait to pick up JS until someone develops a way to give an IDE the tools you are used to. It's not like you will be "out of a job" because you can't write an HTML5 page from scratch, there are ways around it; many of which people have discussed in this thread.
Yes it's a definitely a balance. I actually miss the a++ feature in python. It trades brevity and expression for some (minor) readability and newbie friendliness. In the case of lambdas I simply personally favor the readability of the JS solution in front of the Python brevity. Probably a lot due to allowing multi line lambdas also (which is of course another subject if it's good or bad by itself). Attempts to compress useful code down to a one liner often ends up with very hard to read code.
In any case I'm not trying to say the JS solution is overall better. Just simpler and easier to read.
"Easier to read" is wholly subjective. In my eyes, the following:
xs.fold((x, y) => x + y);
is way easier on the eyes, and hence easier to read, then:
xs.fold(function(x, y) { return x + y; });
which has a lot of syntax noise that only distracts from the actual operation that is being performed here (i.e. fold with +).
For multiline lambdas, yes, the difference in syntax is not as important. Though multiline lambdas in JS are usually either event handlers (which are usually better made named functions); or else you're doing async programming with callback chains, which is better done using a language feature that unrolls regular code into CPS, a la Python's "yield" or C# 4.5 "async/await".
As an experienced SE first learning javascript start by figuring out how to implement base classes and inheritance such that you can new up an array of child instances and modify one without affecting the others or the base. Once you've mastered that then throw that concept out and realize that javascript is not the appropriate place for such code.
Javascript is a browser-based language intended for use in manipulating documents. It will do more but don't do that; it's folly. The browser environment is transitory, there is no persistent storage and a simple page reload can easily discard all the data you've just built up. You have no reliable means to maintain state (attempts to do so using URLs are monstrous to maintain by hand).
Use javascript for what it is meant for, what it's really good at: manipulating the dom. Use it to make your UI interactive and reduce page loads where it makes sense to do so (be careful not to go ajax-happy, that's no good either as managing the history page-stack can be a nightmare in itself). Once the user does something that needs to be preserved, ajaxify that on back to your backend and return some fresh chunks of dom or a new page or whatever your application calls for. Let your backend do the work and javascript handle the display/view. It's good at that and bad at everything else.
To make matters worse, javascript performs terribly. Chrome has a much faster js engine than, say, firefox or IE, but it's still very easy to tip over with too much javascript. Keep it thin.
Good luck ~
I suggest you look at CoffeeScript. It is a compiles to JS, but cleans up a lot of the difficult syntax.
shared_ptr
+1,000 me too!
GWT has really made me enjoy client side be programming again and enabled us to do some VERY sophisticated web apps. As for the GUI widgets and layout abilities, yes, they are a little weak. But throw in a professional widget library like ExtGWT (aka GXT) from Sencha and you're golden - it's a GWT implementation of their very popular ExtJS library.
Ruby is Smalltalk meets Perl, really, it's not much like Haskell. You can do some functional things in it, but many nice features of functional languages like Haskell are not present. Currying, ZF-expressions, argument pattern matching, ...
I was struck by Matz's comments on Ruby when reading up on why list comprehensions never made it in.
http://markmail.org/message/agv5qlyrh2hhncuw (I can't find the original source, annoyingly)
Do you mean that the stack frame has a pointer to a memory location that's placed on the heap, and said pointer is what's captured by the closure?
No, that would be silly. The stack frame contains a structure containing metadata about the variable, including a pointer to the variable. It also contains the variable. Both the pointer and the value are pretty much guaranteed to be in L1 cache, so access to them is fast. When you retain the block, the structure and the variable are copied onto the heap, and the forwarding pointer is updated. At this point, the access has a bit more overhead (and the copy operation also adds a bit).
In this case you also only pay for what you use, but more importantly you only pay for it when you use it, not when you might use it. The caller does not need modifying if the callee decides to keep the block after it returns. The Objective-C version solves the problem in the general case, while the C++ solution places an extra burden on the programmer and introduces a leaky abstraction. I could easily modify something that took an Objective-C block to run asynchronously or use lazy evaluation. Doing the same with C++ lambdas would require modifying every caller.
It also leads to the next interesting question: how many heap allocations do you use for this?
This is a good question. Currently, we use one structure per variable (for byref, as opposed to copied, variables - immutable variables are all shoved into the block structure). There is some possibility for optimisation there, but no one is working actively on it because it's very rarely the bottleneck (unlike C++ designers, compiler writers are expected to actually profile their code before optimising it).
I am TheRaven on Soylent News
JavaScript is typically used in client-side web programming like you mentioned, but there have been many other applications of it. Since you're a Java programmer, an interesting exercise may be to try and write some JavaScript to run on the JVM. Java 6 includes a customized version of Rhino as a Java Scripting API (JSR223) engine for JavaScript. You can invoke JavaScript from the command line using the jrunscript command that's now part of the JDK. I've been toying around with this just to learn the JavaScript language. Just to warn you, dealing with Java's method overloading and reflection can be painful in JavaScript.
>However, writing a little script in JS is like having awesome sex compared to doing the same 'three-liner' in C++ which is like masturbating with a cheese grater in comparison. And still uses 30 lines.
I'm assuming you are speaking from actual experience here
Coming from rigidly structured languages, you're going to have a hell of a time with JS.
I hate JS's fucking type system. It's inconsistent and awkward to use. It's approach to Object Orientation is mind boggling; the syntax is awful. Every time I want to use JS's OO facilities I have to look up a guide because it's so counter-intuitive, especially coming from a C/Java background.
Luckily, JQuery soften the sharp sting of having to develop JS. I use it every day and I don't know what I do without it.
I highly recommend the Crockford videos (esp. Google IO one). They tell where JS comes from and what it's good and bad parts are. I started there after being a DITW systems guy, but now I love JS. Or more precisely, I don't love it, but I enjoy it, and it's doing good things for me.
Try a OO / inheritance approach using prototypes. Relish the flexibility of FAFCOs and learn closures. Fast. Trust me you need closures to maintain scope. Once you crack prototypeOO and closures, you can organize your code and write anything.
Also, if you're serious about not getting side tracked by HTML/CSS layout weirdness, use canvas. It gives you explicit control over your UI using a few simple primitives.
Tools like jslint are always good
http://www.jslint.com/
I find JavaScript's weak typing and dynamic nature difficult to adapt to because I'm so used to strongly-typed, compiled languages with lots of compile-time error-checking and help from the IDE.
I would recommend a re-acquaintance of the Scientific Method.
http://www.xul.fr/en/ is a good starting point for old timers like us
Casteism
I've replied to a comment earlier, but I'd like to give a big thumbs-up to the Chrome Dev Tools.
The Chrome tools are great to work with and at least as powerful as any of the other browser tools -- as this blog post shows.
If you haven't used them for a while, I suggest you give them another try.
(Full disclosure -- I work for Google.)