DevTech

Discussing the Latest Development Technologies

JavaScript, jQuery, TypeScript: Chapter 3, part 2

String Type

Let’s continue our discussion by talking about the String type. The string is a very interesting type because it is really made up of a number of bytes.  But the number of bytes is variable (depending upon the length of the string) and that is unlike the Number and Boolean types where the Interpreter knows the maximum number of bytes the data type will take up.  We will see how this creates a significant challenge for the developers who create programming languages like JavaScript.

You can create a String with the following code.

var firstName = "robert";
console.log("firstName is a " + typeof firstName);

You can see this code and run it at jsfiddle:
https://jsfiddle.net/raddevus/k7b2f8zv/

As I said, strings are a different, because each character in the string takes a byte to store, but the length of the string can not be determined until the variable has it's value set.
The Interpreter (and lower layers of technology, like web browser and the Operating System) still has the constraint that it must find contiguous memory to store the string in.  

That means there is more work for the underlying layers to do to store your string.
Let's look at this a bit more closely by looking at the memory when you store a string with the following JavaScript:

var companyName = "Big House";

Take a look at Figure 7: string in memory.

string in memory

Terminating Character

First of all notice that last odd character located at 0x00CD01. Since the string can be any length, there has to be a way to determine the last byte that is associated with the string so the Interpreter can determine where the string ends and not read other random bytes into the string from memory.  In C and C++ they used a \0 (backslash followed by zero) to denote this. That could just be the ASCII Zero byte (ASCII value 0, aka Null byte).  It's probably the same in JavaScript.

Or, it is possible that JavaScript automatically stores the length of the string in another associated address which contains a Number value.  That would mean that Interpreter would first retrieve the address where the size of the string is and get the number of bytes and then it would retrieve the actual string. 

VisualBasic used a type called a BString which used the first X bytes of the string to store its length. Of course, every time the string changes that value has to be updated.

The point to take away from this is that someone has to handle the issue that strings are of different lengths and the constraint that associated memory for a variable has to be contiguous.

What If The String Grows?

All of this should bring to mind the main problem.  What if the string becomes longer, because you set it to a new string value?
For example, if later in the program you store:

companyName = "Big House Crafts";

Suddenly the program needs seven more contiguous bytes (one space plus six letters).  But, what if the bytes past 0x00CD01 are already taken for use with other variables?

Strings Are Immutable

This is exactly why strings are immutable in JavaScript (and most other languages).  Immutable means they cannot be changed.

But that might seem odd that I'm saying that, because in the JavaScript code we did indeed set the companName variable to one value and then we set it to another value later so it seems we have changed it. 

However, it is underneath JavaScript where the string has not changed : in the actual memory where the program's data is stored.

It's A Whole New String

That's because when you change a string like we did in the previous code, it doesn’t not just change the value stored at the original address.  Instead, the original address is cleared and removed from the internal lookup table.

Then, the Interpreter

  1. calculates the amount of memory your new string is going to take,
  2. goes out and finds enough contiguous bytes,
  3. gets the new address,
  4. stores the address in the internal lookup table
  5. and finally, sets the value of those bytes.  

You now have a whole new string -- a new address where the string is stored.

This also explains why adding characters to a string can be much slower (more processor intensive) than what is expected by the developer.  There is much more work involved than just adding the new character to the end of the string.

 That's all for this installment, but next time we'll dig a big deeper into strings and then talk about Reference types.

Keep on learning, keep on programming.

~Roger Deutsch

JavaScript, jQuery, TypeScript: Chapter 3, part 1

Setting the Foundation: JavaScript Data Types


Because of the way the mind works, it is easiest to learn when we focus on one thing at a time.  However, when taking on a subject as large as JavaScript which has been in use since it was originally created by Brendan Eich for use in Netscape Navigator 2.0 back in September of 1995, it can be a challenge to know what to focus on first.  Additionally, if you don't get your basic foundations set in place it can be much more difficult to learn advanced concepts later.

That's why I want to take you back to a very basic concept which underlies everything that goes on in JavaScript: The Type System.

At first glance, you may think focusing on the type system is too simple and boring, but I promise I'll keep it short and lively and when we're done you'll understand how JavaScript works better than ever.

How JavaScript Handles Types


In JavaScript – as in many high-level languages – all types can be organized into two categories:

  1. Primitive types -- memory address indicates where the data (or value) is stored.*
  2. Reference types -- memory address indicates where the object is stored.*


* This statement may be confusing. I'll explain this in just a few moments.


