Fred Brack   Fred Brack  
Raleigh, NC
Picture of the Cape Hatteras lighthouse

An Introduction to JavaScript
by Fred Brack
Updated

JavaScript LogoAlong with HTML and CSS, the JavaScript programming language is considered a "core technology" of the World Wide Web (read websites), driving many web applications.  The code can be as simply as providing the current 4-digit year ( ... as determined by JavaScript), because HTML can't do that, or as complex as gathering user input to display detailed data from a database.

This is not a full tutorial on the language but rather a brief introduction and reference to its basic features along with some ideas as to how you can get started experimenting on your own.  Want a free tutorial?  Try Learn-JS, which helped me.  And my favorite reference site is W3Schools.  I created this series of JavaScript web pages (see the index at the bottom) to help me document my own understanding of the language as I progress from novice to intermediate user ... and because I like to document stuff for others!  I will come back to it often as a reference document.  I hope you find it useful.

Variables

The starting point for any programming language is how you declare variables (named containers for storing data values).  In JavaScript there are four basic types of variables:

  1. Boolean:  a value which is either "true" or "false" (those exact words)
  2. Number:  like 1, 0, -1, 3.14 ...
  3. String:  always contained within single or double quotes, like "Fred" or 'Fred Brack' or "don't" or ' Please "quote" me! '
  4. Object:  a collection of data; in its simplest form an array of multiple values; but more typically a collection of named values, like "zipcode: 27615" as one of multiple named values in the "person" object

Technically there are five other types of variables:  undefined (declared but uninitialized); null (an empty object pointer); function (actually objects, and discussed below); BigInt (for very large integers); and symbol (fairly new and complicated...).  I have no plans to mention BigInt or symbol; function is important (though it is hard to think of it as a variable); and you will find occasional references to null and undefined.

Each variable name must begin with an alphabetic character (almost always lowercase, but uppercase permitted), or far less common a dollar sign or an underscore. 

