Java Script

Java Script is a scripting language created by Brendan Eich at Netscape that supports Prototype Based Programming, Object Oriented Programming, and Functional Programming. It was originally called Live Script, but the name was changed to Java Script for marketing reasons. Microsoft calls their version JScript. There is now a standardized version, Ecma Script http://www.ecma-international.org/ www.ecma-international.org.

Some have claimed it is Lisp in C's clothing - lambda-the-ultimate.org - but being a dynamically-typed functional language is not enough to make something Lisp. Java Script lacks many features that are crucial to Lisp; macros perhaps being at the top of the list. (Are macros crucial to Lisp? Or, just a great CLOS feature? (Macros *are not* a CLOS feature, they have little to do with CLOS, and actually, the other way round, quite a lot of CLOS would usually be expressed in terms of various macros.)) Perhaps Java Script is a "dialect of Lisp" in Java's clothing. Or, Java Script is Scheme in Java's clothing.

Java Script is commonly found in Web Browsers and servers. It can be embedded in HTML for both client-side and server-side processing. Recently, Java Script has gained renewed interest for its RPC capabilities. See Ajax Web Applications.

On Windows systems, it can be used (along with VBScript) with the Microsoft Windows Scripting Host as a system scripting language.

On Macs, it can be used as an Open Scripting Architecture language alongside Apple Script through the use of a plug-in (based on Spider Monkey, see below).

Mozilla.org has two open-source implementations of Java Script engines, one in Java (Rhino Interpreter, see www.mozilla.org ) and one in C (Spider Monkey, see www.mozilla.org ). Both engines are embedded in a lot of products and also available for the command line.

It's also the basis for Dyna Script, the server-side scripting language for Sybase Dynamo (their answer to ASP).

Language Features

Unlike Java's inheritance model, Java Script is prototype and slot based - sorta like Newton Script and Self Language. It is really quite neat! -- Anonymous Donor

Unfortunately, this is going to change with the forthcoming version 2.0, where Java Script will have a more traditional class-based approach.

(Oh thank you Jesus! -- Paul Murray)

um.. Paul, that's not a good thing, the class based approach is less powerful and less dynamic. Prototypes give you everything classes do and more.

Fortunately for us, prototypes aren't going away. You still can have prototypes. Classes, as it turns out, are just a way of writing constructors, a feature which prototype-languages typically lack.

I think some definitions of "object-oriented" are limited due to the nature of popular OO languages. I haven't used Java Script directly, but I have used a prototypical language. The prototype is really just a delegate, which from a certain perspective is all that inheritance is, except that delegation is a run-time association between objects, while inheritance is compile time, therefore delegation is more flexible. Polymorphism can exist without inheritance. As a matter of fact, delegation promotes composition, which in turn promotes polymorphism. -- Greg Vaughn

I haven't tried this in Java Script, but if it's truly Self-like, then you don't need to do name-mangling to accomplish inheritance. Instead, you adopt a Smalltalk-style metastructure as a matter of convention, including a process and method execution model. Then, by convention, every "prototype" delegates every method to its "class", which looks in its metaclass to see how to interpret it. Since delegation *is* inheritance, you'll get what you want.

Java Script supports true Lexical Closures via function literals. A closure (also known as Lambda Expressions after LISP - where they probably originated) is simply an anonymous sub-routine that closes over the namespace of lexical variables within the scope of the block that defines the function body.

For some interesting use of closure-like behavior for Java Script event callbacks, see BeyondJS http://w3future.com/html/stories/callbacks.xml w3future.com.

Java Script is an interesting language. Arrays, objects, maps (Associative Array) are all unified. Members seem to be rather like slots in the Self Language. The way objects can inherit from one another is very dynamic. I think you could do quite a slick UI framework for Java Script. Yes, you could, and you might end up with something like Mozilla Xul.

Micro Soft are working on adding Static Type Safety support: msdn.microsoft.com

Testimonials

My friend Nick Simons has got surprisingly passionate in favour of Java Script as a pretty good object language in recent months. -- Richard Drake

Cross-platform compatibility

The Achilles Heel of Java Script is its inconsistent behavior across the various platform/browser combinations. As a result, it is virtually impossible to use it to do anything robust on the client side. -- Tom Stambaugh

Yes, a big problem with writing Java Script for the browser is the inconsistencies of its implementation across the various browsers. Take a look at my Js Unit. It's a unit testing framework for running Java Script Unit Tests inside the target browser. A nice side-effect of this is that you could run your tests in your target browsers. -- Edward Hieatt

Sorry, I can't agree at all. Ok, due to differences between the Explorer and Netscape versions there is some confusion. But I always try to write in unicode: one single version of a homepage for both. Period. Try looking at my page on French verbs conjugations - verbes.eduinfo.com -- Pieter Jansegers