First, let's take a look at the primitives.
There are only six primitive types in JavaScript and they are:

  1. Number
  2. Boolean
  3. String
  4. undefined
  5. Null
  6. Symbol (New to JavaScript 2015)

Those last three probably look a little odd to you and we'll get to them, but first let's take a look at the first three and learn why it is important to understand that all of these are primitive types.  Then, we'll delve into Reference Types and how they are different. The knowledge of the contrast of these two types will actually help you understand how the JavaScript Interpreter – which runs all of your JavaScript code – works and how that creating Objects (Reference types) is so much different than creating these Primitive types.


Creating any one of the Primitive types is very easy in JavaScript.
Just type the keyword var followed by the name you want to use to refer to your variable and then set it to some value.

var counter = 0; // becomes a Number type
var isConfigured  = false; // becomes a Boolean type
var firstName = “David”; // becomes a String

typeof Operator Indicates Type From JavaScript Interpreter

We can use the typeof operator to determine what type the JavaScript Interpreter believes a variable is.  Of course, whatever the JavaScript Interpreter believes your variable type to be is what it is.

Here's some code to show you how the typeof operator works.

var counter = 0; // becomes a Number type
var isConfigured  = false; // becomes a Boolean type
var firstName = “David”; // becomes a String
console.log("counter is a " + typeof counter);
console.log("isConfigured is a " + typeof isConfigured);
console.log("firstName is a " +  typeof firstName);

After you run this code and view the console output you should see the following:

counter is a number
isConfigured is a boolean
firstName is a string

See It Run At JSFiddle

JSFiddle is a site that allows you to create HTML, CSS and JavaScript and run it in your browser.

I’ve taken the previous code and added it to a script there so you can see it run if you like.  To check it out, just point your browser at: https://jsfiddle.net/raddevus/x7zw0cka/

NOTE: The script includes some code (document.getElementById(“1”)) that gets the HTML DIV with a specific ID and set its text to the output.  I won’t explain that code right now but we’ll learn all about it later.

A Closer Look At Your Number Variable

Now allow me to go back to that somewhat odd statement I made about primitives where I stated:

"...memory address indicates where the data (or value) is stored."

 

What does that mean?
To understand it better you have to remember that all data is stored in memory at some addressable location.  Data has to be stored that way so that other program elements can access it. Otherwise, if there was no way to tell where the data was stored, there would be no way the computer program could manipulate or display the data and that data would become inaccessible and useless.

You Write JavaScript, You Control Memory Chips

Also, keep in mind that down at the bottom, somewhere the value you indicated you want to store is actually stored in memory somewhere which has a unique address.  That's right, you are actually controlling the switches on a memory chip somewhere in the computer simply by typing:

var x = 55;
 

Again, all you have to do to create a Number in JavaScript is write code like the following:

var x = 31;
var z = 56;

What The JavaScript Interpreter Does

The JavaScript Interpreter notices that you've set the value to a numeric and decides that the type will be Number.  Since it is a Number, the Interpreter knows that it will require a certain number of bytes to store up to a maximum value.
It is necessary for the Interpreter to know what type it is because of what is really going on behind the scenes – at the lower level of computing.  When you simply create a Number variable (var counter = 5;) the Javascript Interpreter has to do a some things so the computer's processor knows what you want to do.


Here are some of those things the Interpreter does:

  1. Determine the data type so it knows how many bytes of memory it needs to store the data
  2. Find a memory location which has enough contiguous slots to store a Number type.
  3. Create an entry in an internal lookup table to store the name of your variable with the name of your variable – so it can know where your variable is stored in memory when you refer to it using the name you defined.


First Step: Determine Type

The Interpreter needs to know the data type because each type requires a different amount of memory.

Second Step: Find Memory

To complete the second step, the JavaScript Interpreter has to know the number of bytes that a Number type takes up in memory.

The Architects of the JavaScript Interpreter

In the case of a primitive type (Number, Boolean, String, etc) the architects who created the JavaScript Interpreter have decided that each of them will take a predetermined number of bytes in memory.

JavaScript Primitive Number: 64 bits (8 bytes)

Currently in JavaScript running in browsers Number types get 8 bytes (64 bits) of memory space.  Some architect made that decision as a trade-off on the max value that you can store and the memory it will take up for every Number in your program.

Keep in mind that since they’ve chosen 8 bytes for a Number then the max number you can store in the Number type is : 1.7976931348623157e+308

That is a huge number and you can check that number by typing the following in your browser’s developer console and press <ENTER>.

