Learning JavaScript

What is JavaScript?

JavaScript is code that runs inside your browser. It can access and modify elements on the page (also called DOM elements for Document Object Model).

Document Object Model
(Browser/HTML Elements That JavaScript Can Modify)

Using a technique called AJAX (Asynchronous JavaScript And XML), JavaScript can also invoke Web APIs, thereby interacting with server side code that can, for example, access a database.

For a general introduction to JavaScript from W3Schools, click here.

While there, take advantage of the "Try It Yourself" links that let you run the sample code, modify it, then run it again.

JavaScript syntax is very similar to Java syntax, but there are important differences between the two languages:

  • JavaScript is interpreted (each line of code translated just before it is run - error lines discovered only if run), whereas Java is compiled (all lines of code translated once before anything is run - any one error prevents the code from being run at all).
  • JavaScript is loosely typed whereas Java is strongly typed. A JavaScript variable's data type can change at runtime, without needing anything like Java style polymorphism. The type of a JavaScript "variable" is based on whatever that variable happens to contain at the moment.
    • In JavaScript, a function is a data type, just like a String, a number, an array, or an object. And you can pass functions as parameters to other functions, a very powerful feature of the language.
    • In JavaScript, the browser will auto-declare variables for you, if you neglect to do so (and make them global declarations). Since it is generally not desirable to have a lot of globally declared variables, use this line of code (so that the browser will error out instead of auto-declaring variables for you):
          "use strict"; // Prevent auto-declaration of variables  
  • In JavaScript, a function can be defined within another function.
    • A function declared inside of another function can only be access within the scope that it is declared (with some exceptions for function expression declarations, which we will see later). Thus, the outer function is similar to a Java class, with the inner functions similar to methods of that class.
    • In JavaScript, functions can be nested to any level. Once you begin nesting functions more than two levels deep, the JS outer functions act like nested Java packages (or Visual Studio namespaces).
  • JavaScript code organization. There can be JavaScript code before and/or after functions. The code that's not in a function just executes top to bottom, skipping over the function definitions.

First JavaScript Code Example

Click on the green icon to run this example that demonstrates most of the ideas explained above (declaring variables that can dynamically change their data type, how to define and invoke a function). In this particular code example, I have copy/pasted the code into the UI, but generally speaking, after running code examples on this page, right click and "View Source" to see the code.

More About JavaScript

Visit W3Schools.com to learn more about Data Types and functions, then read about JavaScript events.

Click here for more JavaScript example code from W3Schools.

How Do I Debug JavaScript?

NetBeans Editor

The NetBeans editor does a very good job of identifying JS syntax errors, so pay attention to these and resolve as many errors as possible before running your code.

Chrome Console

When debugging your JavaScript code, you will only see runtime error messages if you have Chrome's console open (press F12 then click on "console"). The console will show you the line number of the error and provide a link to the actual code (or just find that number in NetBeans where you can also edit/fix the error).

If you add "console.log( )" statements to your JavaScript code, you'll see that output in Chrome's console. If you "console.log( )" an object (object must be by itself, not concatenated with any text), the object will be displayed "tree form" (collapsible) in the console and this is quite useful for discovering the properties of an object.

Chrome Debugger

Wherever you want your first breakpoint, just add this line of code to your JavaScript:

    debugger; // Sets an initial breakpoint for Chrome's debugger  
Then, when the "debugger" line of code is executed, Chrome (with F12 debug window open) will present an interface like the one below. From here, you can step through your code and/or hover over objects/variables to see their current values.

Click here to learn more about debugging JavaScript with Chrome.

Script Tags

Script Tags in the body

While you can place JavaScript within internal <script>...</script> tags anywhere in the <head> or <body> section of a HTML page, it is customary to place the script tags just before the closing </body> tag. This is so that:

  1. The JavaScript code (that may be trying to access page elements) will not run until after page elements are created.
  2. Loading JavaScript code does not delay the rendering of visual elements on the page.

Script Tags that Reference External JS Files

For any substantial JavaScript code, it is best to organize your project by placing JavaScript code in an external JavaScript file as shown in the example below.

    <script src="myscripts.js"></script>     <!-- referencing an external file filled with JS code -->

        // JS code that's directly in your HTML page


