4 Ways JavaScript Has Changed the Way I Code

By  on  

The plot: I started teach myself web programming ten years ago; about three years ago I became infatuated with JavaScript and its practices. The bad news: in teaching myself I developed my own bad habits. The good news: my time with JavaScript and the MooTools team has opened my eyes to a better way of coding. Here are a few ways JavaScript has helped me to become a better programmers.

I Want Everything to be an Object (Screw You PHP!)

Before my love affair with PHP, I was content with using static functions for everything. I had no problem with:

$result = explode(';',$text);
echo $result[0];
//or....
list($title,content) = explode(';',$text);
echo $title;

Now I vomit every time I have to code something like that. I love that JavaScript's "everything's an object" philosophy allows me to quickly string together a billion operations:

var myText = $('myElement').getFirst('a').get('text').split('.')[0].replace(' ','-');

JavaScript FTW!

I CamelCase (Screw You Underscore!)

I generally try to conform to the philosophies of any language when it comes to naming variable and functions. While many would argue PHP can't make up its damn mind about such matters, I would say PHP's standard is the underscore. Since I've coded so much JavaScript over the past few years, I've come to prefer camelcasing. Same readability, a few less characters.

JavaScript FTW!

Same-Line { for Functions (Screw You Pascal!)

My first inclination as a n00b programmer when it came to braces was that they should be given their own line:

function my_function($x)
{
	if($x) 
	{
		//..stuff
	}
	else
	{
		//..stuff
	}
}

I probably thought that the extra whitespace made the code easier to read. Now I'm just annoyed with beginning braces having their own line. Seems like a waste of space.

JavaScript FTW!

I Require Frameworks (Screw You Vanilla PHP!)

Remember the days when people would scour the web for JavaScript components and hack together their website? I recently ran into a company that did that. Sick. Frameworks like MooTools make coding a billion times faster. Your code becomes more consistent and many components are in place for you. Working without a framework is like going into a brothel without protection.

JavaScript FTW!

So that's how JavaScript has changed the way I code. Am I missing something? Have a similar experience? Let me know!

Recent Features

Incredible Demos

Discussion

  1. I want to run my PHP code (or any backend programming language) directly from Firebug Console input.

  2. You sound like a ripe candidate for learning some Ruby on Rails….except for the underscore thing. That’s convention.

    so my_method instead of myMethod……

    However, you get to skip out on ( )’s mostly, { }’s as method wrappers, and semi-colons entirely.

    Win-win if you ask me….

  3. @Lim Chee Aun: Ruby has the IRB console……where you can directly manipulate your data/app. It’s the same running app as the actual site, just w/out the view layer in MVC.

    Haha, RoR FTW!

  4. @Tim Novinger: I had started learning RoR but got sidetracked by a few things, like fun, chicks, and the desire to code in a server-side language that isn’t known for being painfully slow. Hahaha.

    In all honesty I’ll probably start back up again soon.

  5. jared

    1. If you want a one-liner in PHP: $result = array_shift(explode(‘;’,$text)); If you want some object-based, just write something to augment the language.

    2 and 3. I suggest you write your own coding conventions for different languages you use. It would make a good article anyway. =) Here are some good places to start:
    http://pear.php.net/manual/en/standards.php
    http://docs.jquery.com/JQuery_Core_Style_Guidelines

    4. Frameworks make development on any language simpler – at least that’s the goal.

  6. jared

    @Lim Chee Aun: http://codepad.org/ is a good way to test out PHP or other languages.

  7. I’m not quite sure why JavaScript wins the “Same-Line { for Functions”.

    I have never-ever used a single line for curly brackets.
    Not in PHP.
    Not in Javascript.

  8. I totally agree with your first part. Same here. Learning by doing seems to me one of the best teachers. Including all the faults beeing made on this way.
    And getting in trouble, there are thankfully allways articles like yours, getting me out. Thanx.

  9. bml

    Having used both extensively, I have the exact opposite preferences. To each their own I guess.

    I prefer underscores over camelCase, and I have yet to use a PHP framework, but I have had to use tons of JS frameworks. I don’t want everything to be an object. EJS makes me like JS a bit more, but I still vastly prefer PHP.

  10. I’m the same, only with Java not Javascript. I hated Javascript when I started, now I love it.

    It most definitely is possible to Object-only with PHP.

    Also PHP without Smarty is hell.

  11. Lorenzo S.

    @Lim Chee Aun: Run PHP code fomr the Firebug console input! XD It would be orgasmic!!! Anyway, do you know FirePHP? It lets you debug (output) text, variables, array and objects in the Firebug console…

  12. Dave, you’d love Ruby, why did you quit?! Javascript sometimes bothers me because it’s not more like ruby. Semi colons, brackets? Who needs ’em? Anyway …

    As for camelCase v. underscore … sometimes camel case is harder to read:

    navElementDoubleClickAfterShowHandler
    nav_element_double_click_after_show_handler

    But generally I stick to camelCase in javascript like you unless my variable name is super long.

    As for php … great language, no doubt, but when I crack open a php application after working in mootools or ruby for a while I think “Holy crap, who threw up on my screen?” for the first 2 minutes. But then I get over it and really don’t mind the language at all.

  13. JavaScript is pretty cool, but have you guys heard of JScript?

  14. @Timothy: No, but I loooooooooooooove me some VBScript.

  15. Michael K.

    hmmm, interesting even if I think the whole post is directing more into a “I prefer this over that” than into “this is better than that cos….” or maybe I (simply put) got the whole thing totally wrong. However, it reminds me a bit of the “Apple” vs. “Microsoft” battle discussions somehow ;)

    1. I Want Everything to be an Object
    Is it now the “one liner” or is it the “THE” Object you are referring to? As I don’t see much difference between echo $result[0], $result[‘whatever’] and $result->whatever but I do see one when it comes to code lines, but there are a some ways to put everything into one line as well (@Jared) – I guess it’s a individual chioce.

    2. I CamelCase
    LOL, Ohhh what a perfect world it would be if I could stick to one – or the other… (Zend Framework Naming Conventions) I actually don’t really care but prefer the underscore as it’s easier to read – as far as I can tell – but again, more or less an individual choice.

    3. Same-Line { for Functions
    ok, this is where I totally go crazy – YES, I’m wasting space and I’m wasting it BIG see below ;)
    _getParam(‘error_handler’);
    ….

    4. I Require Frameworks
    Me too but I can’t remember who was first, JS or the PHP Frameworks (like CakePHP, Zend) but I know for sure that TOPSYS was one of the first out there… errr, god I’m getting old… it was around 1990.

    One quite important thing you forgot to mention is the combination of a frameworks in conjunction with MVC: it makes team development possible on a really professional level and is cheaper for the customer… cos’ you don’t have to re-invent the wheel again ;)

    Cheers,
    Mik

  16. Michael K.

    ups, some code lost on the way…

    class ErrorController extends Zend_Controller_Action
    	{
    	
    		//=========================================================================================
    		public function errorAction()
    		//=========================================================================================
    		{
    		
    			$errors = $this->_getParam('error_handler');
  17. I too love JavaScript.

    However none of your examples of your love are really due to JavaScript itself. Your love is just in the way you are using it.

    This line you gave for example:

    var  myText = $('myElement').getFirst('a').split('text','.')[0].replace(' ','-');
    

    This sort of method chaining is an API design choice with jQuery/MooTools. Several other JavaScript libraries don’t do this (YUI2 for example) and the method chaining design an be done in many other languages including (probably) PHP with classes and methods.

    Camel case and curly brackets are also just a ‘style choice’ and you could make the same choice in nearly any language if you wanted to.

    I’ll have to STRONGLY disagree with your opinion that curly brackets on the same line are a ‘waste of space’. They make code substantially easier to read. You can easily see where code blocks are, what they belong to and when they begin/end.

    Putting them on the same line just to ‘save a line’ is a bad practice in my opinion, it makes the code much harder to follow.

    I could find millions of programmers who swear by brackets being on their own line. Likewise you could find millions who swear by brackets being on the same line as the loop or function definition.

    It would be interesting to see demographics on these two camps :)

  18. emehrkay

    My favorite js feature is prototyping. How I wish php had this

  19. Claudio Ferreira

    I agree on most topics. But what about events, function as objects/parameters and code brevity? I guess I’d like to see imports in JS for dependencies. It seems Moo 2.0 will bring us something like that!

  20. php -a …in command line is the closest you can get to firebug console in php :)
    i wish php was more like javascript …hope to replace it some day

  21. Eric

    Method chaining isn’t because “everything is an object”, your example works well with jQuery but not in all JavaScript cases. Bracket placement has zilch to do with the languages used in your examples (PHP vs JavaScript). There are a ton of great PHP frameworks, what does using a framework have to do with JavaScript? Yeah, jQuery rocks and should be renamed “JavaScript” and “JavaScript” called “this old kinda clumsy thing that gave us jQuery”. :) But, still, frameworks aren’t a JavaScript-only thing. Google ‘Java Framework’ and put on a couple thousand pots of coffee.

    For those wanting FireBug + PHP, have you played with FirePHP? It kinda rocks. While it’s not exactly possible to do the same in-line edits since PHP isn’t client-side, it’s a great great addition to the dev suite.

    Oh, yeah, and I agree: brackets should never have their own line!! Any other way is insanity!!! Religious war FTW!

  22. “Same-Line { for Functions” has nothing to do with “JavaScript FTW!”, that and camelcase/underscores are aesthetics and naming-conventions.

  23. 1. PHP IS OBJECT-ORIENTED LANGUAGE.
    2. You can write your functions and classes with camel case.
    3. Same line thing.. well PHP is MORE flexible than JS with coding conventions. (in some cases)
    4. There is a shitload of frameworks for PHP? I would say also SCREW vanilla JavaScript…

  24. Dean

    +1 @Hudson – sounds to me like some of us need to learn the languages we’re using properly.

  25. @Tim Novinger @jared @Lorenzo S. @xrado @Eric Thanks! I know those tools, but perhaps I’m just ranting :P

  26. Hey David, do you know what happen to Mooshell on MooTools? :(
    If you look into the blog there’s all iframe from mooshell broken. Could you advise someone of the community about that?
    Nunzio

  27. @Hudson: PHP is not Object Oriented, it is “object capable”. I love this post about it: http://michaelkimsal.com/blog/php-is-not-object-oriented/

  28. Caligula

    @Michael K.: A JS or PHP web framework in 1990?

  29. @WouterToering: Amen.

  30. I really do agree on everything – or almost everything, like “where does it come from”. I started namingThingsLikeThat and requiring a VERY strict object model while learning Java. But POO should just be a thing to learn on every programmer-to-be’s way I guess. The same with spaces : within a few years you just get used to some patterns, and you don’t need to have that much space left.

    I just came across another trick, which was intended for css at first i think. In css it makes code look like this :

    #some-id{
      background:#ccc}
      #some-id li{
        background:#666}
    

    I just love this nested-look-alike stuff. In js it becomes :

    var main={
      someArray:[
        new Stuff(),
        "dont read please"],
      someFunction:function(){
        just.do(this)}};
    

    This way eack line has a a meaning, and a single one. Love it too.

    I’m also very fond of frameworks, but it becomes kinda just harder do deal with stuff you don’t have a framework for (recently trying various stuff with svg and textNodes’ default behavior).

    Last thing I’d say : javascript also changed my behavior in a “bad” way. I used to think “strict language is the only way to go” and look at me right now. I don’t even need to name functions anymore. I’m wild.

  31. mahdi

    I do prefer this way of functions
    if it is one line

    function test(){ echo “this is a test”; }

    function test(){

    echo “this is a test with two line”;
    retrun true;

    } /*

  32. Michael K.

    @Caligula: naaaa, it was not a PHP or JS Framework. TOPSYS (TOols for Parallel SYStems) was “an integrated tool environment for increasing programmer productivity” which then was called “a framework” as it combined most of the things that make a framework, a framework ;)

    This is a part of the abstract to the project description:
    “The TOPSYS tool environment offers tools for specification, mapping, debugging, testing, performance analysis, graphical program animation and dynamic loadbalancing of parallel programs. In addition to these tools a distributed operating system kernel and a synthetic workload generator has been developed. Apart from the integrated hierarchical architecture, the major features of the TOPSYS environment are the support of different monitoring techniques, easy adaptability, high portability and a common graphic user interface for all tools.”

    In the good old ’90s we thought that the only way to increasing computing performance efficiently was to build parallel systems – like todays server farms; nothing else than one, big parallel system ;) but it appeared to be easier to build those systems i.e. hardware then to use them. This “Framework” was the first available collection of tools (officially, as I’m sure that Microsoft, SUN or Apple ect. had developed their own) on the market for code developers – it simplified and speeded up usability and programmability.

    Btw. TOPSYS was open source long before the term “open source” was defined ;)

  33. Arian

    You can make PHP kinda Object Oriented

    For example String:

    class String {
    
        protected $_string;
    
        public __construct($string){
            $this->_string = $string;
        }
    
        replace($search,$replace){
            $this->_string = str_replace($search,$replace,$this_string);
            return $this;
        }
    
    }
    

    Then you can do:

    $str = new String('hi David');
    $str->replace('David','Arian')->replace('Arian','David');
    

    Another good example is Zend_Mail ( http://framework.zend.com/manual/en/zend.mail.introduction.html )

    But overall I agree with you. The thing I love the most about JS are closures, and how flexible they are, even compared to PHP 5.3.

  34. How about hungarian notation? I like it, however I admit that it is not entirelly usable in PHP.

  35. Bogdan

    Tried going OOP in php… then learn a framework like zend ?

  36. Braces on the same line, I think of them like colons in plain English.
    List heading:
    item 1
    item 2

    or

    function() {
    // business
    // more business
    }

    but not

    List heading
    :
    item 1
    item 2

    or

    function()
    {
    // business
    }

    if the function is short then the whole thing can easily be on the same line
    if($this_happened){/*do this simple thing*/}

    kind of like

    Question: answer

    Probably not the best explanation but what I’m getting at is that the first brace should never need it’s own line and if the function is big enough then the last one should definitely have it’s own line.

  37. Jason

    Placing braces on the same line is the preferred style for most languages (e.g., C). Personally, I prefer no braces .. yay Python and Lua!

  38. Good stuff.

    I find whitespace a pain usually, in any language.

    Chris

  39. @Hudson

    @WouterToering: http://en.wikipedia.org/wiki/Php — object oriented.
    I know wikipedia is bad argument. But anyway how about C++? is it object-oriented or not? You can write it like as procedural language. Same goes with javascript. Actually I consider PHP more traditional OOP than javascript. JavaScript objects are associative arrays.

    There is lots of good things in JavaScript and I recommend you all to watch this and 4 other videos as well:
    http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2

    JavaScript is also more strict about place of brackets than PHP.

    @Dean: Yea :)

  40. @Hudson: Yes, Wikipedia is a bad reference haha, just saying :P.

    I am not really familiar with the C languages (shame), but as C noob I consider C way more OOP than PHP, looking at the basic examples. I learned (and I believe almost everybody else too) PHP not by using Classes, but just by the basics of echo and include.

    And JavaScript, hmmz, I thought JavaScript doesn’t even have official Class support? And I never noticed anything about strictness of brackets in JavaScript, maybe I just use an awesome indention style haha.

    Anyway, I still don’t believe PHP is Object Oriented, in my opinion it’s kind a the “screw around” language, where you can try things on many different ways, getting the same result, without errors. But that’s just my opinion ;).

  41. Kirill

    Frameworks (and I mean MooTools!!). It is the reason I started using JS. Wihtout MooTools I wouldn’t even bother starting using JS in my applications because original JS is so painful to use.

  42. “I Want Everything to be an Object”

    that’s way a began to love ruby (rails)!

    ;)

  43. lossendae

    I personnaly don’t use so much undescore with PHP anymore. I like CamelCase.

    I love ExtJS :)

    I try to conform to this:
    http://developer.fellowshipone.com/patterns/code.php

  44. Dude you crack me up! Sounds like we have a very similar story in how we learned programming, and have come to many of the same conclusions!

    in ref to: I Require Frameworks (Screw You Vanilla PHP!), could not agree more!

    I am located just south of you in Rockford IL. We should get a regional MooTools/PHP/AJAX group going.

    Hit me up sometime if that sound of interest to you.

  45. makemoniesonline

    “I probably thought that the extra whitespace made the code easier to read. Now I’m just annoyed with beginning braces having their own line. Seems like a waste of space.”

    JavaScript FTL.

    Putting the brace on the same line is retarded and makes code unreadable.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!