Number.MAX_VALUE

Now, let’s continue our discussion of what happens in memory.


At the lower level where the CPU (main processor) is running and where memory is read in bits, it makes things much easier for a low-level programmer when data is written in sequential memory addresses and that’s basically why data is stored in contiguous memory locations (memory addresses that are next to each other).

What It Looks Like

When you create a new number variable the JavaScript Interpreter goes out and finds 8 sequential bytes in the addressable memory space that is available to it and sets the bits it finds there to represent the value you have stored.

var counter = 27;  

Interpreter stores 27 at the address 0x00FFC0.
counter in memory



Take a close look at Figure 1.
Imagine that each rectangle represents a byte of memory.  Most modern computers only allow you to address one byte of memory (not down to bit level) and so each address represents that one byte.  In our case when we wrote var counter = 27; the Interpreter found 8 bytes of memory which starts at address 0x00CCF0 and it sets the bits to equal 27.

Also, note that even though we can store the value using only the first byte, the Interpreter (and web browser and Operating System) actually set aside the entire 8 byte block of memory.  I've set those bytes to have all their bits zeroed out to indicate that they are in use. That means nothing else can use those bytes or else JavaScript would interpret that to mean that the value of counter had changed.  That memory (that set of eight bytes) is solely under the control of JavaScript for the purpose of storing values to the counter variable.


Reading and Writing That Memory


The JavaScript Interpreter remembers that your name of counter is how it will get to that memory.  That way when code further down in your program does something like:

counter++; // increment the counter

Then it can retrieve the value that is stored there (27), add one to that value and store it in the same place again so that memory will now look like what you see in Figure 2: Value 28 stored at location.

counter is incremented

Memory Addresses Are Arbitrary

Please keep in mind as you study these figures which represent memory that the addresses are completely arbitrary and made up for instructional purposes.  It’s just a way to explain to you what is going on in memory and the memory addresses would change each time the code is run.

Previously the value was :     00011011  (decimal 27)

Now the value is :                00011100 (decimal 28)


Value Stored At Address Is Changed

The point here is that the value stored at the memory address has changed.  Also, now that the Interpreter has stored the address where this data is located, you cannot change that address within this program.  It is locked. That means you can update the value at the address by changing the value of your variable, but you can never change the address that the variable points to -- the location where the data is stored.  Interestingly, as a matter of fact, in other languages (C, C++) there are pointer variables which allow you to change the address the variable points to.


In just a moment we will contrast this to what happens when a Reference type is changed and you will discover it is very important to your understanding of how JavaScript works.

undefined Will Make More Sense Now

Now that I've explained that, I can better explain to you the undefined primitive value.  Remember when I told you that when you set the variable to a value then the JavaScript Interpreter decides what type it is?  

 
 

Well, suppose you do the following in JavaScript:

var x;

What type is x?  The JavaScript interpreter bases the type on the data that is stored in the variable, but we have not stored any data in the variable yet so it’s type is undefined.

It is an undefined and we can prove it with the following code:

var x;
console.log("x is " + typeof x + " type");



Now, let's think about what JavaScript has to do in this case.  It cannot determine the type and yet it has to keep track of the fact that you are attempting to refer to a new variable named x.  But, what should the value of x be? In many languages (C++, C#, Java – no relation to JavaScript) it has a special value referred to as null.  But in JavaScript the architects have created another special value called undefined for this case.

In this case, the variable has not had any memory assigned to it. It cannot, because the Interpreter has no idea how much memory the thing will take up in memory, since it does not yet know the type.


My Guess At How undefined Is Defined

Here's my guess at what JavaScript does.
Somewhere way down in memory, there is one lonely address that has an undefined type sitting in it.  It may look something like what you see in Figure 3: the one undefined object in the address space.

undefined in memory

Then, when you create a new variable without setting it's value, the Interpreter stores the name of your variable in its lookup table and then sets its value of its address to that location (0x000001) so that when you ask what type var x is, it returns the type it is pointing to: undefined.

That is supposed to indicate to the JavaScript developer that the variable has not had its value (or associated type) set yet.

So far we've looked at two of the primitive types Number and undefined.  Let's take a closer look at the Boolean and String types, because they are very similar to Number, then we'll look at our Reference types and it'll be a bit easier to understand the null type.

Booleans Are Easy, But Remember true/false Are Lowercase

A Boolean simply allows you to create a variable that stores only two states: true or false.

You can create a Boolean variable very easily:

var isConfigured = true;
console.log("isConfigured is a " + typeof isConfigured);


If you run that code in your console window you will see the result shown in

Figure 4, below.

 

 

Notice that the true is lowercase.  It has to be because lowercase true and lowercase false are keywords in JavaScript and JavaScript is case-sensitive so True and False are not keywords.

You can see that by running this code:

var isConfigured = False;
console.log("isConfigured is a " + typeof isConfigured);

False is undefined in JavaScript so you get an error as soon as you attempt to set the variable.

False is undefined

Boolean, Probably Stores In One Byte

A Boolean probably stores in one byte since you could literally store it in one bit (either 1 or 0).   The Boolean probably looks similar to what is shown in Figure 6: Boolean value of true (1) stored in memory.

isConfigured boolean stored in memory

If the value is false, then most likely all bits are 0 with a final value of 0.  However, notice again, that it stores the value of the variable at the memory address because it is a primitive type (not a reference type).

Summary of Chapter 3, Part 1

We covered a lot of material in this part and we took a different view of the primitives in memory in an effort to describe how data types are stored from a computer science perspective.  I believe that understanding this will open you up to better understanding what JavaScript and your browser are doing behind the scenes as you write code.

JavaScript, jQuery, TypeScript: Chapter 2

Get all the source for this chapter at my public GitHub : https://github.com/raddevus/jsjqts

JavaScript (as we talk about it in this book) runs in the browser. However, to run JavaScript in the browser it has to be loaded first. JavaScript is loaded by way of the html document.

That means the first thing we need to do is get a skeleton html document setup.

Here’s a basic HTML5 document.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Your title here</title>
</head>
<body>
Your content here
</body>
</html>

That’s all you need.  

DocType

The first line tells the browser’s HTML interpreter (a separate interpreter from the JavaScript interpreter) to expect valid HTML.

Meta Charset

The meta tag sets up the character set that the browser will use so that we don’t run into problems where characters are interpreted differently (like the double-quotes problem I mentioned earlier).

Inline JavaScript

We can write our JavaScript code right inside our HTML and it will run.

To do that we add two script elements (beginning and ending tags) and then type our JavaScript within those two elements.

For example within the previous document we could do something like the following:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Your title here</title>
</head>
<body>
Your content here
<script>// your code here</script>
</body>
</html>

You may also see the script tag include the type attribute which explicitly sets the script as being JavaScript:

type="text/javascript"

However, that is not necessary because browsers will assume the code within the script tag is JavaScript.  

HTML Loads Inline JavaScript

The challenge of inline JavaScript is that it will not have any knowledge of HTML elements which come after it.  That’s because of the way that HTML loads in a browser and when JavaScript runs.

We’ll look at the idea of how the JavaScript loads as we move forward, but first let’s see a small script run.

