Javascript is a language often used within html documents to trigger interactive features.

Since its release in December 4, 1995 [six months after Java, which was released in May 23, 1995], JavaScript has gone through many changes. JavaScript began as a client-side programming language [which runs inside a web browser via a built-in JavaScript engine] for adding interactive contents to the web pages. It became more robust with DHTML [1997] and Ajax [1999]. With Node.js [released in May 27, 2009], JavaScript can be used to program server-side and build full-stack web applications. In 2015, the ECMAScript 6 [ES6] introduces major update to the language.

Introduction

It began as a Client-side Programming Language run inside a web browser via a Built-in JavaScript Engine

JavaScript is the most widely used client-side programming language that lets you supercharge your HTML with interactivity, animation and dynamic visual effect for better User Interface and User Experience [UI/UX]. It is:

  • a small, lightweight, object-oriented, cross-platform, special-purpose scripting language meant to be run under a host environment [typically a web browser].
  • a client-side scripting language to enrich web user-interfaces and create dynamic web pages [e.g., form input validation, and immediate response to user's actions].
  • the engine that supports AJAX [Asynchronous JavaScript and XML - that can be used to update one part of the web page asynchronously], which generate renew interest in JavaScript.

JavaScript works together with HTML/CSS. HTML provides the contents; CSS specifies the presentation; and JavaScript programs the behavior. Together, they enrich the UI/UX of the web users.

JavaScript is Now Everywhere with Node.js

JavaScript has grown beyond the client-side programming. With the introduction of Node.js in 2009 [an open-source, cross-platform JavaScript run-time environment], you can run your JavaScript standalone or inside the server [instead of a browser]. This allows you to use one single language for both the server-side and client-side programming.

History and Versions

JavaScript, originally called LiveScript, was created by Brendan Eich at Netscape in 1995. Soon after, Microsoft launched its own version of JavaScript called JScript. Subsequently, Netscape submitted it to ECMA [formerly "European Computer Manufacturers Association", now "Ecma International - European association for standardizing information and communication systems"] for standardization, together with Microsoft's JScript.

The ECMA Specification is called "ECMA-262 ECMAScript Language Specification" @ //www.ecma-international.org/publications/standards/Ecma-262.htm [also approved as "ISO/IEC 16262"]:

  • ECMA-262 version 1 [June 1997]: First edition
  • ECMA-262 version 2 [August 1998]
  • ECMA-262 version 3 [December 1999]: Added regular expressions, try/catch, switch, do-while, etc.
  • ECMA-262 version 4 - Abandon due to political differences. In 2007, the TC-39 [the committee responsible for ECMAScript] put up a draft specification for ECMAScript 4, which was massive in scope and introduced many new syntax and features. But a group of developers from Yahoo, Google and Microsoft felt that was too much and created an alternate proposal called ECMAScript 3.1. ECMAScript 4 was never finalized.
  • ECMA-262 version 5 and 5.1 [June 2011]: ECMAScript 3.1 was eventually standardized as ECMAScript 5. Added "strict mode", JSON, Array iteration methods, etc.
  • ECMA-262 2015: most popularly known as ECMAScript 6 or ES6.
    This version added significant new syntax for writing complex application, including class declaration, let for local declarations, const for constant local declaration, default parameter values, iterators and for...of loops, Python-style generators, arrow function expression [[] => {...}], binary data, typed arrays, new collections [maps, sets and WeakMap], promises, reflection, proxies, template literals for strings, and many more.
  • ECMAScript 2016 [ES7]: Since ES6, ECMAScript standards are on yearly release cycles in June.
    This version added exponential operator [**], block-scoping of variables and functions, await and async keywords for asynchronous programming, etc.
  • ECMAScript 2017 [ES8]: Added string padding, async functions which use generators and promises, Object.values, Object.entries for easy object manipulation, etc.
  • ECMAScript 2018 [ES9]: Added rest parameters [...], spread operator, asynchronous iteration, additions to regular expression.
  • ECMAScript 2019 [ES10]: Added Array.prototype.flat, Array.prototype.flatMap, changes Array.sort and Object.fromEntries, catch binding becomes optional, etc.
  • ECMAScript 2020 [ES11]: introduces a BigInt primitive type for arbitrary-size integers, the nullish coalescing operator [??] and the gloablThis object.
  • ECMAScript 2021 [ES12]: Added enhancement to strings [replaceAll], promises [Promise.any], and object references. Logical assignment operators [??=, &&=,||=,]
JavaScript vs. Java

Java is a full-fledged general-purpose programming language. It was created by James Gosling at Sun Microsystems [now part of Oracle] and released in August 1995.

JavaScript was created by Brendan Eich at Netscape, also in 1995. Originally called LiveScript, it was a small and lightweight special-purpose language for writing client-side program running inside a browser to create active user-interface and generate dynamic web pages. It was renamed to JavaScript in an ill-fated marketing decision to try to capitalize on the popularity of Java language, when Netscape released its Navigator 2 in 1996.

Java and JavaScript are totally different languages for different programming purposes. However, in the early days, some efforts were made to adopt Java syntax and convention into JavaScript, such that JavaScript seems to be a subset of Java. In reality, they have very little in common.

What Client-side JavaScript CANNOT Do?

Remember that JavaScript is a client-side program that you downloaded from a server, and run inside the browser of your [client] machine. What to stop someone from writing a JavaScript that wipes out your hard disk, or triggers a denial-of-service attack to another server? As a result, for security purpose,

  1. It cannot read file from the client's machine.
  2. It can only connect to the server that it come from. It can read file from the server that it come from. It cannot write file into the server machine.
  3. It cannot connect to another server.
  4. It cannot close a window that it does not open.
jQuery

jQuery is a popular cross-browser JavaScript Library. jQuery is JavaScript [but having its own extension syntax], hence, you need to understand JavaScript. I suggest you read through the JavaScript syntax [and pay particular attention to objects], and then switch into jQuery for your production. Read "jQuery Basics".

Standalone and Server-side JavaScripts with Node.js JavaScript Engine

[TODO]

JavaScript Source-Code Editors and IDEs

You need a text editor to write your JavaScript. You could use a plain-text editor such as Windows' NotePad or macOS's TextEdit [strictly NOT recommended as they can't do syntax highlighting]. To improve your productivity, a good source-code editor [which provides syntax highlighting, auto-code-complete, snippets, documentation, symbol navigation, refactoring, etc.] is essential. There are many freeware/shareware available, such as Visual Studio Code [VS Code], Sublime Text, Atom, Brackets, Komodo Edit, Emacs, Vim, BBEdit, TextMate, NotePad++ [Windows], etc. You can also use a full-scale IDE such as Eclipse, NetBeans, IntelliJ IDEA. There are also many "online" editors and compilers available [e.g., Programiz, JSFiddle, Playcode], but I think that you should install your own.

Client-Side JavaScript by Examples

I shall assume that you know HTML and CSS [read my HTML/CSS articles otherwise]. I shall also assume that you understanding some programming basics [computational thinking] such as variables, if-else and for-loop constructs.

Client-side JavaScripts run inside a browser via a built-in JavaScript engine. There are standards on JavaScript. But the Big-5 [Chrome, Firefox, IE/Edge, Safari and Opera], in particular the IE, does not adhere to all the standards strictly. Furthermore, they create their own extensions. Hence, the behavior of JavaScript could be different in different browsers. You may need to test your JavaScripts on more than one browsers.

JavaScript also run standalone [and in the server]. To run JavaScript standalone, you need to install Node.js, which is a JavaScript engine. I will present the examples in the next section.

Client-side JS EG 1: Functions alert[] and document.write[]

Let us write our first client-side JavaScript to print the message "Hello, world".

Start with a new file and enter the following codes. Do not enter the line numbers, which is used to aid in explanation. Take note that:

  • JavaScript is case sensitive. A rose is NOT a ROSE and is NOT a Rose.
  • "Extra" white spaces [blanks, tabs and newlines] are ignored. That is, multiple white spaces is treated as a single blank character. You could use them liberally to make your program easier to read.

Save the file as "JSExAlertWrite.html" [or any filename that you prefer, with file extension of ".html" or ".htm"]. Run the script by loading the HTML file into a JavaScript-capable browser [e.g., One of the BIG FIVE - Chrome, Firefox, Internet Explorer/Edge, Safari or Opera].

JavaScript Example: Functions alert[] and document.write[] alert["Hello, world!"];

My first JavaScript says:

document.write["

Hello world, again!

"]; document.write["

This document was last modified on " + document.lastModified + ".

"]; How it Works?
  1. JavaScripts are programming codes that are embedded inside an HTML document. The codes are contained between a pair of and tags, as follows: NOTE: In HTML4/XHTML, you need to include attribute type="text/JavaScript" to the opening tag.
  2. You could place the scripts in either the HEAD section [called header script] or BODY section [called body script] of an HTML document. You are free to embed as many scripts into a single document as you like, using multiple ... elements. Lines 7-9 and Line 13-17 are two pieces of JavaScripts, placed in the HEAD and BODY sections, respectively.
  3. JavaScript statements are terminated by a semicolon ';' [like Java/C/C++/C#].
  4. The alert[str] function [Line 8] pops out a dialog box displaying the str and a OK button. Strings are enclosed by a pair of double quotes or single quotes, e.g., "hello" or 'hello'.
  5. The current web page is represented by the so-called document object in the JavaScript. The document.lastModified [Line 16] property stores the last modified date of the current document. The document.write[str] function [Line 14 to 16] can be used to write the specified str to the current document, as part of the current HTML document.
  6. The '+' operator [Line 16] can be used to concatenates two strings [like Java].
  7. As a result of the document.write[], the BODY section of this document contains:

    My First JavaScript says

    Hello world, again!

    This document was last modified on mm/dd/yyyy hh:mm:ss.

  8. The alert[str] and document.write[str] are some of the commonly-used built-in functions provided in JavaScript.

TRY: Print the document's title and the URL location. [Hints: use document.title and document.location properties.]

Don't Get Caught by the Cache - Do Control-Refresh [or Control-F5]

If you modify the codes and reload the web page, the new codes may not get executed because the browser caches the previously loaded version. You could use Control-F5 [Control-Refresh] to ask the browser to discard the cache, and fetch a new page.

Client-Side JS EG 2: Variables and Functions prompt[], confirm[]

This script prompts the user for his/her name, confirms the name, and prints a greeting message.

There are three kinds of pop-up dialog boxes for interacting with the users:

  1. The alert[str] function puts the str on a pop-up box with a OK button. User needs to click the OK button to continue.
  2. The prompt[promptingStr, defaultStr?] function puts up an input pop-up box with the promptingStr with an OK and Cancel buttons. It returns the input entered by the user as a string; or a special value called null if the user hits the Cancel button. The optional parameter defaultStr specifies the initial string to be shown. In this article, I shall indicate optional function parameters with a trailing '?' for compactness.
  3. The confirm[str] function puts str on a pop-up box with OK and Cancel buttons. It returns true if user hits the OK button; or false otherwise.
JavaScript Example: Variables and functions prompt[] and confirm[] var username = prompt["Enter your name: ", ""]; if [confirm["Your name is " + username]] { document.write["

Hello, " + username + "!

"]; } else { document.write["

Hello, world!

"]; }

Welcome to JavaScript!

How it Works?
  1. Line 8 declares a global variable called username, via the keyword var. A variable is a named storage location that holds a value. Once the variable is declared, you can assign [and re-assign] a value to that variable, via the assignment operator '=' [Line 9].
  2. Line 9 invokes the prompt[promptingStr, defaultStr?] function to pop out a dialog box, and reads in the string entered by the user. The string read is assigned to the variable username. The function prompt[] is similar to the alert[], but it accepts a user's input.
  3. In Line 10, the confirm[str] function puts up the message and returns either true or false, depending on whether the user hits the OK or Cancel button.
  4. If the result is true, Line 11 prints "Hello, username!". Otherwise, Line 13 prints "Hello, world!".

TRY: Instead of printing the greeting message using document.write[], do it via an alert[].

Client-Side JS EG 3: The Date Object

The following script creates a Date object representing the current date-time, and prints the current time.

JavaScript Example: The Date object var now = new Date[]; // current date/time var hrs = now.getHours[]; // 0 to 23 var mins = now.getMinutes[]; var secs = now.getSeconds[]; document.writeln["

It is " + now + "

"]; document.writeln["

Hour is " + hrs + "

"]; document.writeln["

Minute is " + mins + "

"]; document.writeln["

Second is " + secs + "

"]; if [hrs < 12] { document.writeln["

Good Morning!

"]; } else { document.writeln["

Good Afternoon!

"]; } How it Works?
  • Line 8 declares a variable called now. It also creates a Date object [via the new operator], which contains the current date-time stamp, and assign it to now.
  • "//" begins an end-of-line comment [Lines 8 and 9]. Comments are ignored by the JavaScript engine but important in explaining your codes to others [and to yourself three days later].
  • Line 9 declares a variable called hrs. It also invokes the function getHours[] on object now, in the form of now.getHours[], to retrieve the hour part of object now, and assign it to variable hrs. Lines 9 and 10, similarly, handle the minutes and seconds.
  • Line 12 to 14 use document.writeln[] to write to the current document. writeln[] [write-line] writes a newline [\n] after the given string. Take note that browser ignores extra white space [newlines, blanks, tabs] in an HTML document; you need to write a

    ...

    or
    tag to ask the browser to display a line break.
  • Lines 16-20 contains a conditional if-then-else statement. Depending on the value of hrs, one of the messages will be displayed.
TRY:
  1. Modify the above script to print the current date, month, year and day of the week. [Hints: Use functions getDate[], getMonth[], getFullYear[] and getDay[] of a Date object. getDate[] returns 1-31. getMonth[] returns 0 to 11 for January to December. getFullYear[] returns a 4-digit year. getDay[] returns 0 to 6 for Sunday to Saturday].
  2. Use a conditional statement to print the day of the week in word [i.e., 0 for Sunday, 1 for Monday and etc.]. [Hints: Use the if-elseif-elseif...else construct as follow.] if [ condition-1 ] { block-1 ; } else if [ condition-2 ] { block-2 ; } else if [ condition-3 ] { block-3 ; ...... ...... } else { block-n ; }

Client-Side JS EG 4: Loops

The following script prompts the user for a multiplier, and prints the multiples of 1 to 100 using a for-loop.

JavaScript Example: Loop

Testing Loop

var multiplier = prompt["Enter a multiplier: "]; for [var number = 1; number

Chủ Đề