When a project code becomes complex with many external JS files, it can become hard to find any given function. SO... we have this important naming convention (which I am very strict about):

=> Every external JS file shall be named the same as the SINGLE Global Function or SINGLE Global Object that is defined within that JS file.

This naming convention should feel familiar because it is similar to Java that requires the file name to match the name of the class defined within.

Script Tags that Reference CDNs

You can also reference JavaScript code that may be hosted by an external domain. This is called a CDN (stands for Content Delivery Network). To use a CDN, just use the fully qualified URL of the CDN as the value of the src attribute of the <script> tag, like this:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>     

Basic JavaScript Code Examples

These examples include user input and events, changing CSS properties, and setting a timer for a delayed function call. Please note: these introductory examples do not demonstrate good object oriented JavaScript programming practices. They just show basic ways in which you can use JavaScript to manipulate the DOM.

To see the code, click each play button (run it), then right click and "View Source".

Simple Calculations

Adding two numbers using prompt input and alert output (no user interface - typically not done this way, just showing the simplest example).
Adding two numbers using textbox for input and innerHTML for output. Validating if user input is numeric.
  • Demonstrates how you can use document.getElementById( ) to reference any DOM element on the page.
  • Shows how to get user input by using the value of an <input> tag

Slide Show (View Source for code)

Simple slide show using setTimeout( ) to cause something to happen repeatedly.
Slide show with click to start/stop using body onclick event handling.

HTML5 Validation (Client Side)

Using JavaScript to invoke HTML5 Validation.

Accessing DOM Objects with Given Class Name or Data Attribute

How to use document.getElementsByClassName( ) which returns an array of DOM elements instead of single element like document.getElementById( ).
How to access all elements with a given HTML5 custom attribute. You can make up your own attribute names (prefixed with "data-").

Click here for a zip file that contains all the code examples on this page.

Creating JavaScript Objects

Each of the following examples has a "Make" function in an external style sheet. The JS in the HTML page is the "consumer code", focusing on getting input (including events) from the user and passing whatever is necessary to the Make function. The JS in the external file (the Make function) is the "provider code" meaning that it should NOT make any assumptions about what's in the HTML page.

    Remember the important naming convention and software design practice which states each external JS file shall be named the same as the single function or object defined within (and there should be no stray lines of code or other globally declared elements in the file).
NOTE: after running the code, right clicking and Viewing Source, you can click (in the code) the script tag and it will open up the JS code in a separate tab.

Simple JavaScript Custom Objects

JavaScript car object with with all public properties and methods.
JavaScript car object with some private properties and a private method.
  • Encapsulation (having private properties and methods) is an important software design concept that prevents errors as software increases in complexity.
Define "closure" which is what we use to get "private properties".

Passing a Parameter Object Instead of a Parameter List to a Function

