Javascript
About the language
History
JavaScript was originally developed at Netscape, for use in their browser Netscape Navigator. This was in the mid-1990s, during the height of the browser wars, when each browser developer was attempting to win market share by creating unique features unavailable in other browsers. There was also a line of thinking during that period that browsers would be, in many ways, an extension of the operating system and general user experience. There seems to have been some thought that Netscapeâs browser would be part of a distributed operating system running a portable version of the Java environment. This would be complemented by a lightweight scripting language, which was officially called LiveScript and developed under the project code name Mocha.
It isnât clear whether it was that plan, or a simple marketing ploy, but this âlightweight interpreted languageâ eventually got name âJavaScript,â even though the language had no real connection to Java.
JavaScript was added to the Netscape Navigator browser in 1996, and Microsoft quickly reverse-engineered a JavaScript implementation for their Internet Explorer browser, which they called JScript. Unfortunately, the implementations were quite different. Different approaches to HTML and what became CSS complicated matters even more, as JavaScript exists primarily to manipulate objects within the document â different document models produced different results. It was common during this period to see websites instruct their users that the site âWorks Best on Netscapeâ or âWorks Best on Internet Explorer.â (AOL, which eventually bought Netscape, also had an in-app browser. But nothing worked the best on it.)
Netscape submitted JavaScript to Ecma, as a potential international, industry-wide standard. In 1997, the standard version, called âECMAScriptâ was released. There have been a number of subsequent version releases since then. Ecma, and not Netscape, now determines the course of the language.
Thanks to a general trend toward browser standardization that began in the early 2000s, and was largely complete by the middle of the 2010s, most browsers implement ECMAScript (and the HTML Document Object Model) in largely similar ways. Today, you can be fairly confident that a JavaScript-based application written according to widely-recognized best practices will work on all major browsers.
Language features
Object Orientation
JavaScript is object-oriented. Itâs a little weird in this way, though; there are objects, but no classes. So many âclassicalâ object-oriented programmers often find it somewhat deficient, or would say it isnât actually object-oriented at all. But it is.
Nearly everything (excluding some primitive values) in JavaScript is an object, and can therefore have methods and accessible data. Objects are not instantiated from classes, however. They are cloned from other objects. Rather than writing a class, you would simply create a prototype object. New objects are then cloned from there, but new methods and properties can be added to the new objects as needed.
There are some advantages and disadvantages to this approach. One (possible) advantage is that if you just need a single instance of an object, you donât have the overhead of writing an entire class and then writing the code that instantiates it. Given JavaScripts primary domain (web documents) this makes a lot of sense.
The main disadvantage is basically philosophical in nature. In a complex application, it will certainly be the case that you would write a number of prototype objects that are note used, but only cloned into new objects â essentially re-creating a class-based paradigm. Except the original objects are still there, as objects. There is no essential difference between them, even though they are being used in fundamentally different ways. The class-object dichotomy represents a particular (âclassical,â even) view of reality â abstract ideas about categories and types of things which are instantiated into real objects. JavaScript presents a messier (but, probably, more realistic) view of reality in which there are no abstract, Platonic notions; there is only this object, and this one, and this one, and so on.
Structure
JavaScript, like most modern programming languages, follows the structured programming model. The syntax is somewhat similar to C, with if
, else
, for
, and while
all behaving as may be expected.
Unlike C, JavaScript mostly only supports function-level variable scope. Block level scoping was added somewhat recently but (as of this writing), it is still much safer to code as if this were not present.
Speaking of variables, variables in JavaScript are dynamically typed. This means you donât have to declare a variable and its data type (string, number, etc.) ahead of actually assigning the value to the variable. This is quite different from C, but is pretty common among other interpreted scripting languages.
Functions in JavaScript are first-class, which means that they can be passed as arguments to other functions or stored as variables. This allows (among other things) functions to be defined inside of other functions. This is used frequently in in-browser applications to cause functions to get defined at particular points. For example, in the following jQuery code, the inner function adjusts the target
property of all on-page links so that they open in a new tab if they link to another domain. This function is created inside a function that is only called when the document is ready (fully loaded). This is a minor example (which happens to be used on this website), but illustrates something done frequently in JavaScript.
The Event Loop
JavaScript relies on an event loop which listens for messages (such as mouse clicks, key strokes, or messages created by other object), and queues those messages for processing. Functions can be created that listen for certain messages, and are then triggered when those events happen (such as the example above, which triggers the inner function when the document ready
event occurs).
This event driven architecture makes perfect sense for JavaScriptâs original (and still primary) purpose â website user interaction. It allows the application to listen for user-created, unprompted inputs. More recently, this feature has been exploited in server-side environments like Node.js. Having a built-in event-listening system makes it (relatively) easy to build real-time applications in domains such as chat, gaming, collaboration, and dispatch.
JavaScript Events
JavaScript provides a way of interacting with, and manipulating, the content of a web page. This can be done through code stored in a linked .js
file, in an on-page <script>
code block, or by accessing JavaScript event triggers within the documentâs elements.
An event is like a signal or message that something has happened. For example, every time your mouse clicks on an element of a page, the onclick
event for that element is fired. Under normal circumstances, this doesnât cause anything else to happen. But you can use those events to trigger other code to run. You can write code that says (in essence): Everytime this thing happens, do this other thing.
You can imagine the possibilities here:
Every time this picture is clicked⌠load the next picture.
Every time the mouse enters this area⌠change the color.
Every time the mouse approaches the navigation bar ⌠open a modal window with a special offer.
JavaScript, being a language designed for user-interation, is âevent-drivenâ. There are a lot of events in JavaScript, and bunch of them are tied to HTML elements.
Events as HTML Attributes
All HTML elements on a webpage have a set of built-in events which fire under certain circumstances. You can access these events as if they were attributes of the element:
#flamingo-picture-1 { border: 15px solid red; }
If you are doing much more than one single line, it can get a bit too much to try to keep all of it inside the onclick
attribute. In that case, you might just want to call a function from the event.
#flamingo-picture-2 { border-width: 15px; border-style: solid; border-color: red; }
function changeBorderColor() { var img = document.getElementById(âflamingo-picture-2â); if (img.style.borderColor === âredâ) { img.style.borderColor = âblueâ; } else { img.style.borderColor = âredâ; } }
List of JavaScript Events on HTML Elements
Most of the names describe exactly when they fire. A few of them are only applicable to a few kinds of elements. See JavaScript Elements for code samples and demonstrations.onclickWhen the user clicks on the element. (Mouse button is pressed and released immediately.)oncontextmenuWhen the context menu (âright-clickâ) is opened (or when the user tries to open it â this can be used to disable the context menu).ondblclickWhen the element is double-clicked.onmousedownWhen the user presses the mouse button down while inside (or over) the element. (Mouse button is pressed and held.)onmouseenterWhen the mouse enters the element. (Sometimes called âhover,â but that is not the name of the event.)onmouseleaveWhen the mouse leaves an element.onmousemoveWhen the mouse moves while inside an element.onmouseoverWhen the mouse enters an element, or one of its children.onmouseoutWhen the mouse exits an element, or one of its children.onmouseupWhen the user releases the mouse button, while the mouse is inside the element.onerrorWhen an error occurs while loading an external file (most often used on media files).onloadWhen the elements completes loading (mostly used on media files, but can be used also for <body>
).onscrollWhen the content is scrolled.
Programming Notes
The Document Object Model
HTML is used for your pageâs content. CSS controls how everything looks. How do you use JavaScript to manipulate what is on the screen and what it looks like? To you use JavaScript to manipulate the HTML directly?
The answer is the DOM, or the Document Object Model. And no, you do not manipulate the HTML directly. You manipulate the DOM.
The DOM is the browserâs own representation of a web page, based on the HTML and CSS. But the DOM is not a document, is the current, live state of page as it is displayed in the browser currently. This means that the DOM knows things like element size, playback position and volume, which element is being clicked on or hovered over. Also, the DOM updates as it is being manipulated. So if you change the content of an element, that change is made in the DOM and reflected in the view (the browserâs window).
Ajax
JavaScript is the J in Ajax, which originally stood for Asynchronous JavaScript and XML. (XML, or Extended Markup Language, is a data serialization format. It has now largely been replaced by JSON â JavaScript Object Notation â but the name sticks because âAjaxâ sounds catchy.)
Ajax is something you probably use everyday. It is an application pattern wherein data is sent to or fetched from the server without the web page being refreshed. (Requests and response are not out of sync with browser refreshes or changed in URL.) This is how many web apps, like Gmail for example, work. The client-side (browser) JS application sends requests to the server and receives all the needed data or content as a JSON object (or XML document) and then uses that data to update the view.
jQuery, the unofficial standard library
Most programming languages have a standard library, a set of classes and/or functions that help programmers do common, low-level programming tasks. Typically, these standard libraries come packaged with the language and are documented along with them.
For a number of historical reasons, JavaScript does not have a standard library. This means that in a âpureâ JavaScript implementation, many very common tasks are needlessly verbose and complicated.
JQuery is one of several JavaScript libraries which provide a wide range of basic functionality, making it easy to do common programming tasks like traversing the DOM, manipulating HTML objects and their properties, communicating with a server, and interfacing with the browser.
The jQuery library is extremely common, so much so that many consider it to be the de facto standard library for JavaScript. Understanding jQuery is an important skill for any front-end web developer.
Read more: https://html.com/javascript/#ixzz6hG2TcZRB
Last updated
Was this helpful?