Slashdot Mirror


JavaScript: The Good Parts

Anita Kuno writes "JavaScript: The Good Parts is about the good parts of JavaScript and how to use them. This book takes a realistic look at the strengths and weaknesses of JavaScript and tells you how to use it to its best advantage. The code samples deal with the language and its merits — creating web pages is not discussed. How to understand the language, to execute the operations you want, is the focus of the book, not how to make rounded corners. The author, Douglas Crockford says, 'My microwave oven has tons of features, but the only ones I use are cook and the clock. And setting the clock is a struggle. We cope with the complexity of feature-driven design by finding and sticking with the good parts.'" Keep reading for the rest of Anita's review. JavaScript: The Good Parts author Douglas Crockford pages 153 pages includes the index publisher O'Reilly Media Inc. rating 8 reviewer Anita Kuno ISBN 9780596517748 summary The Good Parts of JavaScript. Intended for those familiar with object-oriented programming, who understand inheritance, functions, variables, arrays, and enumeration, it identifies its audience as programmers new to JavaScript as well as those with some familiarity who wish to improve their interaction with the language. People who want to have a good relationship with JavaScript and those who wish to improve the relationship they have will find it most useful. There are lots of books and tutorials that deal with JavaScript but this approaches the language from the point of view of a survivalist.

I expect this little field guide to retain its usefulness for many years. As Brendan Eich, the creator of JavaScript, states on his blog, "What was needed was a convincing proof of concept, AKA a demo. That, I delivered, and in too-short order it was a fait accompli." JavaScript was a mock up that got a stamp of approval. His first draft became the language. I find that rather shocking. But Brendan alludes in his blog to the idea that there were many other considerations in play at the time, so the story-boarded code got the go-ahead. Crockford's book fills a niche for users explaining how to code with JavaScript and be a better programmer because of the experience.

Douglas Crockford writes in a relaxed, conversational style establishing a connection with the reader that continues through the book's contents (all 100 pages) and the five appendixes ( 50 pages total for the appendixes). I read the book in an evening-away-from-the-screen kind of mood and only followed one piece of code as outlined in the book. The book is approachable with a cursory acknowledgment of the code and it is also informative with a detailed examination of said code.

Special mention goes to Chapter 7: Regular Expressions. There are some topics which are so complex that other authors either skip over them, or use so much jargon as to render the effort useless. Douglas Crockford gives a guided tour of a regular expression designed to parse a url and it is intelligible and informative. He identifies the shortcut he uses in his regular expression code and acknowledges the risks he accepts by using it. I found his twelve and a half pages on regular expressions gave me a reasonable introduction to the subject.

He uses quotes from Shakespeare as an icebreaker for each chapter and appendix. The book contains code snippets and some recipes for adding your own functions and methods which Douglas feels should have been in the language and aren't. This I find to be a very interesting feature of the book. Like the staples for a good kitchen: ganache, bechamel, mirepoix; Crockford identifies the staples of a scripting language and gives the reader the recipes for the features that JavaScript doesn't have; .integer, .trim, and .curry (which allows the creation of a new function by combining a function and an argument).

One of the things that is missing from this book is the DOM (the Document Object Model). I couldn't be happier about that. Every other reference I have approached mashes JavaScript to the DOM so fast that as a newcomer to the language I thought that aspects of the DOM were properties of JavaScript. Douglas Crockford has an episode on Yahoo! Video talking about that very topic and it was a breath of fresh air for deciphering JavaScript. By the way, the amount of characters, in the above sentences about the DOM, is about the quantity of characters dedicated to the topic in JavaScript: The Good Parts. For me, this is a plus.

The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor. Since both are readily available in a variety of flavors and styles, I am fairly confident that every programmer wanting to learn about the good parts of JavaScript can do so.

My previous attempts to learn JavaScript had not gone well and I didn't have an understanding about why the topic was proving so confusing for me. Knowing the history of the language and the environment at its birth, I now have a better appreciation for the abilities of this language as well as a higher level of acceptance for its quirks. I understand now why I should use "var" when assigning a variable, and also why it is a good idea to conclude the line containing "return" that is followed by a block, with the left curly brace that begins the block. I didn't have the patience to accept these idiosyncrasies before and now that I know the history of JavaScript, I can see why it is a good idea to use Crockford's suggestions as a consistent coding style.

Charles Jolley suggested that I read JavaScript: The Good Parts as a basis for learning JavaScript. His tag line was: "I read it in three hours." Now, that may be an inappropriate reason for reading a book, but after spending hours and hours with various media trying to understand JavaScript, three hours seemed like a reasonable investment of time. (It took me a little longer reading at home with the occasional interruption but I still did my first pass in an evening.) The author wrote the book as an enumerable (the recipient of an action one or more times) with each reading revealing layers of understanding.

In the appendixes, there is an appendix entitled "Awful Parts" and one entitled "Bad Parts". Global variables head the list in "Awful Parts". There are discussions throughout the book about why to avoid JavaScript's default to global variables and how to do this in your coding style. The explanation, of why global variables should be avoided in JavaScript, is detailed in the "Awful Parts" appendix. Also making an appearance in "Awful Parts": scope, semicolon insertion, and reserved words. The "Bad Parts" appendix includes: == (double equal sign) which can be evaluated unpredictably depending on the circumstances, "with" which can also have unpredictable results, and "eval" which passes a string to the JavaScript compiler and executes the result. "eval" slows the result when compilation isn't required and can also compromise the security of your application. But what about its use in JSON you ask? Crockford suggests using the JSON.parse method instead of "eval". The file which creates the JSON object with the parse method can be found here. If this is of interest to you, I suggest you check the link and access the book to hear it from Crockford directly.

I find Douglas Crockford's perspective on JavaScript in JavaScript: The Good Parts to be useful in my own relationship with JavaScript. His style is accessible and intelligent.

You can purchase JavaScript: The Good Parts from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