Here’s the entire code listing including the HTML which you can find in the chpt002_001.htm file (

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Your title here</title>
</head>
<body>
   <div id="first">
   Your content here
   </div>
<script>
  var el = document.getElementById("first");
   el.innerText = "You are a JavaScript superstar!";
</script>
</body>
</html>

 If you open that file in a browser it will look something like the following:

I’ve highlighted (with the red rectangles) the two important parts of the document to focus on.

The first one is the title text that comes from the title element in the head section of the HTML document.

The next one is the text that appears within the document’s body.  It is actually the innerText of the div element with the id=”first”.

Here is what happened when you loaded the file in your browser.

  1. The browser fetches the chpt002_001.htm file and begins loading it
  2. When the browser gets to the script element it loads the text and allows the internal JavaScript interpreter to take over.
  3. The JavaScript interpreter finds the first valid statement (the first line inside the script element) and attempts to run it.  It calls a method named getElementById() on the document element (the object that represents the HTML document -- the DOM (Document Object Model).
  4. The getElementById() method takes one parameter which is a string that represents the id value of the element you are searching for.  It returns the element as an object and that object is stored in a variable named el.
  5. The element is a document node and contains a built-in property named innerText which represents the text between the element’s tags : in our case between <div id=”first”> and </div>.
  6. Finally, the script sets the innerText to “You are a JavaScript superstar!"
  7. That is what the user sees on the screen in the client area (below the browser menu and navigation bar).

 

Of course, the HTML document contains different text in the div before the JavaScript runs.

It looks like:

<div id="first">
   Your content here
</div>

 

But the user never sees that text because the document loads so fast and the JavaScript interpreter runs and alters the text before the user ever sees the original text.

However, the JavaScript only alters the div element in memory so there is a way to see the original text of the document.  

Browser : View Source

You can view the source (HTML and JavaScript) of any document by right-clicking in the client area and selecting [View Page Source]* from the context menu that appears.

*Note: Some browsers have a menu item which is simply [View Source].

View Source

 

When you choose the menu item, the browser will retrieve the document from the server again but display it as HTML.  

 

html source view
Since this is a view of the source the JavaScript interpreter does not run and the <div> element still displays its original content.  This view also shows the content of the script tag so your JavaScript code is exposed to everyone. Normally that isn’t really a problem but it is something to keep in mind since any user could view the JavaScript that you’ve written. It certainly means you’d never keep a secret password or value in your JavaScript.

This view can be very helpful for us as developers so we can take a look at page source and begin to determine why our code may not be working.

This was a very trivial example so the JavaScript is inline with the HTML.  However, as soon as your code becomes a bit more complex you are going to find that to make changes easier it is far better to split your JavaScript into its own file. 

Why Might You Split Out Your JavaScript?

One of the most obvious reasons to split it up is because you may create a script that you want to run on multiple pages.  Maybe you have a function named FormatDivElements() and it is used to do work on all the divs on every page in your site. If you put the code inline then you’ll have to copy the same code to every page that uses it.  So if you have five HTML pages thas the FormatDivElements() function then you’ll have to paste it into each of those files.

Then, what happens if you discover a bug in that function and want to fix it?  You have to edit it on every page that uses the code.

But, if you separate out your JavaScript, you can load the JavaScript file in each page and when you need to change it you’ll only have to edit that one JavaScript file and it will get updated on all the pages that use it.

Separation of Concerns

This idea also allows us to keep our different types (HTML, JavaScript) of code from being dependent upon each other and making things more difficult to change or extend later.  You will hear this described as Separation of Concerns (SoC). Separation of Concerns just means keeping different things separate from each other and putting similar things together.

In our case that means keeping your HTML file pure HTML (as much as possible) and keeping your JavaScript pure JavaScript.  You will see that this also pertains to CSS (Cascading Style Sheets) which can also be placed inline in the HTML but is far better when it is separated into its own CSS file.

 Here’s how easy it is to separate our JavaScript into its own file.

  1. Create a new file and name it main.js
  2. Cut all the source code from the script element (do not copy the script tags themselves, because JavaScript files do not use those tags)
  3. Paste the code into the new file
  4. Save the code in a file named chpt002_002.js in a sub-folder named \js (I’m going to save the HTML as chpt002_002.htm so you can download this example so I’m making the JS file match)
  5. Add the src attribute to the script element in the HTML file
  6. Set the src=”js\chpt002_002.js” so the HTML file knows where to load the JavaScript from.

two lines to cut


Here’s what the HTML file looks like after we remove the code and add the src attribute.

 altered source

You can see that I also collapsed the script element to one line since it doesn’t contain any code.

 

Now you can load chpt002_002.htm and the result will look just like chpt002_001.htm.

However, if you load the page and then right click it and [View Page Source] you will see that the JavaScript is no longer inline.


script no longer inline

In most (if not all) browsers you can now click the src link and the browser will load your JavaScript file and display it.

 

click src link to view js

You can also see that I like to add a first line comment in my JS files that tells me which file I’m looking at.   

 

JavaScript Comments

To add a line as a comment you simply start the JavaScript line with two slash characters (//).  Any text after that on the line will be ignored by the JavaScript interpreter as if it does not exist.

The next line will resume code as normal.  If you want multiple lines of comments you should add // to those lines also.  There is an accepted multi-line comment but it is warned against because it can cause you problems when you comment out numerous lines of code by accident.  The multi-line comment starts with /* and it ends with */ so that anything in between those two tokes will be seen as comments by the JavaScript interpreter.

Chapter Summary

That’s it for this chapter.  Now you know the proper way to set up your HTML and JavaScript files. This is how all the code in the rest of our examples will look so it is important that you understand how this all works.  

What’s Next?

Now that we have our working process we can begin a much closer inspection of pure JavaScript.  In the next chapter we’ll take a look at the fundamentals of JavaScript such as data types, statements, control structures (if statements, for loops, etc).  These are the nuts and bolts of JavaScript that allow you to build larger apps. In chapters that follow we’ll look at functions and classes (including points about prototypal inheritance).  I’ll also show you some of the commonly used built-in features like JavaScript timers and other features that will help you build apps.

 All of this will set the table for you to easily learn jQuery and be able to see the huge benefits that jQuery can bring.

JavaScript, jQuery, TypeScript: Chapter 1

Why Learn Pure JavaScript?

Learning pure JavaScript (JavaScript only with no other libraries like jQuery) is important because the more familiar you are with JavaScript the easier it will be for you to use the other JavaScript-based libraries.   It will also help you understand why those other libraries were created (in most cases to make JavaScript easier to use).

Also, once you see how difficult some things are in JavaScript you will have a better appreciation for the way that jQuery and TypeScript make certain things easier to do.

Seeing A Result Makes Learning Easier

The first thing that is important to your learning is knowing how to see a result.  Browser developers have made things a lot easier these days by including Development Tools right in the browsers themselves.   

If you press F12 (in most browsers - definitely works in FireFox, Chrome, Edge) then you will see a new window area pop open.

I’ve pressed F12 in FireFox on my Arduino blog so you can see what this will look like.


Everything below the red line I added is the Browser Console.  There are also a number of tabs in that lower section. The first one is [imposter] and the second one which is currently selected is [Console]. The third one is [Debugger] and you can see the rest of them.

Pressing F12 opens the sub-window up with the [Console] tab already selected, which is indicated by the faint blue line and the blue text (“Console”).

In FireFox you can enter JavaScript statements at the very bottom where it shows that grey >>.  You just click to the right of it and type the JavaScript you want to run, hit <ENTER> and your code will run.

Go ahead and type: 2+2<ENTER>

When you do, FireFox will allow the JavaScript interpreter to run to evaluate the code and then it will print the result in the Console.  Also notice that when you press your <ENTER> key the Console window clears out the text you’ve typed from the >> line. That’s just a convenience so you can type another command.

 

Other Browsers Differ A Bit

If you are using Microsoft Edge the Console window looks a bit different, but you’ll be able to find your way around.

 

Errors Show Up Too

If you had typed something that the JavaScript interpreter could not understand it would give you an error.

 

I typed some nonsense :

sda =ewwlj<ENTER>

 

The JavaScript interpreter didn’t know what to do with that so it attempted to give me an idea of what it didn’t understand.

 

The Console Will Remember All the Code You Type

You can type numerous lines of JavaScript code and the Console will remember it as if you are typing in a larger program.  

For example, I’ll type in the following commands:

>> var x = 2 + 2<ENTER>

>> console.log(“This value of  x is “ + x)<ENTER>

 

Each time after I typed a line and pressed <ENTER> then the JavaScript interpreter responds with ← undefined.  This isn’t a problem. It just indicates that the browser is slightly confused about what is happening. It thinks that you are running a function that has no return value.  You don’t have to worry about that for now.

Strange Characters and Text

Sometimes a character on the screen is something different than what the JavaScript interpreter thinks it is.  This is true for double-quote characters. They are represented in different editors in by various characters. It’s a long story but the point is that if you copy my code instead of typing the double-quote characters then you may see a different and erroneous result. If you see something odd happen then that may be the problem.

 

Finally, as you can see, when you type the second line that references the variable x (var x) the interpreter remembers the value of x and is able to print it out.

 

If you hadn’t already defined x then the interpreter would’ve given you an error.  

For example, type the letter q and press <ENTER>.

Now the interpreter tells you that q is not defined and that there is a ReferenceError. That means the JavaScript interpreter does not know about something you are referring to.

 

Odd Error Language of JavaScript Interpreter

Already you are beginning to experience the odd language that the JavaScript interpreter uses to warn you about things. You also notice that sometimes the interpreter tells you something is ← undefined and you can ignore it.  Then other times it tells you there was a ReferenceError and something is not defined and you need to pay attention.

These messages are created by the developers who created the browser.  That means these messages will often vary from one browser to the next (Edge is different than FireFox, etc).  Usually they are similar so you will be able to figure it out. Here’s the q error in Microsoft Edge.

The better you become at discerning what these cryptic little messages mean, the better JavaScript programmer you will be, because you’ll be able to figure out what is wrong with your own programs.

 

This Isn’t Really The Way We Write JavaScript Programs

Of course typing code into the JavaScript console isn’t really the way we write JavaScript programs.  There are at least two reasons we don’t do this:

  1. You cannot save your work -- Once you close the browser tab or refresh the web page all that code will go away. It is only stored in memory and not to disk.
  2. You can’t easily share it so other users can run the code too.  Since it isn’t saved to a file and the program only exists in memory you don’t have a way to have other users run your code.

 

This is why we normally write our code using a text editor and save it to a file.

 

Which Text Editor Should You Use?

You should use the text editor that is easiest for you to use and the one you are most comfortable with.  Here are some suggestions of text editors that you may decide to use and reasons why you may choose each one.

I’m only going to talk about editors which are 100% free so you will find some popular editors missing, but with the number of free professional text editors available I just can’t think of actually spending money on a text editor.  Later, after you’ve done a lot of JavaScript programming you may find you want one of those editors. But, for now, we will only look at the free ones.

 

Notepad++

Pros: Easy to get, free and easy to use.  You can get it at: https://notepad-plus-plus.org/

Notepad++ also isn’t resource intensive meaning that it won’t eat up a lot of your memory or processor to run it.  Other editors may be more intensive since they may add more capabilities that use more of your computer’s resources.

Notepad++ also has syntax coloring and the ability to list all the functions found in your JavaScript.

Syntax coloring means that Notepad++ will colorize the text that it knows are special things like variables, function names, etc.  It is a simple and nice way to help you see your code more easily.

 

Cons: You can’t debug* your JavaScript.  

 

*We will talk about debugging JavaScript in depth later.  For now, just know that debugging has been a challenge with JavaScript for a long time but Visual Studio can allow you to step into JavaScript and run it line by line. The browser development tools (console, etc) also allow this in some instances.

 

Atom

Pros

  • Easy to get and free.  https://atom.io/
  • Can be used on the Big Three platforms (Mac, Win, Linux).  If you switch between OSes you may want to use Atom.
  • Fantastic syntax coloring.  Editor themes which can make the screen much easier on your eyes.
  • Multiple panes for multiple files: you can open up multiple files and view them all at once.  This is very helpful since there are times when you will need to edit HTML and more than one JS file at at time.
  • Built-in treeview of your project so you can see your project folders and files listed as if you are looking at them in file explorer.
  • You can easily display and work on numerous files at one time using Atom.  You’ll see that is a fairly big deal later when you see how JavaScript and HTML should (must) be broken up into its own source files.

Cons:

Atom is built in HTML, CSS and JavaScript and runs on top of Node.js (JavaScript engine that allows JavaScript to run outside of a browser).

That means Atom is more resource intensive and you may feel your computer slowing down a bit.

A bit more to learn just to start typing JavaScript. The interface is more extensive since it provides more functionality and that makes it a bit more overwhelming to start using.

Visual Studio Code

This is a new smaller editor based upon Microsoft Visual Studio.  I tried it out a bit and even though it is free I don’t like it very much.  If you’re going to go with a bigger editor I suggest you use Atom. Visual Studio Code doesn’t really provide much benefit above Atom and it does some annoying things like adding a \.vscode folder to your HTML / JavaScript projects.

Which Editor Will I Be Using In This Book?

I will often just use Notepad++ because it is fast and easy to start editing a JS file.  However, if I am building a project that is any larger than a simple one-file JavaScript you will see me move to the Atom editor.  

 

Now that you have your text editor and you’re ready to go, we are ready to write our first basic JavaScript along with HTML.  We’ll start that work in the next chapter.

JavaScript, jQuery, TypeScript : Introduction

Background

I write for a number of reasons:

  1. Solidify the things I am learning.
  2. Force myself to look at things more closely / question the knowledge I am gaining.
  3. Create a historical record of what I am learning.
  4. Share information I've gathered with others in an attempt to create community through learning tech.

I recently had a need to learn TypeScript and it pushed me backwards toward learning/remembering JavaScript so I thought it might be nice to pull the three technologies of JavaScript, jQuery and TypeScript together into one place.

If this sounds interesting to you I hope you'll continue reading my posts/chapters as I attempt to create an Engineer's Notebook of sorts.

JavaScript, JQuery, TypeScript

This book is a quick introduction to pure JavaScript, jQuery and TypeScript.

It will be a type of “engineer’s notebook” focusing on the three languages from the standpoint of the practicing developer who needs to learn the foundational parts of the languages that she will use most often.  This book will not cover every topic in complete detail. Instead it will serve as a place to start for many topics while other more interesting topics (author’s opinion) will be covered more thoroughly.

There are a few good reasons to learn all three of these languages. And yes, many of those reasons are simply related to the fact that you can’t really escape JavaScript.  But I’m not just a JavaScript Fanboy. I don’t think JavaScript should be used everywhere. But, I don’t believe it shouldn’t be used anywhere either. I like to use it as I might use a hammer.  The perfect tool to hammer some nails into board. But a hammer is not the right tool for those times when I have nuts and bolts which will be used to connect two pieces of metal. Hammers do not work everywhere.  Neither does JavaScript.

I think you should learn all three of these languages because:

  1. they are all related and
  2. they are surging in use and popularity.  
  3. They are used as inherent parts of many JavaScript frameworks.

For example, TypeScript and jQuery are used in AngularJS.  jQuery is used in Bootstrap and too many other places to count.

You should learn pure JavaScript because understanding it will help you:

  1. Understand what is really going on inside jQuery and TypeScript :
    1. jQuery is written in pure JavaScript.  jQuery solves a number of challenges more elegantly than code you will encounter in pure JavaScript so understanding pure JavaScript will help you understand what jQuery is really doing.
    2. TypeScript compiles (transpiles) to pure JavaScript and again solves some problems for you that are more easily understood when you understand the challenges that pure JavaScript creates.

You should learn jQuery because it simplifies a lot of the work you will do in pure JavaScript. The jQuery API is far easier to use than the JavaScript library when manipulating the DOM (Document Object Model of HTML). The jQuery API “just works” in every major browser so you won’t have the worries that you’ll do something that works in only one or two browsers.  This is not always true for pure JavaScript because various browser versions do implement JavaScript in some subtle and different ways.

For example, Microsoft Edge uses the Chakra (JScript engine) to run JavaScript.  JScript is Microsoft’s name for the script language the rest of us refer to as JavaScript.  Both JavaScript and JScript are actually versions of ECMAScript.

While Google Chrome uses the V8 (JavaScript engine) to run JavaScript.

You should learn TypeScript because it makes creating classes in JavaScript a lot easier.  Your code will be cleaner and more organized. Plus, TypeScript is beginning to take over. It may well be that in five years developers look at pure JavaScript developers the same way we now look at Assembly language developers.  How do we look at Assembly language developers? Very critically. :)

What Will This Book Cover

  • Browsers (Google Chrome, Microsoft Edge, Mozilla FireFox, OSF Opera, Apple Safari)  That’s right, I didn’t even mention Internet Explorer.
  • Text Editors (Possible choices - Notepad++ or Atom)  I’m ignoring many possibilities here like
  • JavaScript types
  • JavaScript functions, classes and scope
  • JavaScript DOM manipulation
  • Challenges of pure JavaScript
  • Installing / Referencing jQuery (CDN)
  • jQuery selectors
  • TypeScript Compiler (Installation and Running)

 

What You Need

A computer running one (or more) of the following browsers:

  • Mozilla FireFox
  • Google Chrome
  • Microsoft Edge
  • Apple Safari
  • Opera Software Opera
  • Text Editor

I’ve examined a couple of text editors and I’ll talk a bit more about this in the next chapter.  I also tried the Visual Studio Code editor and wasn’t really impressed. I’d rather just use the Atom editor because it is a bit more intuitive to use.   Much of my work will be done in Notepad++.

 

If you already have a favorite text editor you can use it with no problem.

Debugging JavaScript

One of the major problems/challenges with JavaScript is that there isn’t a great IDE (Integrated Development Environment (Editor which includes tools to do all your work, including debugging).  

 

Since the browser is the run-time environment for JavaScript code (notwithstanding Node.js)  it is also the place to debug JavaScript. Browsers offer much better debugging functionality than they did in the past, but they’re still not nearly as nice as debugging C# code in Visual Studio.  Much of our debugging will be done via writing logs to the browser’s console (much more later).

 

What Do You Need To Know To Use This Book?

You don’t have to have previous programming experience to use this book, but it will help.  

A basic understanding of HTML will help but it isn’t completely necessary either since I will explain some of it as it relates to JavaScript. I will move quickly over much of the HTML details but I am sure you can learn what you need as you go.  Resources like w3schools.com will be really helpful.

There are some some basic things that you should know though. You should know how to use web browser, download software and install it.  You must know how to move around in the file system using file explorer. You’ll need to know how to do those things because I won’t explain those as we go and if you don’t know how to move around in the file system it is going to be difficult for you to find the JavaScript files we create and edit.

What Will This Book Do For You?

It will provide a foundation of JavaScript, jQuery and TypeScript fundamentals so you can go further with JavaScript technologies.  For example, after you complete this book, you will find it far easier to learn Node.js.

That’s all you need so let’s jump in and start learning some pure JavaScript.