I disagree with the points about inconsistencies in implementation. If you say that about Java Script then you must say the same thing about HTML. Netscape provides very good documentation on its Dev Edge website and if you follow their guidelines then you will be able to write script that works in version 3 & 4 browsers (Java Script 1.2) and version 5 browsers (Java Script 1.5) with very very few problems.

The inconsistency problem manifests itself significantly in implementation of DHTML and DOM - particularly in version 4 browsers - but this can be overcome by writing an abstract API that either uses switching or the Bridge Pattern. Java Script is actually a lot more flexible than is commonly believed. -- Walter Rumsby

It is quite possible to write compatible code as long as you do not use the Document Object Model (which is not part of the language definition anyway). Take a look at my Js Unit, which is available for a big number of environments as long as their engine is based on the ECMA standard. -- Jörg Schaible

Java Script and Wiki

Yes, check out Jeremy Ruston's Tiddly Wiki (www.tiddlywiki.com ) - the original is stand-alone HTML with all logic implemented in JS. There're now several spin-offs using PHP/MySQL... -- Karsten Schmidt

Does anyone knows of any library (or way) that allows to write Java Script CGIs? I'm planning on writing a Wiki Wiki Web in Java Script, I've found a really neat interpreter/byte-code compiler and it's a great way to learn the programming language (not the DOM/browser stuff)... Thanks! -- David De Lis

I may have misunderstood the question here, but if you use ASP you can use JScript to write server side code. -- Tobin Harris

No, I meant Java Script as an application building language, like C++ or Java, not as server-side stuff. I've written a small CGI library that allows me to access the query_string variables, but it's pretty weak, I'd prefer to work with one already done. Anyway... -- David De Lis

The Spider Monkey project generates a standalone executable as a reference implementation.

I am interested in using Java Script and Wiki as a way of building a Filesystem Based Wiki or a Wiki For Literate Programming. -- Andy Glew

Future

Have you looked at the proposal of Java Script 2.0? The ECMA TC39 group is working with the proposed draft at www.mozilla.org .#23You can find a lot of resources on Java Script on the Mozilla project page www.mozilla.org as well...

Two compilers that translate Java Script 2.0 to Java Script 1.X are Jangaroo (www.jangaroo.net ) and Mascara (ecmascript4.com ).


Don't forget the Netscape Java Script console - type javascript: into the URL field - better than dosument.write or alert() for tracing variables, etc. -- Dave Everitt


If used appropriately, Java Script is an easy and effective tool for creating dynamic Web-based interfaces for proprietary Intranet applications.

As long as you have some form of defence against Cross Site Scripting Exposure, attacks from people outside who know what you're using inside.


I only found out about Wiki yesterday, but I have been using a guestbook which stores the updates in Java Script function calls. My Web pages include these and I provide the code to be called.

This makes Java Script really useful, as you can update the data on a page.

Have a look at www.btinternet.com (broken link: unhosted) and www.dougrice.plus.com .

I hoped that BTOpenworld would provide the guestbook script that saves Java Script Function Calls along side their normal guestbook script, but I need help in working out how it would make them money.

It allows me to knock together simple applications quickly, and avoid a lot of the complications of server side programming.

From my limited knowledge of the PHP/MySQL solution, your database query gives you an array of the data from the database search. My idea gives you an array of data, it's just all the data that the guestbook users post in the order that they post the data.

It is similar to Wiki.


A nice feature of Java Script is its treatment of functions as first class objects, which allows Closures and Higher Order Functions.


For more information on Java Script see:


Some Java Script Tutorials


Presentation

Java Script is a Scripting Language. See the definition at: en.wikipedia.org

Java Script enables you to write fixed menus easily and quickly--pull-down menus, windows, menus for the right click of the mouse and other things (given the right environment).

A non-programmer thinks, "For those who can't put together 3 lines of code in any language, javascript is god-send!" It's actually a product of Netscape and subsequent contributors and is Just Another Programming Language, though one shaped by its birth within the framework of a Web Browser.


Paste the following as js.html in a local text file and open in your browser you can edit and run simple Java Script code in the text field without refreshing (the button calls the eval() function). A simple ide for learning.