How to assign a variable gets interesting!  There are four ways to do this.

  1. const pi = 3.14 (this makes the variable "pi" a constant which cannot subsequently be altered in your program, so it's not really "variable" ...)
  2. var pi = 3.14 (the normal way to declare a variable; its "scope" is global, which means it can be accessed anywhere downwards within your program)
  3. let pi = 3.14 (an alternate way to declare a variable, giving it block scope, making it available wherever you declare it and downwards, not upwards to the caller)
  4. pi = 3.14 (another alternate method which acts mostly like using "var" in front, and would also be used to alter an existing "var" or "let" value)
We interrupt to introduce the semicolon,
which is used as a statement-end character.
While not required, it is highly recommended,
and we will show it from now on.

Note that in each case above, the type of pi (no pun intended) is number or numeric.  However, you could also say:

var pi = "3.14";

which would have a type of string.  In fact, you could redefine the variable pi in this manner, thus changing its type.

You can define multiple variables on one line, if you wish, separating them with commas, or even split the definition between lines:

var a = "alpha", condition = true, 
pi = 3.14;

While I don't intend to cover objects in this introduction (see JavaScript Objects), here are two examples of object definition:

array = [ 1,2,3 ];
object = { firstName:"Fred", lastName:"Brack" };

Brackets define an array, while braces define an object.  Arrays are a type of object, though.  Non-Array objects consist of propertyName:value pairs as shown.

Basic Arithmetic Operators

The basic arithmetic operators are exactly what you would expect:

Like some other languages, JavaScript allows two additional arithmetic notations to automatically increment or decrement a variable by 1:

Example:

var x = 5;
x++; // x now equals 6
We interrupt to introduce the double-slash (//),
which is used to begin a COMMENT.

This is a bit more complicated than it looks, as we have prefix and postfix notation.  If the increment or decrement notation appears before the variable (prefix), the increment is done before using it in an equation.  If it appears after the variable (postfix), the increment is done after using it.  Example:

var x = 5;
var y = ++x; // now both x and y = 6 (because x was incremented before assigning to y)
var z = x++; // now x = 7 and z = 6 (because x was not incremented before assigning to z)

Please note that the plus sign (+) means two things:  add versus join.  For numbers, it means add.  For strings, it means join.  If you combine strings and numbers, they will both be treated as strings.

var x = 5;
var y = 6;
var z = "7"; // string
x+y; // = 11
x+z; // = 57
1+x+z; // = 67 same as (1+x)+z
1+(x+z); // = 157
"Hello"+" "+"there"; // = "Hello there"

Basic Comparison and Logical Operators

Logical operators are typically used in IF statements, but they can be used in many places.  An expression is evaluated and returns a Boolean value of true or false.  The logical operators are used within the expression to create a simple or complex comparison which is ultimately either true or false.  Here is the basic set of operators:

There is an additional operator:  === (three equal signs).  This means that not only must the values match, but the types must match also.  Example:

x = 5
y = "5"
x==y // true
x===y // false

Note from experience!  You will forget that you must use a double equal sign many times; so when your JavaScript fails, look for this problem!

Getting Started Testing

So how do you get started "playing" with JavaScript to test your knowledge?  I would suggest that you use a JavaScript simulator.  The one I'm using is located at https://www.webtoolkitonline.com/javascript-tester.html, but there are others.

This simulator will flag JavaScript syntax errors as soon as you type a line.  But how do you see the values of your calculations?  The simulator will automatically display the result of the last statement if you don't.  Another method is to use the alert function.  It displays results in a dialog box the only operand of which is OK to dismiss it.  The operand of alert is whatever you want displayed.  You can combine items to be displayed with plus-signs (+).  This would allow you to name a variable, for instance, and show its value.  One caveat:  no blanks are included by default, so include any blanks in your quoted string.  Example:

x = 5;
alert("The value of x is " + x);
// The spaces around the plus sign are optional and do NOT result in blanks in the output
// Note, however, the trailing blank after "is"

Alert Box

Alternatively, if you want to create your own HTML page for testing, you can get greater value out of using what's called the debugging console and the console.log function.  (Note:  Ctrl-Shift-I will bring up the debugging tools page, from where you can select Console.  Some browsers, like Mozilla, let you go directly to the console with Ctrl-Shift-K.)  Create a web page with the following content, observing that all your JavaScript code will be placed within <script>...</script>.

<p>Test JavaScript</p>
<p>Results are generally visible in the CONSOLE (Ctrl-Shift-I or Ctrl-Shift-K).</p>
<script>
console.clear();  // this simply clears the console screen
// place your JavaScript statements here ...
console.log(...your message and/or variables here...);
</script>

Now add your JavaScript statements and either publish the code to test or invoke it directly from a web browser.  (I use Microsoft Expression Web's SuperPreview function for this purpose.)  With each change you make, refresh the page and try again.  Exactly how you invoke the debugging console can vary from browser to browser.

To see a list of all the possible debugging options available with the console function, view my JavaScript: Using the console Object document.  You can even cut-and-paste the code from there to try out.

I should mention that I like to simplify displaying my results during testing by using my own function say, as in say("The value of x is " + x).  The definition of say will vary depending on how you test.  You can use any of the following definitions depending on how you are testing!

// Use this one anywhere
function say(msg) { alert(msg) }

// Use this one anywhere you bring up the debugging console (Ctrl-Shift-I or -K)
function say(msg) { console.log(msg) }

// Use this one with https://www.webtoolkitonline.com/javascript-tester.html
function say(msg) { 
  var screen = document.getElementById("screen");
  var div = document.createElement("div");
  div.innerHTML = msg;
  screen.appendChild(div);
}

Functions

Since a tutorial on all the variations of creating a JavaScript function would be quite long, I just want to give a basic definition so you will be better prepared when you look at examples or use existing functions.  A JavaScript function is similar to a subroutine in other languages and is considered a method in JavaScript.  It takes zero or more operands and then has instructions to determine what to do with them before returning.  Because functions are objects, their definition is bounded by braces.  You are required to include a pair of parentheses after the function name, regardless of whether or not any variable names appear within for passed values.  For example:

function funcname ( parm1,parm2 ) {
  // function code to be executed
}

The function definition can appear anywhere in your code and doesn't even have to fall prior to first invocation (though typically it does).  When it is invoked, the statements inside the function definition will be executed.  Remember those variables defined with "var"?  Their values will be available to the code inside the function.  But inside the function, you will probably define any local variables (that is, local to the function) with let () (meaning they have block scope), which is also true of how parm1 and parm2 are handled in the function (meaning that any changes to them will not be reflected back to the caller).  Here is an expanded example of our function:

function addem (parm1,parm2) {
  let text = "The answer is ";
  let answer = parm1+parm2;
  return text+answer;
}
alert(addem(2,3)); // this will return "The answer is 5"
// outside the function, text and answer are undefined

In case you are wondering, you could eliminate the first two lines of the function and replace the last one as follows:

   return "The answer is "+(parm1+parm2);

It is worth noting, however, that the parentheses are required to let the mathematical addition be performed!  Without those parens, the answer would be 23 because the first item in the list was a string; so parm1 and parm2 would be treated as strings.   Also note that no semicolon is required after the closing brace on a function definition.  And another thing:  the return statement stops execution of the function; it does not have to appear last; and you might have multiple return statements in branches of your function.  Any operand of return is returned as the value of the function.  If you run off the end of the function without a return statement being executed, the result is "undefined."

And yes, you might invoke the function in this manner:

sum = addem(2,3);

That should be enough to get you started on experimentation!

Properties and Methods

I said we weren't going to discuss JavaScript objects in this introduction because that is a HUGE area.  However, to understand better how to read JavaScript and use elementary features, we should touch on these two primary characteristics of objects:  properties and methods.

It turns out that even though properties and methods are object features, they can be used with non-object values (called primitive values) too.  For example, length is a property of a string variable, and indexOf is a method to find the position of a value within a string.  You invoke properties and methods by suffixing a variable name with a period, followed by the property or method name.  Methods require parentheses, even if you are not passing an operand.  Examples:

fullName = "Fred Brack";
lthOfName = fullName.length; // = 10; length is a property
posOfBlank = fullName.indexOf(" "); // = 4 (starts with 0); indexOf is a method
alert("The length of " + fullName + " is " + lthOfName); // 10
alert("The blank is found at position " + posOfBlank); // 4 (remember, numbering starts at 0)
alert("The first name is " + fullName.substr(0,posOfBlank) + "."); // substr is a method
We interrupt to discuss names.
JavaScript is unforgiving if you don't use
matching or proper capitalization in names.
This includes variable names, function names,
property and method names.  For example, above
you cannot say "indexof" (instead of indexOf)
or reference "fullname" (instead of fullName).
You WILL make these errors ... often!
And this is as good a time as any to point out that
standard practice is to begin variable or function
names with a lowercase letter and capitalize
any word changes (also known as camelCase),
as in indexOf or fullName.

To learn more about strings and their methods as demonstrated above, see JavaScript Strings next.  You can even cut-and-paste the code from there to try out.

The Document Object Model (DOM)

Like Objects, the DOM is a huge area which won't be discussed yet (see The Document Object Model); but you at least need to know what it is.  The Document Object Model is how JavaScript communicates (reads and writes) with your HTML.  The World Wide Web Consortium (W3C) defines it this way:

The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

Using the DOM structural notation, you can essentially alter anything on an existing web page, though in some cases you will need to identify areas by using an "id" tag on HTML tags (e.g., <h2 id="head2">Heading</h2>.  Your JavaScript will then reference that id to alter the characteristics or content of the heading.  As elsewhere in JavaScript, the DOM has properties and methods.  A property would be an existing HTML element (like our example) where you want to get or set a value.  A method would be an action you take, like inserting or deleting some HTML.

The most elementary thing you should understand about the DOM is how you can insert some HTML on your web page right at the point where your JavaScript is running.  Basically everything in the DOM starts with the word document (the object name) followed by a period and the property or method.  To insert (write) some HTML in your document, you use the document.write notation followed by whatever HTML you want inserted.  Example:

newhtml = "<p>This is new.</p>";
document.write(newhtml);

Obviously you can use your JavaScript to dynamically create whatever it is you are going to write, and it can be as small as the current year or as large as the entire body of the document.  This introduction to the DOM was just to get you to the point where you could write something in your testing HTML, but it is just the tip of the iceberg!

The Browser Object Model (BOM)

The Browser Object Model (BOM) represents the browser in use as opposed to the HTML on the page.  All references typically begin with the object name windowEverything in JavaScript is a member of the window object.  An example of a window method would be causing a new browser window to be opened:  window.open(url).  The following subcategories exist:  screen, location, history, navigator, popup alert, timing, and cookies.  In some cases those words (or related words) must be preceded by "window.", while in other cases they can stand alone.  The popup alert "alert" function is an example.  While technically called via "window.alert," we typically just write "alert" by itself, as shown under Getting Started Testing above.

# # # # #

Index of My JavaScript Articles

I offer these tutorials/reference documents or pages, recommended in this order:

Let me know if this tutorial/reference document was useful, and send in any comments or corrections.

Fred