Code in JavaScript and HTML right here in the browser



About JavaScript

In computing, JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production; the majority of websites employ it, and all modern Web browsers supported it without the need for plug-ins. And no, it is NOT the same as Java! It has an API for working with text, arrays, dates and regular expressions, but does not include any I/O, such as networking, storage, or graphics facilities, relying for these upon the host environment in which it is embedded.

Although there are strong outward similarities between JavaScript and Java, including language name, syntax, and respective standard libraries, the two are distinct languages and differ greatly in their design. JavaScript was influenced by programming languages such as Self and Scheme.

Here's Brendan Eich - the creator of Javascript.

Recent Developments

JavaScript has become one of the most popular programming languages on the Web. Initially, however, many professional programmers denigrated the language because, among other reasons, its target audience consisted of Web authors and other such "amateurs".The advent of Ajax returned JavaScript to the spotlight and brought more professional programming attention. The result was a proliferation of comprehensive frameworks and libraries, improved JavaScript programming practices, and increased usage of JavaScript outside Web browsers, as seen by the proliferation of server-side JavaScript platforms.

In January 2009, the CommonJS project was founded with the goal of specifying a common standard library mainly for JavaScript development outside the browser.

With the rise of single-page applications and JavaScript-heavy sites, it is increasingly being used as a compile target for source-to-source compilers from both dynamic languages and static languages.


The most common use of JavaScript is to add client-side behavior to HTML pages, also known as Dynamic HTML (DHTML). Scripts are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:

  • Loading new page content or submitting data to the server via Ajax without reloading the page (for example, a social network might allow the user to post status updates without leaving the page).
  • Animation of page elements, fading them in and out, resizing them, moving them, etc.
  • Interactive content, for example games, and playing audio and video.
  • Validating input values of a Web form to make sure that they are acceptable before being submitted to the server.
  • Transmitting information about the user's reading habits and browsing activities to various websites. Web pages frequently do this for Web analytics, ad tracking, personalization or other purposes.

Because JavaScript code can run locally in a user's browser (rather than on a remote server), the browser can respond to user actions quickly, making an application more responsive. Furthermore, JavaScript code can detect user actions that HTML alone cannot, such as individual keystrokes. Applications such as Gmail take advantage of this: much of the user-interface logic is written in JavaScript, and JavaScript dispatches requests for information (such as the content of an e-mail message) to the server. The wider trend of Ajax programming similarly exploits this strength.

A Web browser is by far the most common host environment for JavaScript. Web browsers typically create "host objects" to represent the DOM in JavaScript. The Web server is another common host environment. A JavaScript Web server would typically expose host objects representing HTTP request and response objects, which a JavaScript program could then interrogate and manipulate to dynamically generate Web pages.

Because JavaScript is the only language that the most popular browsers share support for, it has become a target language for many frameworks in other languages, even though JavaScript was never intended to be such a language. Despite the performance limitations inherent to its dynamic nature, the increasing speed of JavaScript engines has made the language a surprisingly feasible compilation target.

Simple examples of JavaScript

Variables in JavaScript can be defined using the var keyword:

var x; // defines the variable x and assigns to it the special value "undefined" (not to be confused with an undefined value)
var y = 2; // defines the variable y and assigns to it the value 2

Note the comments in the example above, both of which were preceded with two forward slashes.

There is no built-in I/O functionality in JavaScript; the run-time environment provides that. The ECMAScript specification in edition 5.1 mentions:

… indeed, there are no provisions in this specification for input of external data or output of computed results.

However, most runtime environments have a console object that can be used to print output. Here is a minimalist Hello World program:

console.log("Hello World!");

A simple recursive function:

function factorial(n) {
    if (n == 0) {
        return 1;
    }

    return n * factorial(n - 1);
}

Multiplication of two numbers:

<html>
<body>
	<h1>Multiplication</h1>
	Enter Number 1:<input type="text" id="a1"><br>
	Enter Number 2:<input type="text" id="a2"><br>
	<button onclick="myFunction()">Product</button>
	<p id="a3"></p>
	<script>
 		function myFunction(){
			var a=parseInt(document.getElementById("a1").value);
			var b=parseInt(document.getElementById("a2").value);
			var c=a*b;
			document.getElementById("a3").innerHTML=c;
			 		
 		}
	</script>
</body>
</html>

An anonymous function (or lambda):

function counter() {
    var count = 0;
    return function () {
        return ++count;
    };
};

var closure = counter();
closure(); // returns 1
closure(); // returns 2
closure(); // returns 3

This example shows that in JavaScript, function closures captures their non-local variables by reference.

Variadic function demonstration (arguments is a special variable):

function sum() {
    var x = 0;

    for (var i = 0; i < arguments.length; ++i) {
        x += arguments[i];
    }

    return x;
}

sum(1, 2); // returns 3
sum(1, 2, 3); // returns 6

Immediately-invoked function expressions are often used to create modules, as before ECMAScript 2015 there was not built-in construct in the language. Modules allow gathering properties and methods in a namespace and making some of them private:

var counter = (function () {
    var i = 0; // private property

    return {   // public methods
        get: function () {
            alert(i);
        },
        set: function (value) {
            i = value;
        },
        increment: function () {
            alert(++i);
        }
    };
})(); // module

counter.get();       // shows 0
counter.set(6);
counter.increment(); // shows 7
counter.increment(); // shows 8

More advanced example

This sample code displays various JavaScript features.

/* Finds the lowest common multiple (LCM) of two numbers */
function LCMCalculator(x, y) { // constructor function
    var checkInt = function (x) { // inner function
        if (x % 1 !== 0) {
            throw new TypeError(x + " is not an integer"); // throw an exception
        }
        return x;
    };
    this.a = checkInt(x)
    //   semicolons   ^^^^  are optional, a newline is enough
    this.b = checkInt(y);
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
    constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately
    gcd: function () { // method that calculates the greatest common divisor
        // Euclidean algorithm:
        var a = Math.abs(this.a), b = Math.abs(this.b), t;
        if (a < b) {
            // swap variables
            t = b;
            b = a;
            a = t;
        }
        while (b !== 0) {
            t = b;
            b = a % b;
            a = t;
        }
        // Only need to calculate GCD once, so "redefine" this method.
        // (Actually not redefinition—it's defined on the instance itself,
        // so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.
        // Note that this leads to a wrong result if the LCMCalculator object members "a" and/or "b" are altered afterwards.)
        // Also, 'gcd' === "gcd", this['gcd'] === this.gcd
        this['gcd'] = function () {
            return a;
        };
        return a;
    },
    // Object property names can be specified by strings delimited by double (") or single (') quotes.
    lcm : function () {
        // Variable names don't collide with object properties, e.g., |lcm| is not |this.lcm|.
        // not using |this.a*this.b| to avoid FP precision issues
        var lcm = this.a/this.gcd()*this.b;
        // Only need to calculate lcm once, so "redefine" this method.
        this.lcm = function () {
            return lcm;
        };
        return lcm;
    },
    toString: function () {
        return "LCMCalculator: a = " + this.a + ", b = " + this.b;
    }
};

// Define generic output function; this implementation only works for Web browsers
function output(x) {
    document.body.appendChild(document.createTextNode(x));
    document.body.appendChild(document.createElement('br'));
}

// Note: Array's map() and forEach() are defined in JavaScript 1.6.
// They are used here to demonstrate JavaScript's inherent functional nature.
[[25, 55], [21, 56], [22, 58], [28, 56]].map(function (pair) { // array literal + mapping function
    return new LCMCalculator(pair[0], pair[1]);
}).sort(function (a, b) { // sort with this comparative function
    return a.lcm() - b.lcm();
}).forEach(function (obj) {
    output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
});

The following output should be displayed in the browser window.

LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56
LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168
LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275
LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638

Tutorials and Links

JavaScript is usually learned in conjuction with HTML (and PHP). Again, there are plenty of sites that will help you learn it free. We can recommend our own resources which are pedagogically tested and tried in the classroom. They're a little different than the usual approach, and get students quickly engaged in how powerful the software can be (game creation and web design). You can check out the powerpoint series
<<<here - just click on the next tab after JavaScript Other than that, there are other websites like:

www.w3schools.com/js/ - absolutely amazing as always!

https://www.javascript.com/about

https://www.codecademy.com/learn/javascript

and finally the highly recommended:

http://www.homeandlearn.co.uk/JS/javascript.html


On the other hand if you're after lots of code snippets you may want to check out:

https://www.hscripts.com/scripts/JavaScript/

 

and www.javascriptkit.com

 

Or just google javascript code snippets - there are thousands around and you can virtually find anything you want to do in minutes!

 

 

Videos

In addition to Web browsers and servers, JavaScript interpreters are embedded in a number of tools. Each of these applications provides its own object model that provides access to the host environment. The core JavaScript language remains mostly the same in each application.

Embedded scripting language

Scripting engine

  • Microsoft's Active Scripting technology supports JScript as a scripting language.
  • Java introduced the javax.script package in version 6 that includes a JavaScript implementation based on Mozilla Rhino. Thus, Java applications can host scripts that access the application's variables and objects, much like Web browsers host scripts that access a webpage's Document Object Model (DOM).
  • The Qt C++ toolkit includes a QtScript module to interpret JavaScript, analogous to Java's javax.script package.
  • OS X Yosemite introduced JavaScript for Automation (JXA), which is built upon JavaScriptCore and the Open Scripting Architecture. It features an Objective-C bridge that enables entire Cocoa applications to be programmed in JavaScript.
  • Late Night Software's JavaScript OSA (also known as JavaScript for OSA, or JSOSA) is a freeware alternative to AppleScript for OS X. It is based on the Mozilla JavaScript 1.5 implementation, with the addition of a MacOS object for interaction with the operating system and third-party applications.[84]

Application platform

  • ActionScript, the programming language used in Adobe Flash, is another implementation of the ECMAScript standard.
  • Adobe Integrated Runtime is a JavaScript runtime that allows developers to create desktop applications.
  • Atom, the open-source text editor developed by Github, was implemented using Javascript, and has a special API on Javascript for packages that are developed for it.
  • CA, Inc.'s AutoShell cross-application scripting environment is built on the SpiderMonkey JavaScript engine. It contains preprocessor-like extensions for command definition, as well as custom classes for various system-related tasks like file I/O, operation system command invocation and redirection, and COM scripting.
  • GNOME Shell, the shell for the GNOME 3 desktop environment, made JavaScript its default programming language in 2013.
  • The Mozilla platform, which underlies Firefox, Thunderbird, and some other Web browsers, uses JavaScript to implement the graphical user interface (GUI) of its various products.
  • Qt Quick's markup language (available since Qt 4.7) uses JavaScript for its application logic. Its declarative syntax is also similar to JavaScript.
  • TypeScript is a programming language based on JavaScript that adds support for optional type annotations and some other language extensions such as classes, interfaces and modules. A TS-script compiles into plain JavaScript and can be executed in any JS host supporting ECMAScript 3 or higher. The compiler is itself written in TypeScript.
  • Ubuntu Touch provides a JavaScript API for its unified usability interface.
  • webOS uses the WebKit implementation of JavaScript in its SDK to allow developers to create stand-alone applications solely in JavaScript.
  • WinJS provides a special Windows Library for JavaScript functionality in Windows 8 that enables the development of Modern style (formerly Metro style) applications in HTML5 and JavaScript.

Javascript - Code /Projects / Downloads / Code Snippets

Animation Effects

Form validation

Creative Commons: https://en.wikipedia.org  Oa 80x15 orange.png