<html> <head><title>Eval()</title> <script language="JavaScript"> <!-- function evaluate() { //document.forms[0].out.value = eval(document.forms[0].field.value); } --> </script> </head> <body> <form> <input type="button" name="go" value="go" onClick="evaluate()"><p> <textarea rows="20" cols="40" name="field"> //start code

init(); o.m1(1);

function init() { o = new Object(); o.a1 = 0;

o.m1 = function(x) { alert("before:"+this.a1); this.a1 = x; alert("after:"+this.a1); } }

//end code </textarea> <textarea rows="20" cols="40" name="out"> </textarea> </form> </body> </html>


Some Java Script oddities and bugaboos:

Variable declarations are optional (much like Basic Language); though if you read an undeclared variable before writing to it you'll get an error. (Writing to an undeclared variable declares it - in the global scope.)

Language is Weakly Typed, and the automatic coercions that it does can produce surprising results. "2" + "3" is "23" (+, when applied to two strings, performs concatenation); "2" * "3" is 6. (Multiplication not defined for strings; so the language tries converting them to numerals, succeeds, and multiplies those). This can be surprising. Is it? It's the same behaviour as other languages, e.g. python. -- Greg Bowyer Nope. Python says "2"+"3" is "23", "2" * 3 is "222", and "2" * "3" and "2"+3 are type errors.

Rather annoying gotcha in array constructor. new Array() returns a newly created empty array; new Array(2,3) returns a newly-created array with 2 and 3 as its two elements. new Array(5) does not return a newly-created array with 5 as its single element; instead, it returns a 5-element array! Use new Array(length) to create a sized array, use var myArray = [2, 3, 4, 5] to define an array

Whereas most languages have one universal singular value (null/nil/Void/whatever); Java Script has two - "null" and "undefined". With somewhat interesting and irregular semantics.

No integral types - the only numeric type supported is an IEEE754 double-precision float. For a scripting language, this limitation is probably less obnoxious than it would be elsewhere.

Language has Lexical Scoping, but with an interesting twist. Unlike Java Scripts brethen C/C++/Java/C#/etc, where variables introduced in an anonymous block within a function are only valid within that block; in Java Script such variables are valid for the entire function. In other words:

if (a == b) { var c = "Equal!"; }

if (c == "Equal!") { // do something }

is legal Java Script. If the first condition is not true, c will evaluate to "undefined".

Semicolons are optional in Java Script; if the parser sees a line break, it will try and interpret the two lines as separate statements (if it can't, it then tries to interpret them as a single statement). This too can produce surprising results.

It is not precisely true that semicolons are optional. The syntax actually requires them, and the rules for inserting them automatically are almost the exact opposite (it is only tried if it is a syntax error without one and if other additional conditions are met). There are plenty of situations where a newline is not sufficient, semicolon insertion won't take place, and it won't do what you expect. For this reason pretty much every serious javascript programmer considers it a misfeature.


Some of the claims here may overstate the power of Java Script. While the language itself may, given an ideal engine in an ideal environment, provide everything mentioned, there are still important shortcomings that need to be addressed before a Java Script Ide can be competitive with Smalltalk (my benchmark).

In particular, what if any execution model is implied by the language, and how much of that model can be surfaced in the environment? Can I get at things comparable to stack frames, activation records, and so on? Is there a real process model (real in the sense that I can do multi-threaded things)?

How hard would it be to support a basic Smalltalk-style debugger/inspector? I note, for example, that the Venkman Debugger cuts several corners, and appears to dramatically slow the execution while running. Is Venkman the best there is? Is Venkman itself written in Java Script, so that I can change it on the fly?

[The short answer is no. The Ecma Script language standard itself is minimal and doesn't specify anything about threading or processes or even an execution model. It is intended to be extended, though, so an implementation of Java Script with these features certainly would be possible. Venkman, as with all XUL applications, is implemented in Java Script but I believe the JS engine that powers the application is separate from the JS engine that executes the code Venkman looks at (and the JS code that runs on web pages).]


Douglas Crockford has articles about how to use Java Script in an object-oriented fashion at www.crockford.com . He also has an article called Java Script: The World's Most Misunderstood Programming Language that I like a lot. -- Chad Skeeters


Q Serverside Javascripts on Microsoft IIS. Any benefits to using it instead of Vb Script?

Answer: Yes, you can share function and code snippets that can be used on both the server and client side, like form validation, error checking (but not handling), or other more complex algorithms, like regex's.

That, and Vb Script sucks in comparison. It doesn't have exception handling, anonymous functions, prototypes, or a good culture in general.

Question: Any recomendations on books? Something like Java Script For Programmers, not Java Script For Total Morons, please.

Answer: Check out the book list on Iwanna Learn Java Script.

Question: Is there any mechanism for Java Script to communicate information between frames and windows in a browser? (e.g. like 'cookies' for Java Script, but NOT delivered as part of the HTTP request header? - i.e. kept purely client-side?)

Answer: Yes. When a frame named frame1 wants to access a frame named frame2, it can do so via parent.frame2. See, e.g., the "Writing to Other Frames and Windows" section of Dynamic Html The Definitive Reference from Oreilly And Associates.

Question: That does not seem very cookie-like, since the communication requires knowing ahead of time (by name) exactly which other frames and windows will be involved in the communication. Is there a way to do this Can one do it without knowing the 'names' of these other windows and frames? (My goal is Hmac User Authentication for Wiki Ide, and this would just make it convenient by automatically logging in on all pages by entering username and password on one page.)



See original on c2.com