162 comments

  1. No by Anonymous Coward · · Score: 0

    alert('no');

    1. Re:No by neonmonk · · Score: 1

      console.log('yes');

    2. Re:No by MightyMartian · · Score: 3, Funny

      document.location.href='bubblyboobsxxx.com';

      --
      The world's burning. Moped Jesus spotted on I50. Details at 11.
    3. Re:No by Anonymous Coward · · Score: 0

      document.write('perhaps');

    4. Re:No by neokushan · · Score: 5, Funny

      You have no idea how disappointed I was when I found out that web site didn't actually exist.

      --
      +1 IDisagreeSoHeMustBeATrollOrAnAstroturferOrAShill
    5. Re:No by Anonymous Coward · · Score: 0

      That's O.K, we'll just use the DNS exploit to create it!

    6. Re:No by kinabrew · · Score: 1

      function itsPossible () {
              var itsPossible = document.createElement('div');
              itsPossible.appendChild(document.createTextNode('It's possible'));
              document.body.insertBefore(itsPossible, document.body.childNodes[0]);
      )

      itsPossible();

    7. Re:No by Anonymous Coward · · Score: 1, Funny

      slashdot = {
              [...]
              humor : function() {
                      while (this.story.hasActivity()) {
                              if (joke.isLame()) {
                                      joke.recycle();
                              }
                      }
              },
              [...]
      }

    8. Re:No by Anonymous Coward · · Score: 0

      I probably should have given the variable a different name. Oh well.

    9. Re:No by clone53421 · · Score: 1

      How do you get your code to indent? I've tried and it won't work for me.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    10. Re:No by Anonymous Coward · · Score: 5, Funny

      Four spaces baby; the way God indented.

    11. Re:No by Maxime · · Score: 1

      Set the plain old text mode in the options.
      No idea how to do syntax highlighting, though ;)

    12. Re:No by ChoGGi · · Score: 1

      hello/div

  2. Filed next to "Famous Jewish Sports Legends" by Anonymous Coward · · Score: 0, Troll

    Perfect for a little light reading.

    1. Re:Filed next to "Famous Jewish Sports Legends" by stephentyrone · · Score: 1, Offtopic
    2. Re:Filed next to "Famous Jewish Sports Legends" by eln · · Score: 0, Offtopic
    3. Re:Filed next to "Famous Jewish Sports Legends" by JCOTTON · · Score: 1

      wtf? The parent should be modded troll.

  3. Maligned So It Must Be Useful by WED+Fan · · Score: 5, Insightful

    Javascript has its uses and works fine. Platforms have been the problem for me in the past. But with new libraries like jQuery, Javascript has become quite the tool.

    --
    Politics is the art of looking for trouble, finding it everywhere, diagnosing it incorrectly and applying the wrong fix.
    1. Re:Maligned So It Must Be Useful by RandoX · · Score: 4, Funny

      Why would anyone need anything other than VBScript for client-side web scripting? :)

    2. Re:Maligned So It Must Be Useful by edmicman · · Score: 2, Interesting

      Ugh....we've inherited a site that does just that. Granted, we run a classic ASP main site that uses VBScript on the server side, but I never even know there was client-side VBScript. Their whole damn website is non-functional in anything but IE...hell, they even have corresponding Javascript in some of the pages commented out, replaced by clientside VBScript!

    3. Re:Maligned So It Must Be Useful by neuromancer23 · · Score: 2, Funny

      >> Ugh....we've inherited a site that does just that.

      Hang in there trooper. Just remember that the world isn't all bad. There are still lots of people out there who care and are trying to make a difference.

      I will pray for your soul.

    4. Re:Maligned So It Must Be Useful by toriver · · Score: 1

      Me, I use Python for client-side scripting and expect people not only to use MSIE but also to have Python support (by way of ActivePython) in their computer's WSH.

      Oh I just kid.

    5. Re:Maligned So It Must Be Useful by Anonymous Coward · · Score: 0

      You, my friend, were just one colon and one right paren away from being modded into oblivion...

    6. Re:Maligned So It Must Be Useful by Anonymous Coward · · Score: 0
  4. Re:Java or JavaScript: cool? by MightyMartian · · Score: 1

    I tend to think of programming languages the same way I do hammers; they're tools to be used to accomplish a goal. That being said, I have to say I've always found Smalltalk to be a very cool language.

    --
    The world's burning. Moped Jesus spotted on I50. Details at 11.
  5. One browser? by Benbrizzi · · Score: 4, Informative

    The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor.

    You need waaay more thane ONE browser to write JavaScript. There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

    1. Re:One browser? by Anonymous Coward · · Score: 0

      I learned on top of Internet Explorer & I was recently a consultant on the development of an accredited DHTML exam.
      I know about cross browser compatibility today, but only worrying about one browser in the beginning definitely helped me pin down the basics.

    2. Re:One browser? by xactoguy · · Score: 5, Informative

      Most of those cross-browser incompatibilities are actually with the DOM model, not the underlying JavaScript implementation. While IE 5.0's implementation* had some notable bugs (String.slice() and String.substr() along with a fair bit of the assert() functionality), things are pretty compatible these days until you start using the DOM. * Opera 6 and below as well as Netscape 4 and below had some interesting quirks too, but those browsers are beyond the memory of most modern web-designers.

      --


      And so we go, on with our lives
      We know the truth, but prefer lies
      Lies are simple, simple is bliss
    3. Re:One browser? by Bogtha · · Score: 4, Informative

      You need waaay more thane ONE browser to write JavaScript.

      Not all JavaScript is intended to be executed in browsers. Server-side JavaScript was introduced a year after client-side JavaScript, and desktop scripting in JScript has been available in Windows for a decade as part of Windows Scripting Host.

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website. These are two very distinct things.

      There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

      Actually, there are very few incompatibilities between JavaScript implementations. It's the DOM that is the cause of most incompatibilities, and all the major libraries like jQuery, Prototype, etc, abstract those difficulties away. Modern JavaScript development is not a case of writing two different scripts. In fact, even without the help of libraries, that style of development was mostly obsoleted when Netscape 4 died.

      --
      Bogtha Bogtha Bogtha
    4. Re:One browser? by Anonymous Coward · · Score: 0

      The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor.

      You need waaay more thane ONE browser to write JavaScript. There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

      Not if you're using it for firefox extensions or XULRunner applications.

    5. Re:One browser? by Anonymous Coward · · Score: 0

      Well, yes and no. If you write a little Javascript this is the case, but I found out recently that if you write a LOT of Javascript it can go the other direction.

      I'm just completing work on DHTML Super Mario Brothers which is 99.9% pure Javascript on top of jQuery. Cross browser was a breeze. One tiny IE issue, but the rest of the game works flawlessly on every modern browser out there.

      Sometimes, oddly enough, the solution is more Javascript.

    6. Re:One browser? by coopaq · · Score: 1

      "waaaay... thane... JavaScript... javascript... firefox..."

      You may have some other troubles getting in the way of your consistent codebase.

    7. Re:One browser? by Joebert · · Score: 2, Interesting

      Not all JavaScript is intended to be executed in browsers. Server-side JavaScript was introduced a year after client-side JavaScript, and desktop scripting in JScript has been available in Windows for a decade as part of Windows Scripting Host.

      Not to mention applications like Adobe Fireworks, Flash, Photoshop, 7 a whole host of other applications utilize Javascript for extensions. Lookup "JSF" with Macromedia or Adobe context for more on that.
      Some Apple applications use both Applescript & Javascript too if I remember right.

      --
      Wanna fight ? Bend over, stick your head up your ass, and fight for air.
    8. Re:One browser? by Darkness404 · · Score: 1, Insightful

      Yes, but if you are going to code something, code it for Firefox. Firefox is enough standards-compliant that more strict browsers (such as Safari and Opera) can usually read JavaScript for Firefox. Leave out IE till the end, because likely it will give you more headaches then it is worth. Plus, IE is only written for 1 platform (Windows) and also, IE becomes more standards supporting with each release, but still proprietary enough to make it an absolute pain to code anything for it.

      --
      Taxation is legalized theft, no more, no less.
    9. Re:One browser? by uhlume · · Score: 3, Informative

      Of course, the vast majority of those incompatibilities are due to inconsistencies in implementation of the DOM — which the book under review explicitly chooses not to address. Take the DOM out of the picture, and the core JavaScript language is fairly consistent across all modern browser implementations. In the context of the language as covered in this book, a single browser is probably a pretty safe requirement.

      --
      SIERRA TANGO FOXTROT UNIFORM
    10. Re:One browser? by zoips · · Score: 1

      Stop confusing DOM for Javascript. They are completely unrelated.

    11. Re:One browser? by Anonymous Coward · · Score: 0, Troll

      For best development be sure and check with Firefox using NoScript. Opera with all scripting disabled etc. If the boss objects just remind him that while the majority may ignorant that not everyone is willing to do business with those that demonstrate their abusive nature by insisting on Flash and Javascript etc being enabled.

      Call me flamebait or troll if you wish, but facts are facts. It is dangerous to be so trusting and most Flash is just a waste of bandwith especially to those customers furthest from the big stores and stuck on dialup.

    12. Re:One browser? by Jack9 · · Score: 1, Insightful

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website.

      This is a red herring as webites are not the topic and theoretically you don't need a browser to develop a website at all. Simplest: yum install apache. Done. If you are going to take the comment out of context, be consistent.

      Actually, there are very few incompatibilities between JavaScript implementations. It's the DOM that is the cause of most incompatibilities, and all the major libraries like jQuery, Prototype, etc, abstract those difficulties away.

      To display anything at all with javascript requires you to reference the DOM means that they are effectively parts of the same problem. Attacking the language as opposed to acknowledging the known problem seems to be your goal. Are you really implying that because someone else has written browser specific routines, that the OP's point:

      There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

      is incorrect?

      Way to support his argument and make yourself look like an idiot. God forbid you want to use more than the Library's features or you'll have to ACTUALLY WRITE JAVASCRIPT which means you'll have to do multiple browser specific implementations (in almost all cases) and still have to stamp the site with "works best on..."

      Might want to check the source of the /. page you're reading before you spout about obsoletion of browser specific javascript.

      --

      Often wrong but never in doubt.
      I am Jack9.
      Everyone knows me.
    13. Re:One browser? by Maxime · · Score: 1

      Exactly. It's the same thing as optimization: first code something clean and standard / best practices compliant then add the smallest amount of dirty hacks to make it fast or IE compatible.

    14. Re:One browser? by herve_masson · · Score: 1

      To be more precise, I suppose you meant that there are still many cross-browser incompatibilities with DOM, CSS and HTML, not on the javascript language itself, isn't it ?

    15. Re:One browser? by MightyYar · · Score: 1

      At the very least, display an error telling me that the site only works with JavaScript enabled! I can't believe how lazy (or is it stupid?) some developers are. How long would it take to stick a piece of text in there that you immediately hide with javascript?

      --
      W..w..W - Willy Waterloo washes Warren Wiggins who is washing Waldo Woo.
    16. Re:One browser? by zoips · · Score: 1

      To display anything at all with javascript requires you to reference the DOM means that they are effectively parts of the same problem.

      You seem to be under the mistaken assumption that Javascript only executes in the browser. A lot of my one off scripting is done in Javascript which I run using Rhino, a standalone Javascript interpreter. There are many other Javascript interpreters which are not tied into the browser.

      The fact that Javascript is widely used for browser scripting does not mean that Javascript can only be used to do browser scripting. Hence it is completely valid to dismiss claims of Javascript incompatibilities between browsers when the actual incompatibility being referenced is a DOM implementation problem.

    17. Re:One browser? by Bogtha · · Score: 1

      Call me flamebait or troll if you wish, but facts are facts. It is dangerous to be so trusting and most Flash is just a waste of bandwith especially to those customers furthest from the big stores and stuck on dialup.

      Okay, you're a troll. What does checking in Firefox have to do with server-side or desktop JavaScript that isn't even designed to run in a browser? What "trust" do you think is dangerous here and what does your opinion of Flash being a waste of bandwidth have to do with it?

      --
      Bogtha Bogtha Bogtha
    18. Re:One browser? by Bogtha · · Score: 2, Interesting

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website.

      This is a red herring as webites are not the topic

      How can it be a "red herring"? What do you even mean by that? If you are talking about browser testing, you are talking about websites. I was pointing out that multi-browser testing isn't as mandatory as Benbrizzi claims because browsers aren't the only place that JavaScript is used.

      To display anything at all with javascript requires you to reference the DOM means that they are effectively parts of the same problem.

      Please go back and read my comment again, you seem to have completely missed the point of it.

      No, you don't need the DOM to display anything with JavaScript. In fact, the DOM isn't going to be much help at all if you aren't running JavaScript inside a web browser. The DOM and JavaScript are two distinct things, and lumbering JavaScript with criticism of DOM incompatibilities is ludicrous in the instances where you are using JavaScript but not the DOM.

      Attacking the language as opposed to acknowledging the known problem seems to be your goal.

      Dead wrong. If you would care to read my comment properly instead of flying off the handle you might actually see why.

      Are you really implying that because someone else has written browser specific routines, that the OP's point:

      There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

      is incorrect?

      Yes. Very few web developers need to write separate scripts for different browsers these days because of the work that has gone into these libraries.

      Might want to check the source of the /. page you're reading before you spout about obsoletion of browser specific javascript.

      Browser-specific JavaScript and separate scripts for different browsers are two very different things. Browser-specific JavaScript is mainly done with shims and helper functions these days. Back in the olden days you really did have to write two different scripts.

      --
      Bogtha Bogtha Bogtha
    19. Re:One browser? by Anonymous Coward · · Score: 0

      The intent was not to detract or disagree with what you said but to add to it. Serverside scripting is preferred over clientside. You also stated:

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website. These are two very distinct things.

      Which was the comment I was attempting to add to, from my viewpoint, apologies for my lack of clarity. Too many web pages refuse to load if JavaScript and Flash are disabled and many of those who do load, do so improperly and are unbrowseable.

    20. Re:One browser? by Tumbleweed · · Score: 1

      You need waaay more thane ONE browser to write JavaScript.

      No you don't. To simply *write* it, all you need is a text editor. Why bother testing in *any* browser, much less all the common ones. Either you're that good, or you shouldn't bother. :)

    21. Re:One browser? by Paradise+Pete · · Score: 1

      You need waaay more thane ONE browser to write JavaScript.

      You're making exactly the kind of error alluded to in the review.

    22. Re:One browser? by Poltras · · Score: 3, Insightful

      Stop confusing C# with .Net, stop confusing Obj-C with Cocoa, stop confusing C++ with STL. Stop confusing C with stdlib. Stop confusing COBOL with mainframe.

      Yes, a language and an API are unrelated, but I've rarely seen one without the other. Have you seen many javascript running outside web browsers lately? And while you are correct that you don't have to learn DOM to get into Javascript, you'll need it sooner than later, and using a coherent/compliant implementation of it is crucial in its learning.

    23. Re:One browser? by Zontar+The+Mindless · · Score: 1

      ... Netscape 4 and below had some interesting quirks too, but those browsers are beyond the memory of most modern web-designers.

      "...and get off my lawn."

      There were just so many things to hate about the 4th-gen browsers, weren't there...? Ah, those were the days. ;)

      --
      Il n'y a pas de Planet B.
    24. Re:One browser? by Anonymous Coward · · Score: 0

      How long would it take to stick a piece of text in there that you immediately hide with javascript?

      Or just use <noscript>.

    25. Re:One browser? by AchilleTalon · · Score: 1

      You need waaay more thane ONE browser to write JavaScript.

      Not all JavaScript is intended to be executed in browsers. Server-side JavaScript was introduced a year after client-side JavaScript, and desktop scripting in JScript has been available in Windows for a decade as part of Windows Scripting Host.

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website. These are two very distinct things.

      Very true, I even use JavaScript in some pieces of software completely unrelated to a browser or a web server. With Rhino and the likes, the JavaScript can be executed from about any other software, so it can provide a scripting language to extend a software and customize it to fit a specific customer need. Actually a scripting language by itself.

      --
      Achille Talon
      Hop!
    26. Re:One browser? by zoips · · Score: 4, Interesting

      Yes, I have. At my last job basically our entire test framework was written in Javascript. Why, I'm not sure, but it was. I also do most of my scripting in Javascript and execute using Rhino. If it's not going fast enough, I just use Rhino to compile it all to Java bytecode and execute it directly in the JVM.

      As I said elsewhere in this thread, just because Javascript is widely used for browser scripting, does not mean that is its only use. Your blurb at the beginning is completely irrelevant to this topic.

    27. Re:One browser? by spectre_240sx · · Score: 1

      Actually, I do a lot of Windows scripting in JScript. WSH may not be the nicest environment in the world, but once you dump VBScript it gets a bit better.

    28. Re:One browser? by Cajun+Hell · · Score: 1

      I suppose you meant that there are still many cross-browser incompatibilities with DOM, CSS and HTML

      Don't forget the event handler. It's not even about IE vs FF. It's like IE does things one way, and every single browser on the fucking planet does it another way, and they're all compatible with each other. IE is the one black sheep of the web world. VIC20s will have good browsers before Microsoft makes one.

      --
      "Believe me!" -- Donald Trump
    29. Re:One browser? by Anonymous Coward · · Score: 0

      I'm just completing work on DHTML Super Mario Brothers which is 99.9% pure Javascript on top of jQuery.

      Just because you can do something doesn't always mean you should.

    30. Re:One browser? by Jack9 · · Score: 1

      The fact that Javascript is widely used for browser scripting does not mean that Javascript can only be used to do browser scripting.

      I understand that. I don't see why that matters. To whit:

      The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor.

      The original quote makes no mention of serverside scripting, it makes mention of a browser. Therefore any reference to javascript is assumed to be executed within a browser. The points summarized were:

      The article makes a bad assumption about needing 1 browser.

      Response, 1 browser is insufficient nowadays.

      Response, you dont have to use more than 1 browser if you use an OO library and you need more than 1 browser only if you're making a website.

      My response, you'd have to be an idiot to believe that since the OO library has browser-specific implementations that may or may not be equal and if you're going to be literal about only needing 1 browser to write javascript (which you arent even doing anymore if you only use an api), then you dont need a browser at all for javascript or a website. Javascript requires knowledge of a browser's DOM implementation to display anything.

      Your response, you don't need a browser for serverside javascript or for displaying anything using javascript.

      I concede your point, since it has nothing to do with what I was talking about.

      --

      Often wrong but never in doubt.
      I am Jack9.
      Everyone knows me.
    31. Re:One browser? by rossdakin · · Score: 1

      Exactly correct. If you stick to the standards, JavaScript itself should run smoothly cross-browser. You run into trouble with small things like trailing commas in lists and other examples that xactoguy mentioned. The big cross browser inconsistencies are with the DOM, which is arguably very popularly tethered to JavaScript in practice, but is really just a nail to the hammer. The hammer can hit lots of other stuff too.

    32. Re:One browser? by deniable · · Score: 1

      Amen to that. Another weird data point: JScript has a built-in sort. The last time I checked vbscript didn't.

    33. Re:One browser? by Anonymous Coward · · Score: 0

      what about IE3? It's "Jscript" implementation was an absolute nightmare.

    34. Re:One browser? by IbnSlash · · Score: 1

      I hate IE more than anyone here, but gotta disagree with you. If you are going to code for one browser, code for IE. It still is the most widely used browser in the world, whether one likes it or not.

    35. Re:One browser? by Bogtha · · Score: 2, Informative

      The original quote makes no mention of serverside scripting, it makes mention of a browser. Therefore any reference to javascript is assumed to be executed within a browser.

      How do you propose that web developers test server-side scripting? Telnet to port 80 and type the requests by hand?

      Yes, you want a web browser when you are writing server-side JavaScript. No, that doesn't mean that it is executing within a browser.

      Response, you dont have to use more than 1 browser if you use an OO library

      I never said that at all. I disagreed with the assessment that cross-browser JavaScript incompatibilities require developers to write two different scripts, and I said that part of the reason for that was the availability of libraries that mitigate the problems with the DOM.

      if you're going to be literal about only needing 1 browser to write javascript (which you arent even doing anymore if you only use an api)

      Using an API means that you are no longer using the same language? Now you're just being silly. You aren't arguing because you think you are right, you are just arguing for the sake of it. JavaScript is JavaScript regardless of whether you access the DOM directly or make use of a library. Besides, the DOM is an API, so by your logic, it's pretty much impossible to write JavaScript to execute in a browser at all.

      Javascript requires knowledge of a browser's DOM implementation to display anything.

      WScript.Echo("No it doesn't.");

      <%@LANGUAGE="JavaScript"%>
      <%
      Response.Write("It really doesn't.")
      %>

      --
      Bogtha Bogtha Bogtha
    36. Re:One browser? by Bogtha · · Score: 1

      Don't forget the event handler.

      He didn't. The DOM includes events.

      --
      Bogtha Bogtha Bogtha
    37. Re:One browser? by POWRSURG · · Score: 1

      This is correct. It's been my experience that the only non-DOM related area that still has a great deal of cross browser incompatibilities is in the area of WYSIWYG editors. True, every browser supports the ability to turn on designMode, and Firefox 3 finally meant that every browser can enable contentEditable, but how the different browsers handle the editing process is completely incompatible with one another. Firefox seems to love to insert br tags in many situations. IE seems to actually handle hitting enter/return the most sensibly IMHO. That's the only thing I'll say that for in regards to WYSIWYG editors, because beyond that it is horrible. Generating font tags by default with no alternative but to ignore the browser specific functionality for most features, completely ignoring the W3C model for Ranges/Selections for their own proprietary TextRange/Selection objects, and other non-trivial headaches. IE's Text/Range/Selection issues give me the most trouble, as I often encounter DOM related bugs with them as well.

    38. Re:One browser? by HaMMeReD3 · · Score: 1

      Also, may I note that knowing the patterns expressed in the book (I've read it as well), will help you significantly in tackling cross-browser problems. Also, it was a design flaw in a way to make JavaScript look C/Java style, because it's not, and there can be confusing scope and oop behaviours that would be unexpected to an unexperienced programmer. I know I've been programming JS for years and I've ran into weird bugs I could never explain until I read through this book.

  6. Just the good parts by RandoX · · Score: 0, Troll

    So... it's a blank note pad with a different cover?

    1. Re:Just the good parts by Gat0r30y · · Score: 1

      It is a very short book (I actually own it). However, if you have to use JS - it is an excellent resource. There is a section on the Bad Parts too - there isn't much detail in the Bad Parts, but it is still a hefty portion of the book.

      --
      Prediction: The real iPhone killer is going to be sex robots from Japan. Think about it.
  7. the only problem with javascript by circletimessquare · · Score: 4, Insightful

    is its neigbhorhood, where it is used. you spend 90% of your programming time dealing with the quirks between different browsers. ie isn't even the biggest offender, safari is

    which is to say, there is nothing wrong with javascript. it a diamond trapped in a cage made out of shit

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
    1. Re:the only problem with javascript by MightyYar · · Score: 1

      ie isn't even the biggest offender, safari is

      Depends on whether you are developing on Safari or on IE, doesn't it? :)

      I actually use Firefox for the initial development and then test/fix for the others. Since I've started using jQuery, I spend a lot less time fixing stuff between browsers.

      --
      W..w..W - Willy Waterloo washes Warren Wiggins who is washing Waldo Woo.
    2. Re:the only problem with javascript by appleprophet · · Score: 2, Informative

      Safari (actually, I believe you mean WebKit) is the biggest offender? +4 insightful? Are you fucking kidding me?

      I'd like to see an example of what you mean by offensive, because WebKit is the most standards compliant browser in existence. Internet Explorer is less offensive than Safari? Give me a fucking break.

      Every commit in WebKit causes the JavaScriptCore code base to run thousands of regression tests, including FireFox's. These test virtually every aspect of JavaScript, including specifications that IE does not even support yet! If there is a single regression, the commit is rejected.

      I know you are talking out of your ass, but shit like this really pisses me off for some reason. The hundreds of developers for WebKit deserve better.

    3. Re:the only problem with javascript by Pollardito · · Score: 3, Informative

      IE is undoubtedly worse than Safari and its cryptic error messages when something doesn't work are a big reason not to code anything in IE first, but Safari has had it's issues. It used to be that you could not change the value of a radio button control with JavaScript in Safari. I remember implementing a page that had an extra hidden variable for every radio button that I wanted to have an editable value just because of this particular problem. There are some quirks when reading back values that you've written into an innerHTML (all HTML tags come back capitalized and any HTML comments that were in the string you wrote into the value come back stripped out), but I doubt that is something that many people have run into.

  8. Reminds me... by Shaitan+Apistos · · Score: 4, Funny

    ...of a t-shirt I saw once, it read "But what about all the good things Hitler did."

    In all seriousness though with Prototype I don't find javascript browser inconsistencies nearly as problematic as css browser inconsistencies.

    1. Re:Reminds me... by Tumbleweed · · Score: 2, Interesting

      In all seriousness though with Prototype I don't find javascript browser inconsistencies nearly as problematic as css browser inconsistencies.

      Yeah, wait until you start using javascript to manipulate css, the you get the best of both worlds (of pain).

  9. I'm coming out by StonedRat · · Score: 1

    I love JavaScript :)

    Am I a crazy mad man?

    --
    "Religion is the most malevolent of all mind viruses." - Arthur C. Clarke.
    1. Re:I'm coming out by Anonymous Coward · · Score: 0

      I love JavaScript :) Am I a crazy mad man?

      Most likely just inexperienced.

  10. Re:Java or JavaScript: cool? by alexgieg · · Score: 1

    Since when is ANY programming language "cool"?

    I myself don't find JavaScript cool, but I couldn't say the same about Prolog, Forth or LUA. On top of that, INTERCAL and LOLCODE also manage to be funny. ;-)

    On a more serious note, if you can "feel" something as uncool, others can feel them as cool. Feeling nothing translates into perfect indifference. And since you posted a comment, your post itself is proof that inanimate tools do cause emotions and sentiments, your own words notwithstanding.

    --
    Conservatism: (n.) love of the existing evils. Liberalism: (n.) desire to substitute new evils for the existing ones.
  11. Re:Java or JavaScript: cool? by QuoteMstr · · Score: 1

    And Lisp: Lisp is a hammer with all the power of a jackhammer and all the artistic merit of The Last Supper. :-)

  12. Re:Java or JavaScript: cool? by ByOhTek · · Score: 1

    maybe not cool in the sense of popularity by the people world as a whole... But by that sense, not much, if anything, is 'cool'. In the popularity sense, 'cool' tends to be geared towards a culture or grouping. Be it Americans, western culture, eastern culture, Russians, British, business executives, geeks... The slang word cool tends to be used in a rather flexible manner.

    Also, it's a word rooted in OPPINION, which means SUBJECTIVE and not OBJECTIVE. That's probably related to the relative-to-grouping concept above, if you really want to ponder the semantics of it a bit more.

    --
    Self proclaimed typo king, and inventor of the bear destroying coffee table (patent not pending).
  13. Good parts? by sjonke · · Score: 1

    [html]
    [head]
    [/head]

    [body]

    [script type="text/javascript"]
    document.write("This message is written by JavaScript");
    [/script]

                    Here?
    [/body]
    [/html]

    --
    --- What?
  14. Scoping is Awful? by PipianJ · · Score: 3, Informative

    I must admit that JavaScript's method of scoping isn't the best (mostly because it has variables that can be reassigned, and scoping binds to the variables, not the values) but I can say that scoping is a time-saver if you do it right and (for example) have a bunch of anchors that all need slightly different arguments in their onclick event handlers.

    I've more than once used something like:

    function onclickGenerator(i) { return function() { doSomething(i); }; }

    var elements = document.getElementsByTagName('a');
    for (var i = 0; i < elements.length; i++) { elements[i].onclick = onclickGenerator(i); }

    It would be nice if it treated scope by binding values, not variables though... (If you tried doing the above by replacing onclickGenerator(i) with function() { doSomething(i); }, every element would end up calling doSomething(elements.length);, instead of doSomething(value_of_i_at_onclick_set_time);

    1. Re:Scoping is Awful? by clone53421 · · Score: 1

      Easier to read IMHO:

      var elements = document.getElementsByTagName("a");
      for (var i = 0; i < elements.length; i ++)
      elements[i].onclick = new Function("doSomething(" + i + ");");

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    2. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      You really should do
      for(var i = 0, e = elements.length; i < e; i++)

      Otherwise, elements.length needs to be re-evaluated every iteration of the loop.

    3. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      To be clear, parent is comparing lexical to dynamic scope.
      The above silly example, is an example of not taking advantage of block structure.

      If you write everything as if it were a C program, yeah, lexical scope can be weird.

    4. Re:Scoping is Awful? by larry+bagina · · Score: 3, Informative
      Ick. Requires an eval. What if you need to pass a string or an object?

      Extend function.prototype a bit:

      bleh.onclick = doSomething.bind(null, {one: 1, two: 2});
      bleh.onclick = doSomething.curry("...");

      (also, you should use level 2 events, but that's another issue).

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    5. Re:Scoping is Awful? by Anonymous Coward · · Score: 1, Interesting

      Easier to read IMHO:

      elements[i].onclick = new Function("doSomething(" + i + ");");

      No. You should never use "new Function()" for anything. You'd be better off using a closure.

    6. Re:Scoping is Awful? by PipianJ · · Score: 1

      To be clear, parent is comparing lexical to dynamic scope.
      The above silly example, is an example of not taking advantage of block structure.

      If you write everything as if it were a C program, yeah, lexical scope can be weird.

      My apologies. I suppose I'm confusing my closures with scoping, but the way closures are done in Javascript belies the fact that it doesn't have single-assign variables.

    7. Re:Scoping is Awful? by PipianJ · · Score: 1

      All Prototype's bind does is hide the fact that it's creating and calling a generator function anyway... It still fundamentally has to wrap the function in a closure-generating function because JavaScript doesn't have block scoping.

      By the way, if you like level 2 events, I hope you don't have any clients using IE!

    8. Re:Scoping is Awful? by clone53421 · · Score: 1

      Requires an eval.

      Ok, but it happens once. Not too bad a performance hit unless you have a ton of links. As I said, I think my code is easier to read and figure out what it's actually doing.

      What if you need to pass a string or an object?

      I'm not coming up with any idea of an example that would require that, but I'm sure if I had to I would make it work. Probably I'd put the string or objects that I needed to use as arguments into an array and then they'd be referenced by an integer like in the previous example. (Most likely the purpose of passing i in the example was because doSomething() needed to refer back to the clicked element, document.getElementsByTagName("a")[i], so it's already passing an object as an index of an element in a known array. Now that I'm thinking about it, that would have been more easily accomplished using (event.target ? event.target : event.srcElement) anyway.)

      Oh, and I tried to indent. It took it out. /. just doesn't like me; I've tried &nbsp; and it simply refuses to leave them alone... hence my question above...

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    9. Re:Scoping is Awful? by aasm · · Score: 1

      That's because {} in javascript doesn't create scope, so you're always capturing the same lexical scope (the same /i/ variable) when creating a closure inside the for, that's why /i/ has the .length value, if you do "i = 0" after the for you're changing also the /i/ captured in the closures you've created because it's the same variable. the only thing that creates a new lexical context in javascript is a function call so you can alternatively write:

      for (var i = 0; i < elements.length; i++) { (function(i) {
              elements[i].onclick = function() { doSomething(i); }
      })(i) }

    10. Re:Scoping is Awful? by lyml · · Score: 1

      No, we left the limitations of C 20 years ago.

      Try to keep up with the times.

    11. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      I suppose you have a good reason?

    12. Re:Scoping is Awful? by Achoi77 · · Score: 1

      You really should do for(var i = 0, e = elements.length; i < e; i++)

      Otherwise, elements.length needs to be re-evaluated every iteration of the loop.

      isn't being evaluated there anyways when it's assigning it to e? How about something like

      for(var i = 0; var e = elements.length, i < e; i++)

    13. Re:Scoping is Awful? by larry+bagina · · Score: 1
      or:

      Array.forEach(elements,function(e, i){
      e.onclick = function(){doSomething(i); }
      });

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    14. Re:Scoping is Awful? by shutdown+-p+now · · Score: 1

      In a language with mutable variables, closures always bind to variables, not to their values, by definition (since the environment that is closed over consists of variables). I think it has been the case at least since Scheme.

    15. Re:Scoping is Awful? by incripshin · · Score: 1

      How to make pretty code on slashdot: Formatting must be "Plain old text" (I know, it's hardcore to use the HTML option, but you cannot format your code properly). Then, enclose your code in an ecode within a tt. Last, you don't need to write &amp; instead of &, &lt; instead of <, etc, with ecode. It is, however, necessary when using <code> for inline code. Here's what you end up with:

      int main(int argc, char **argv)
      {
          if (argc & 1)
              printf("even args\n");
          else
              printf("odd args\n");
          return 0;
      }

      I think this is a problem with any language with lambas. I tried my own implementation storing the indices in an array, which I can recall doing with SML. Then I tried doing this:

      for (var i = 0; i < elements.length; i++) {
          var t = i;
          elements[i].onclick = function () { doSomething(i); }
          delete t;
      }

      But the lambda is tied not to the variable identified by 't' (a hard link), which is what any sensible lambda function would do. It instead is tied to the identifier 't' (a soft link). Total BS if you ask me. Thanks to everybody here for helping me to hate JavaScript just a little bit more. There is a way around using generators in this specific case, though:

      for (var i = 0; i < elements.length; i++) {
          elements[i].onclick = function () { doSomething(this.link_number); }
          elements[i].link_number = i;
      }

    16. Re:Scoping is Awful? by PipianJ · · Score: 1

      That'd be bassackwards wouldn't it? Now you've put the assignment back in the looping part, which is what we're trying to avoid.

    17. Re:Scoping is Awful? by PipianJ · · Score: 1

      Yeah, but can JavaScript really be sure that elements wasn't altered by the contents of the loop? Granted, that's a theoretical mistake on my part to not store it in a variable for that case, but in practice, I'm relatively sure it doesn't matter (seeing as we can PROVE that there is no change in the number of items in the array, assuming, of course, that setting onclick does exactly what we expect it to... But now we're getting into pedantic reasoning for sample code that doesn't even do anything!)

      That being said, I'm not entirely sure where the cost of calling elements.length comes in, unless no JavaScript engines actually keep length as a property on the array object, instead preferring to count the elements every time (or if accessing a property of an object is significantly more expensive than accessing a variable).

      I mean, come on, we're talking about a simple instance variable that just needs updating on a push or a pop...

    18. Re:Scoping is Awful? by larry+bagina · · Score: 1

      Yes, but it's easier than doing closure generation inline, or creating a function from a string. Javascript 2 is slated to have a Function.bind(function,thisp,...) function.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    19. Re:Scoping is Awful? by Achoi77 · · Score: 1

      wow, I fail at for loops

      confused my commas and semicolons, thinking that the commas seperated the 3 expressions - which doesn't even make sense, since there is only 1 comma there. Which is why I read it wrong in the first place. *boggle*

      sorry about that.

    20. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      It requires an eval and since you have other options that do not and are safer/require less overhead, why do it in the first place?

    21. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      20 years huh?

      var foo = ['one', 'two', 'three'];
      for(var i = 0; i < foo.length; i++)
      {
                      document.write(foo[i] + '<br/>');
                      foo.push('four'); //oh shit, we just blocked the browser!
      }

      Ahh..

      var foo = ['one', 'two', 'three'];
      for(var i = 0, e = foo.length; i < e; i++)
      {
                      document.write(foo[i] + '<br/>');
                      foo.push('four'); //that's better
      }

      Think it doesn't happen? It does. Although the book only discusses javascript and not the DOM, this kind of crap happens a LOT when working with DOM objects, especially if you are adding and removing children. What about updating the items in a select box? If you make changes to the original array(or whatever) in your loop and you evaluate it's length during every iteration, you end up with weird things, unless that's what you intended.

    22. Re:Scoping is Awful? by larry+bagina · · Score: 1

      In JavaScriptCore and SipderMonkey, accessing a property requires calling a function and doing a string comparison. ("length" and numbers are special cases for Array objects). I don't think the compiler/interpreter has enough knowledge to prove that the length won't change... The XMLHttpRequest properties, for example are volatile.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    23. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      I use the following:

      A = function(o){
          var a=[];
          for (var i=0; i<o.length; i++) a[i] = o[i];
          return a;
      }
      A(document.getElementsByTagName('a')).forEach(function(e,i){
          e.onclick = function() { doSomething(i); };
      })

    24. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      But the lambda is tied not to the variable identified by 't' (a hard link), which is what any sensible lambda function would do. It instead is tied to the identifier 't' (a soft link).

      Actually, it is a "hard link" in your terminology. The problem is that local variables in JavaScript are scoped to the containing function, even if they're declared in an inner block, so there is only one "variable identified by 't'" shared by the entire loop.

    25. Re:Scoping is Awful? by clone53421 · · Score: 1

      Good workaround. I hadn't thought of that.

      Yeah, the basic issue with the first way is that the function () refers to the variable t, which you're re-using. The function doesn't automatically use the current value of a global variable, because that wouldn't make sense when you did need to use a global variable in the function... if the variable changed, it'd ruin the results.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    26. Re:Scoping is Awful? by clone53421 · · Score: 1

      Since the whole language is an interpreted language anyway, I don't see much difference in using an eval or not.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    27. Re:Scoping is Awful? by Anonymous Coward · · Score: 0
      Or use:

      for (var i = 0; i < elements.length; i++) { var x = i; elements[x].onclick = function() { doSomthing(x); }

      The onclick function is called after the for loop has finished running, and i is out of scope. If the scoping was different, then you wouldn't be able to access i at all. Java's annonymous classes, c#'s delegates, and Ruby's blocks work the same way. This is not unique to JavaScript.

    28. Re:Scoping is Awful? by incripshin · · Score: 1

      But I don't think the variable should be changing. What makes sense to me is that since the scope of t is restricted, each loop should get a new variable. This way, the lambda functions would all refer to different variables. This is how Perl works, but not JavaScript or Python. I typically haven't liked Perl, but this is doing a lot to warm me up to it.

    29. Re:Scoping is Awful? by clone53421 · · Score: 1

      Javascript doesn't create a new scope within a for loop, though.

      for (var i = 0; i < 10; i ++) { var p = i; }
      alert(p);

      Alerts 9, the last value of p.

      I think the only time scope changes is in a different function.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    30. Re:Scoping is Awful? by Anonymous Coward · · Score: 0

      Your ways of programming are highly devious, Master.

  15. Re:Java or JavaScript: cool? by Anonymous Coward · · Score: 0

    And THIS is the symptom of an uber-asshole: he would rather spend his time blathering his pissy opinions

    And your post was what... an example of a helpful opinion?

  16. TiddlyWiki by yumyum · · Score: 2, Interesting

    To see some incredible (IMO) JavaScript functionality, check out TiddlyWiki.

    1. Re:TiddlyWiki by Anonymous Coward · · Score: 0

      Some of these are pretty cool too.

  17. Shortest Book Ever? by Anonymous Coward · · Score: 1, Funny

    > JavaScript: The Good Parts

    Shortest book ever?

  18. JavaScript: The Good Parts by mrroot · · Score: 1, Funny

    I can tell from the title alone that this has got to be the shortest book ever written.

    --
    I Heart Sorting Networks
    1. Re:JavaScript: The Good Parts by eddy · · Score: 0, Flamebait

      Yeah, the single line "Javascript supports C++-style line comments." can't possibly count as a book, can it?

      I guess the rest is just 'this page intentionally left blank' filler!

      --
      Belief is the currency of delusion.
    2. Re:JavaScript: The Good Parts by Tumbleweed · · Score: 1

      I can tell from the title alone that this has got to be the shortest book ever written.

      Just wait for his next book, "Microsoft Bob: The Good Part."

  19. The author's website by DCstewieG · · Score: 5, Informative

    Crockford's website has a bunch of great articles about JavaScript. I've learned quite a bit from there.

    http://www.crockford.com/javascript/

  20. Re:SLASHDOT SUX0RZ by Anonymous Coward · · Score: 0

    The creativity involved in making the link text in all of these trolls never fails to make me smile.

  21. Re:Java or JavaScript: cool? by Anonymous Coward · · Score: 1, Funny

    lithp ith for fagth.

  22. Re:Java or JavaScript: cool? by hellwig · · Score: 1

    Don't forget Python. The Python hammer functions differently based on the relationship of where your hand is currently on the handle to where it was previously. If you drop your hammer, you have to re-build your house from scratch.

    --
    Eggs
    Milk
    Bread
    Cat Litter
    Soda
    ...
  23. fuck safari by circletimessquare · · Score: 2, Interesting

    i just wrote some script to handle anchor tag clicks globally. firefox, fine. opera, fine. ie, fine. safari: doesn't work in safari, because safari insists on doing the default action no matter what

    http://codingforums.com/archive/index.php?t-30983.html

    you can't cancel dom events in safari! fuck safari. so now i have to completely write off safari support, or completely alter my programming model because of its stupidity, and do some really guly hacks

    or perhaps, no hacks possible!:

    http://www.peterblum.com/SafariBugs/CancelKeyPress.html

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
  24. Re:Java or JavaScript: cool? by QuoteMstr · · Score: 1

    Or how about the C hammer? It's a rock.

  25. browser fucking by MightyYar · · Score: 3, Informative

    Are you really required to support older versions of Safari? I only have 3.1.2 and that page that you linked to works as described - so it appears to have been fixed.

    --
    W..w..W - Willy Waterloo washes Warren Wiggins who is washing Waldo Woo.
  26. javascript/lisp connection by Phantom+of+the+Opera · · Score: 3, Informative

    Javascript itself is a relative of scheme, which is a descendant of lisp.

    It offers macros, closures and of course recursion.
    The big difference is that javascript is not list based.

  27. One sitting... by Innova · · Score: 1

    JavaScript: The Good Parts

    Must be a quick read.

  28. This best part of JavaScript is by iamghetto · · Score: 1
  29. Crockford's instructional vids by spads · · Score: 3, Informative

    Though they were the logical starting point, I am grateful to be mainly past my reliance on books. However, based on how good his videos (e.g. http://javascript.crockford.com/, http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/) are, I would consider checking this one out.

    --
    Bukowski said it. I believe it. That settles it.
  30. There isn't anything wrong with the scoping by lazyl · · Score: 1

    I recommend buying the book. Closures are implemented with the expected scoping. They allow you do to things like this:

    function createCounter()
    {
            var i = 0;
            return {
                    incr: function() { ++i; },
                    decr: function() { --i; },
                    getValue: function() { return i; }
            }
    }

    --
    Aw crap, ninjas!
  31. that example is old then by circletimessquare · · Score: 1

    but safari still does default actions. you can't globally cancel a click, for example. i can't globally take over all anchor tag actions. safari will try to follow the href link still, no matter what you do in code. its really infuriating and im thinking of just dropping safari support

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
    1. Re:that example is old then by MightyYar · · Score: 1

      Hmmm, I just tried it here:
      Sample page showing disabled a tag clicks

      Seems to work well enough, though I am using the aforementioned jQuery. Do you have a little example of what you are trying to do?

      --
      W..w..W - Willy Waterloo washes Warren Wiggins who is washing Waldo Woo.
    2. Re:that example is old then by beejhuff · · Score: 1

      This may not be the end of the world, right? If your create your links as javascript function calls, then there are no standard link click actions on a global level that you have to cancel - just the javascript function call, which you can always catch, and modify the original destination if needed.

      Not certain this will work for your particular application, of course, and there may be other drawbacks to using function calls instead of normal href links (Google and other search engines may not crawl your pages properly is one I think of off hand) but it's an option.

      I'm also not defending Safari here :) I'm just noting that if your goal is supporting all browsers, that will inevitably limit your design options in some way. Maybe there's another algorithmic track you can pursue that will satisfy your cross browser compatibility requirement?

      --
      Bryan "BJ" Hoffpauir
    3. Re:that example is old then by Fweeky · · Score: 3, Informative

      Do you have a test case showing what you're doing then? Because document.addEventListener("click", function(event) { event.preventDefault(); }, false); and document.onclick = function(event) { event.preventDefault(); } both work fine in 3.1.2 here.

  32. Alternative? by Bigbutt · · Score: 1

    I'm a hobbyist and haven't programmed professionally in quite a while but if not Javascript, what (and I'm not using VBScript)? I'm not doing gigantic web sites, but little one off tools for my Shadowrun game. I'd like to have one page for inputting numbers, calculations, and the results are posted in the last field (like a total). Is there something I can use that's more appropriate?

    [John]

    --
    Shit better not happen!
    1. Re:Alternative? by larry+bagina · · Score: 1

      you can either do it client side with javascript or do it server side with php, perl, ruby, asp, asp.net, c, etc.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    2. Re:Alternative? by Bigbutt · · Score: 1

      Really? What's the right way to do it with php on the server side?

      It's a form with say 10 fields. Field number 10 is read only and contains just the calculated value from the other 9 fields.

      If I type '3' in field 1, field 10 should immediately display '3'.
      If I type '2' in field 2, field 10 should immediately display '5'.

      And so on. I've used php to build pages, but not interact with the client.

      The idea is during combat, I can bring up the page and enter in the necessary values and pass field 10 to the attacker and field 20 to the defender. This way I don't have to look up 4 or 5 tables and combat becomes smoother.

      [John]

      --
      Shit better not happen!
    3. Re:Alternative? by larry+bagina · · Score: 1

      The form would have to be submitted, of course. You could have javascript automatically submit the form when a field changes. asp.net can do that automatically. Of course, if you're going to write javascript to submit the form, you might as well just do it all in javascript. Or a spreadsheet.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    4. Re:Alternative? by Anonymous Coward · · Score: 0

      This comment gets to the heart of why JavaScript's critics are so vocal about its shortcomings. The problem is that there isn't anything else that a developer can use in place of JavaScript. If you need in-browser dynamic behavior that works in multiple browsers, you have to use JavaScript. Period. End of discussion. Using Flash, Java applets or ActiveX plugins or a combination thereof could be made to work, but not easily and users bristle whenever they see those technologies in use.

      The problem is that JavaScript, or at least the part that can be used across multiple browsers is a pretty crappy language. It's missing packaging, support for true OO programming, threads and a whole host of things that are just really difficult to not have. The JavaScript derivative ActionScript is a half-decent language, but is only supported in Flash. As a result, there's a hundred or so JavaScript frameworks which try to cobble together their own support for the features the core language is missing. And they all do it differently and, in many cases, make it really easy to write code with memory leaks or serious performance issues.

      But asking about alternatives is really two separate questions...one grounded in the current reality that we're forced to accept by browser vendors and another that deals with the idealized situation of what could we use if browser vendors didn't limit us to just JavaScript. IE does support VBScript, but that doesn't help developers write stuff that works in all browsers and VBScript is probably a worse option than JavaScript. It's really a shame because, IIRC, when they were deciding what scripting language to use in one of the early versions of Netscape Navigator, it came down to JavaScript and Lua. And the latter, in 20/20 hindsight, would probably have been a better choice.

      But what really needs to happen is for browser manufacturers to agree on a common runtime format that could be used to allow developers to use any language, scripting or traditional, that supports that runtime. The natural candidates would probably be either the Parrot VM, Sun's JVM or Microsoft's CLR, since they already exist and already have support for many languages. It would be a lot of work and there would be licensing issues to resolve no matter which runtime was agreed upon, but the end result would be a situation where developers could implement their client-side code in whatever language they choose.

      At this point, the reason there's nothing else but JavaScript is not technical, it's political.

  33. Well Written by MrMunkey · · Score: 3, Insightful

    I've had the book for about a month now. I've read most of it, but I haven't finished it yet due to work and personal projects and tv and games... Anyway, I think it is really well written. Doug is definitely has a very intimate knowledge of the subject, but his writing comes across more like a guide than an expert. He takes an approach kind of like taking you on a tour of the language. It's a pretty short book, so in theory it should be a quick read. I'd suggest you pick it up if even for only understanding JavaScript better.

  34. Re:Java or JavaScript: cool? by JCOTTON · · Score: 1

    "And THIS is the symptom of an uber-asshole ... he would rather spend his time blathering his pissy opinions "
    I hear you. But is this YOUR pissy opinion?

  35. No .trim??? by TheUnknownCoder · · Score: 2, Informative
    String.prototype.trim = function(){return(this.replace(/((^\s*)|(\s*$))/g, ""))};

    There you go.

    --
    Uncopyrightable: The longest word you can write without repeating a letter.
  36. Re:SLASHDOT SUX0RZ by Anonymous Coward · · Score: 0

    Honestly, I'm still not even sure where the goat is in that artwork...

  37. Re:Scoping is Awful? You need to buy the book... by soulcox · · Score: 1

    If you would read the book you would find that your code contains a few definite "don't do that, that is bad practice" statements (at least according to Crockford).

    If we take away the fact that there are several global variables created, the most problematic thing is that the code creates "elements.length" number of functions -> memory consuming, when it is easy to avoid.

    There are several videos on YDN theatre which discuss many of the subjects the reviewer mentions (these screencasts came before the book). After I watched one I ended up watching just about all of them. See and listen to http://developer.yahoo.net/blogs/theater/archives/douglas_crockford/

    and you will start to understanding javascript... not just write stuff what seems to work.

    If you want to see if you write "good" javascript try "jslint" written by Crockford http://www.jslint.com/ But like the site says "WARNING: JSLint may hurt your feelings."

  38. its simple by circletimessquare · · Score: 2, Informative

    document.onclick=function(){
    blah blah
    }

    then cancel event bubbling and default action, according to normal ie and firefox methods

    the anchor tag is not modified in any way. the href goes nowhere

    and i've tried to cancel the default action in safari in myriad ways, but it always tries to follow the bogus href ;-(

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
  39. Re:Scoping is Awful? You need to buy the book... by PipianJ · · Score: 1

    Interestingly, jslint doesn't complain about the above code (if you assume that doSomething was already written and defined as a global function and that we're running in a browser such that document is already defined as a global variable.)

    Yeah, building multiple functions is a bit wasteful. I suppose you could get by by attaching new properties to the elements and having the function attached to onclick reference the objects by using the event's target/srcElement property to get back to the custom variable.

    That's one of the either really good or really bad things about JavaScript: there's a heck of a lot of vastly different things you can do to get the same effect.

  40. well that's the whole point by circletimessquare · · Score: 1

    do i give up all of my work and program from scratch according to a new approach? or do i just ignore safari?

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
    1. Re:well that's the whole point by Phroggy · · Score: 2, Insightful

      do i give up all of my work and program from scratch according to a new approach? or do i just ignore safari?

      That depends. Starting from scratch with a new approach might result in code that's even more compatible with other browsers you haven't thought of, and it might even work better on the browsers you already do support.

      Not only does the iPhone use WebKit, but my Nokia phone does as well. How many mobile users access your web site?

      --
      $x='S24;r)>63/* h@<5+oZ)32"5cz';$me='phroggy'x$];
      $x=~y+ -xz+\0-Tx+;print$_^chop$me for split'',$x;
  41. Great book - try out the online 'debugger' by __aanjtz122 · · Score: 3, Informative

    I really like this book. The author does not treat you like an idiot or make 'oh so funny' jokes to make you feel comfortable with the text. The writing style is friendly and fluid, while the content is always to point. I wish more programming books were as dross-free as this one.

    Many readers are likely to read through sections twice or a few times. Crockford warns, 'This book is small, but it is dense', and it is certainly is cramed with useful information. The author states no intention of writing a JavaScript reference but has certainly written a book that I will pick up frequently on JavaScript projects

    I am surprised the reviewer didn't mention JSlint a free, online JavaScript 'verifier', written by the author, that can be used to 'debug' and write better code. It may even be worth a try before you buy the book.

  42. No browser! by Lincolnshire+Poacher · · Score: 1

    > You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website.

    Indeed. Well actually, you don't even need a browser to execute a JavaScript program.

    About two years ago I stumbled across SEE, the Simple ECMAScript Engine. It is a standalone JavaScript interpreter. I find it excellent for teaching the fundamentals and flexibility of JavaScript in a non-Web context. No DOM references, no browser oddities, no picking through a JavaScript Error Console; just the student and the raw language.

    http://www.adaptive-enterprises.com.au/~d/software/see/

    BSD-licensed, of course. I have no affiliation with the project other than as a satisfied user.

  43. Re:Scoping is Awful? You need to buy the book... by soulcox · · Score: 1
    Hm, I disagree. I pasted the above code, using default settings on the jslint page, and I got:
    Error: Implied global: doSomething 1, document 3
    and
    Global elements, i, onclickGenerator
    1 onclickGenerator(i)
    1 "return"()
    Outer i
    Global doSomething

    /*members getElementsByTagName, length, onclick */

    Yeah, building multiple functions is a bit wasteful. I suppose you could get by by attaching new properties to the elements and having the function attached to onclick reference the objects by using the event's target/srcElement property to get back to the custom variable.

    Well.. wastefull.. true, but for some apps it is detrimental (think ajax). Your example can perhaps be converted into something which avoids the need to pass "i" at all. Script libraries like YUI have code where you can control scoping when the handler executes. This may be overkill in this situation. So in this example perhaps setting an (html) id on the element and extracting it in the "doSomething" function would suffice, then you don't need the parameter at all.

    function doSomething() {
    var id = this.id /* lets say id is a1*/
    doSomethingElse(id);
    }

    then (something like)
    for (var i = 0; i < elements.length; i++) {
    elements[i].id = "a"+i;
    elements[i].onclick = doSomething; }

    But I really do recommend the screencasts, I thought I knew stuff about javascript, after having it explained (and verifed) in the screencats it is much easier to simply "use the good parts of javascript".

  44. But is it current? by DrEasy · · Score: 1

    With the recent introduction of classical inheritance to JavaScript (which may or may not be a good thing, that's besides the point), is this book still current though?

    --
    "In our tactical decisions, we are operating contrary to our strategic interest."
  45. Browsers by Anonymous Coward · · Score: 0

    Everybody talking about browsers, remember, Javascript is an interpreted language so the browser just acts as the interpreter. There is absolutely no requirement to use a browser to implement a javascript interpreter.

  46. Re:Java or JavaScript: cool? by johanatan · · Score: 1

    I wish more systems/languages used the 'image-based persistance' idea. And, its message passing is elegant simplicity--easy for humans to wrap their minds around.

  47. Re:SLASHDOT SUX0RZ by Anonymous Coward · · Score: 0

    dude, get with the now. goatse vids

  48. Yeh right! by thexile · · Score: 1
    Especially after you type in this:

    javascript:while(true)alert("Ha ha!");

  49. Re:Maligned So It Must Be DANGEROUS = more like it by Anonymous Coward · · Score: 0

    "Javascript has become quite the tool." - by WED Fan (911325) on Friday July 25, @02:06PM (#24338577) Homepage

    Yes, it has - However, quite often also (not just 'for the good') for the creation of malware laden websites, as well as adbanners that are bad (in combination w/ Iframes too).

    Searching SECUNIA.COM for the past 3-5 yrs. worth of exploits almost nearly always has something to do with javascript, in the past few years worth of attacks, such as these:

    ----

    Microsoft apologises for serving malware:

    http://apcmag.com/microsoft_apologises_for_serving_malware.htm

    ----

    (It even happens to "the best of them", including large corporate bodies, in them being 'suckered' by the people that put out malwares, by sneaking them into adbanners, as the example above notes)

    AND, javascript's being exploited fro upcoming worse malware attacks, such as this:

    ----

    Researcher to demonstrate attack code for Intel chips:

    http://www.infoworld.com/article/08/07/14/Researcher_to_demonstrate_attack_code_for_Intel_chips_1.html

    ----

    That last one? It's "pretty bad", imo @ least, maybe yours too, if you take a read of that last one.

    I do NOT doubt it could happen, anymore than say, a malware being able to flash your vidcard OR motherboard's BIOS (because, if tools by say, ASUS &/or Gigabyte can do it, AND WHILE YOU ARE IN WINDOWS mind you (not bootup from a floppy) then it's possible these could too)

    E.G.-> For example, if they ship a download via scripted attack that has say, a PnP driver + BIOS "img file" inside of it that the bogus javascript could SOMEHOW execute (or, a .exe they send - who knows? I don't make that kind of bogus ware, but the point is, the people misusing it are getting more & more "creative" about it, & their methods seem to be working).

    ----

    Now, don't "get me wrong" here:

    It's not that I "hate javascript" (well, I don't like working w/ it as opposed to other languages, let's put it that way), because it has its uses, but it gets abused a lot, in the way of being intended to harm others, is all.

    Fact is - I have to use it myself on ASP.NET pages I create or created on the job, for instance, because sometimes, it makes easy going of it, or provides a way to do things I need done, faster (or, the only way I could SEE or KNOW how to do certain types of functionality, fast).

    (Now - If the folks that create & extend javascripting engines can somehow do away with these misuses of javascript happening (how, I have NO idea, somekind of 'sandbox' such as 'fullblown java' has, good idea, maybe not perfect, but solid idea) that'd be GREAT... but I don't think that is as easily done, as it is said.

    Mainly because it's like saying that for probably nearly ANY compiler out there for say, std. .exe files, first of all, probably an impossible undertaking (like a razor, compilers & code have 2 sides potentially).

    Well - then, I wouldn't be "afraid of javascript", as an end-user online! Fact is, IF I knew it was safe (or, rather, safer than it is)?

    I'd turn it on again in ALL of my webbrowser programs, & for every site online again (I cut the latter off, years back, once I saw it was being abused in bad adbanners mainly, like the first example above).

    Yes, that is right, I am a bit afraid of it & tend to initially "cut it off" as to using it, wholesale @ first, in all of my webbrowsers, & ONLY turning it on for sites I absolutely cannot live without it on, & that's mostly banking &/or shopping style websites (& others that demand database or other files' access for instance, for ABSOLUTELY full & proper functionality (not just 'bells & whistles')).

    Personal

  50. i didn't use addeventlistener by circletimessquare · · Score: 1

    i'll try that method

    thanks for the tip

    still a pain to change the whole programming model of how my page works just for safari

    i'm current using document.onclick as a global handler

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it