A desirable software design pattern is to pass a parameter object (instead of a parameter list) to a function. Why?
  • Passing a parameter object is self documenting - it shows which values are being passed into which properties (and you don't have to check the order of variables in the parameter list).
  • It makes it easy for the calling code to skip whatever optional parameters they don't want to pass in (and when an optional property is not provided, the receiving function can provide default values).

Event Handling

Events from the HTML page triggers object methods.
Car object has built in events (swipe mouse through divs to see colors change).

User Input Data

User input data from the HTML page is passed to to object setter/modifier functions (methods).

Setting CSS Style and Adding Image Tags

Car object sets style (of the visual representation of the car object).
Visual representation of the car object has an image tag.

Two Ways to Create JS Objects

Suggest you NOT create objects this way, although you may find examples on the internet where they create an object using the "new" keyword and rely heavily on the keyword "this" to mean the current object (like in java). The problem is that if we use "this" to mean the current object, then things get tricky when our objects (with visual representations on the page) become complex with subparts having their own event handling -- because then we will want "this" to mean whatever part the user clicked or hovered over (not the whole object).
Suggest you create objects this way, (without using "new" and without using "this" to mean the current object). This frees up the keyword "this" to be used for event handling within the object.

Associative Array Notation

Shows how you can create a "hash" in JavaScript using "associative array notation". With this syntax, instead of using an integer as index (inside the square brackets), you use a "key" (usually a String). Then you can place your values inside and/or retrieve them by the key.

Iterate Through Object Properties

Shows how you can discover the values within an object, even if you do not know the names of the properties within the object.

Click here for a zip file that contains all the code on this page.

Dropdown Menus

Simplest Drop Down Menu - Single JS Toggle Function

This is a simple JavaScript function that just toggles the content associated with a drop down menu header. Toggle means to hide an element if it is showing or show an element if it is hiding. The HTML page must pass in the id of the content that is to be toggled. This simple code is easy to understand, but its functionality lacks sophistication. For example, you can open more than one drop down menu at a time and clicking outside the menu area does not close any open drop down menu.

Better User Functionality

This code provides better functionality and it's now more than just a single function.
  • If the user opens one drop down menu, any open drop down menu is closed first.
  • If the user clicks outside the menu area, any open drop down menu is closed.

BUT the HTML coder still has to pass the id of the content associated with each drop down menu header.

Less Work For HTML Coder

In this version, the HTML coder does not have to assign onclick handler functions to all the drop header elements, nor do they have to assign ids to the associated drop content elements. The JS code automatically assigns an onclick function to each drop header element. This onclick function determines which drop content should be opened/closed by navigating to the parent (of the clicked element), then from there, finding the first child element with the drop content style.

Click here for a zip file that contains all the code examples on this page.

Professional Looking Modal Windows

A modal window is simply a window that "goes in front" of everything else. The user must then deal with this window, e.g., by filling it in and clicking submit or by closing it out.

JavaScript Built In Modal Windows (alert, confirm, prompt)

Page that shows JavaScript built-in modal windows: "alert", "confirm", and "prompt" (all of which have a very unprofessional looking user interface).
  • With JS alert you can display information to the user.
  • With JS confirm you can ask the user to confirm or cancel an operation.
  • With JS prompt you can ask the user to enter data.

Creating Modal Window Alert Using JavaScript

ANTI-PATTERN (don't copy this code): using JavaScript to customize your own modal window (creating a DOM object with fixed positioning and CSS styling). This code is provided for educational reasons (it is simple to understand). HOWEVER (as previously mentioned), it is bad design because it defines functions and has lines of code running at the global level. The next example shows the same code but well designed (encapsulated).
GOOD DESIGN (OK to emmulate this): using JavaScript IIFE (immediately invoked function expression) to encapsulate modal window code.

Adding Confirm to Alert (Sharing Private Functions)

This version adds a confirm method to the alert method (sharing some common code). Click on the two buttons in the home content area to test the two different types of modal windows (alert/display versus confirm).
This code demonstrates the two styles of modals (alert and confirm) within a normal page layout.

Click here for a zip file that contains all the code examples on this page.

Working With Lists of Objects

JS Sorting

Sorting a list of objects that have public properties (uses JS associative array notation to access public properties to determine sort order).
Sorting a list of objects that has private properties (uses JS eval function to invoke appropriate getter functions to determine sort order).

List of Objects in HTML page

The HTML page allows the user to modify employees within a list (Make employee function in external file).

Object Composition

Object contains a list of Employees.
Deleting Employee from list (basic User Interface).
Deleting Employee from list (better User Interface - clickable delete icon per Employee).
Updating Employee within list.

Click here to learn more about object oriented JavaScript.

Click here for a zip file that contains all the code examples on this page.

Client Side Data Persistence (Local Storage)

Since HTML5, we use Local Storage instead of Cookies if we want to persist data on the client side. Both approaches essentially allow you to set name/value pairs to a local file on the user's machine and then you can retrieve the value back if you provide the name. Click here to learn more about Local Storage, but here are some of the main points:

  1. Local Storage can store more than Cookies (5MB instead of 4KB).
  2. Local Storage does not slow things down like Cookies (because Local Storage does not send all the data to the server with every http request).
  3. Local Storage uses the Same Origin policy - essentially meaning that data that written by one application can only be read by that application.
  4. Local Storage (unlike Cookies) never expires. If you want your data to be deleted when the user closes out the browser (or tab), use sessionStorage (has the same methods as localStorage: getItem, setItem, removeItem).
Reading/writing data (name/value pairs) to/from Local Storage.
Reading/writing JavaScript objects to/from Local Storage - uses JSON.stringify( ) and JSON.parse( ).
Allowing user to select their desired layout (with persistence upon page refresh).

Click here for a zip file that contains all the code examples on this page.

New JS Features (ES6)

ECMAScript 6 (also called ES6) is a new JavaScript specification that introduced some nice new features. It is important to learn ES6 because React (a popular JS framework we'll be learning) uses ES6 extensively. Unless you are familiar with ES6 syntax, you'll get lost in the React sample code.

Before getting to the ES6 sample code, let me just mention that ES6 introduced two new keywords: let and const.

  • Whereas the scope of a variable declared with "var" is the function of declaration, the scope of a variable declared with "let" is the block of declaration (more like java).
  • With the "const" keyword, you can define a constant which will cause a runtime error if any code later tries to change its value (again, like java).

ES6 Examples

Arrow Functions are an abbreviated way to define functions, but they also handle the keyword "this" differently. In an arrow function, "this" means the parent function, not the arrow function itself. Therefore, when using React, some code that's implemented with an arrow function will not work properly if converted to a "normal" (non arrow) function.
Object and array destructuring are used extensively in React code. These examples will explain the syntax and show how to use destructuring.
This shows how to use object destructuring in function parameters.
In JavaScript, you can use either single quote ' or double quote " to delimit String literals. Now with ES6, you can also use backtick ` which can be very helpful if you need to have quotes inside of quotes inside of quotes. The backtick also allows the definition of multi-line String literals which can be quite useful if you are trying to represent multi-line HTML code.
Using ES6 binding ${variableName} along with backtick, you can inject the value of a JavaScript variable into a String literal.
With ES6, you can write JavaScript code that looks like Java classes.
Using the "extends" keyword, you can define "classes" that inherit from other classes (again, like java).

Click here for a zip file that contains all the code examples on this page.

Functional JavaScript Programming

Functional programming in JavaScript has become very popular lately, but what why? Let's start by examining what is a "pure function".

  • A pure function is one that always gives the same result (given the same input parameters). So a functional programming purest would never allow a function to reference variables that are outside the function.
  • A pure function has no side effects. So a functional programming purist would create a new variable rather than changing an old one. That way, each variable has just one meaning - regardless of where we are in the code.

To get a brief taste of basic JS functional programming, run the examples below (and view the source). If you want to learn more, click here to read this article on functional JS programming by James Sinclair (starts out very easy and finally gets very advanced).

For Each - you can iterate over a list without needing to set up an index variable and "for loop".
Filter - you can create a new array that is a subset of another array (based on some filter criteria) without a "for loop".
Map - you can create a new array that holds all elements of another array, but after getting transformed by some function (without a "for loop").
Alphabetic Sort - every JS array has a built in sort method. To use it, you supply a function (as input to the sort method) that takes in two elements of the array and returns 1, 0, or -1 depending on whether the first element is greater than, equal to, or less than the second (respectively).
Numeric Sort - using the JS built in sort method, passing in a function that will result in a numeric sort of elements in an array.
Reduce - you can specify how to do things like create the total of all elements in an array (without needing a "for loop").

Click here for a zip file that contains all the code examples on this page.

JavaScript Injection Hack and How To Prevent It

JavaScript injection occurs when a hacker inputs data that has JavaScript in it and then that data is to a database. Then, whenever normal users (victims) visit that site and view that data, the hacker's JavaScript runs on the victims computers - their cookie (local storage) information can be stolen. Hackers do not even need to use sophisticated JavaScript, they just need to be able to exploit certain vulnerabilities:

  1. One web site must store sensitive information (e.g., logon credentials or access level) in a cookie or local storage.
  2. Another web site allows does not strip JavaScript code from user entered data before storing it into a database.
  3. Some users regularly use both web sites (or it could be one site that has both vulnerabilities).
How do you write a web application that prevents JavaScript injection hacks? Simply:
  1. Make sure your web site never stores (or relies upon) any sensitive information that is stored in a cookie on a client machine (especially not user login information and/or username/password.)
  2. Always "clean" all user entered data before storing it into a database (or anywhere server-side).
For a Code Example that demonstrates JavaScript (and SQL) injection hacks, click here (zip file). Since this example uses server side code (requires database access), you'll have to wait until you have learned how to install and run such programs.

JavaScript Online Books