JavaScript 102: Variables, Statements, and Comments (Final Lesson)

Going a little deeper

PROGRAMMING FOR NON-GEEKS - JavaScript 102: Variables, Statements, & Comments
Photo by Science in HD on Unsplash

YOU can learn to program! You don't have to be a geek. You don't have to be good at math. Just dive in and start practicing. It is complicated, but not hard.

We are working our way through JavaScript and Jquery, by Jon Duckett (no affiliation.

For today's lesson, please read pages 43 through 65.

With any new language, you have to learn new words and what those words mean. Computer languages are no different. When you learned HTML and CSS, you had to learn new “words” and what those words meant. For example, HTML uses tags, and CSS uses classes. For someone who knows HTML and CSS, those two words have different meaning. If you did not know HTML and CSS, the typical English meaning persists.

Today’s lesson builds on the words and concepts in JavaScript. Since this is the most basic programming language, many of the concepts learned here will carry on to other languages.

Pay attention.

Image of skeleton
Photo by Mathew Schwartz on Unsplash

Anatomy of a statement

The most basic building block in a script is a statement. This is all on one line and ends with a semicolon. If you see a really long line that wraps around, it is still one line of code. Your code viewer might be displaying it over multiple lines, but it is still one line of text. One really long line of text. The computer will keep reading until it hits a semicolon (;). Forgetting a semicolon is a “bug.” It is also one of the first things to check when your script does not work.

A statement tells the computer to do one thing. Sometimes that thing is a shortcut which tells the computer to perform several other actions. Even in that case, you are telling the computer to run one shortcut. And that command ends in a semicolon;

Here’s an example statement:

document.write('Good afternoon!');

The word “document” in this statement is an object. A web page is a giant collection of objects. The entire page is known as the Document Object Model (DOM). You will encounter that a lot. If so, it means “all the things” that make up a web page.

Between “document” and “write” is a period (.). That period is known as a member operator. You could read this as “within,” like “look within this object for the next thing I’m about to say.”

That “next thing” could be a method, a property, or a variable. In the above example, “write” is a method. You can see because it is followed by parenthesis(). If there is something inside of those parenthesis, it is a little bit of information the action will need to do the job correctly (parameter). The write() method doesn’t need a parameter to work, but it will send nothing to the browser. It’s a lot cooler when you define a parameter for this method.

Of course, every statement ends with a semicolon (;). I know I have said it before, but it really is important, and it really is easy to miss. When I took CS101 in college, I spent hours trying to figure out why a program refused to work. I had missed one semicolon on one line.

Bugger.

Sidewalk sign saying, "The Future is Unwritten"
Photo by Max Böhme on Unsplash

Let there be comments (PLEASE)!

You should remember comments from HTML (<!– comment –>). I never used them much. It seemed pretty clear what was going on by just looking at my code.

Comments are much more important when it comes to programming. What’s going on is not as obvious. You need to make it obvious (to yourself and others). HTML was a “markup language.” It adds style to something that already exists. It is pretty easy to imagine text without style. With a “programming language” we are creating something from nothing. It’s not always obvious what is going on. Comments will make things a little easier to understand.

Comment lines are proceeded with a double-slash (//). Javascript will ignore everything after the //. If your comment spans multiple lines, start it with /* and end it with */. There is one key difference to the comments you leave in programming code. When you use “view source” on an HTML file, your script will be hidden from view. That means that the only people who will see your comments are other programmers.

Some programmers even leave little jokes in their comments. These hidden gems are only found by other programmers.

Here is an example of what a comment would look like in code:

// This comment is on a single line
/* This comment
is on
multiple lines */

It is highly recommended that you use comments in your code. This will assist others in understanding and debugging. It will also assist you to decipher code at a later date.

Pink, magnetic letters
Photo by Jason Leung on Unsplash

What is a variable?

A variable is like the Memory buttons on your calculator (M). “Here is a value that I would like to use in a future calculation.”

A variable can hold a number, text, or object You can think of a variable as “short-term memory” for your computer. The web browser will forget the information after the user has finished his/her session. If the value is important to keep, it should be stored in a cookie or a database. We’ll cover that in the future.

A variable can change. It varies. You may start with one value and end with a very different value. This is called the scope of a variable.

Let’s tear apart a piece of code:

var nameOfVariable;

“var” is a keyword. It tells the computer to create a variable named whatever is to the right of it. In this example, the variable will be named “nameOfVariable.” Notice that our statement ends with a semicolon.

A variable name can be anything. Remember that case is important. NAME and name are two different things. Many words in JavaScript are written in “camelCase” That means that multiple words are shown without spaces. The first word is lower case. Every other word is displayed with a capital first letter. Example:

camelCase

The first step in setting up a variable is to declare the name of a variable. We did that, above. Secondly, we assign a value to a variable. We do that with an equal sign:

variableName = 3;

The equal sign is called an assignment operator. There are many different assignment operators, but you will probably just be using the equal sign for a bit. The equal sign tells Javascript to take the “thing” on the right and assign it to the “thing” on the left. Using the above example, you can read it as “assign a value of ‘3’ to ‘variableName.’

Note: Help a brother out. That “brother” might be you. To keep some sanity in your script, try to make your variables logical. Don’t set houseColor to “3.” Don’t set clientAge to “purple.” JavaScript will let you do it, but don’t. That will just cause insanity.

The assignment variable may be used to create an initial value for a variable, or it may be used to assign a new value to a variable. It may be used over and over again to change the value of a variable. If a variable has been created, but no value is set up yet, that variable is known as “undefined.”

Fingers typing on laptop
Photo by Glenn Carstens-Peters on Unsplash

Variable Types

There are four types of variables. A variable type may change throughout your script. This is true of JavaScript, but is not true of every programming language. It is best to stick with one type for each variable.

1 Numeric. This is a plain ol’ number. It could be 3, -12, or 97.6. Some languages distinguish between small numbers (0-9) and large numbers (10-infinity). JavaScript does not. Go crazy.

2 String. This is some text. It may be in any language (including special characters and emojis). It is surrounded by single or double quotes (” or ‘). If your letters should contain either a single or double quote, use the other to enclose your text. Example:

randomString = "Howdy, partner! How's your day going?";

or

randomString = 'I like to use the word "Howdy" when I greet people.'

If you want a string to contain both types of quotes (‘ and “), you will need to use an escape character. If you proceed a character with a backslash (\), JavaScript will read the next character as literal. Example:

randomString = "Howdy, partner! How's your day going? Notice my use of \"Howdy\" in a sentence?"

Escape characters may also be used to insert type that is normally invisible (like a newline character). If you ever have need of an invisible characters or special characters, I have included a handy reference of each.

As a final note, you cannot use “smart quotes” (aka curly quotes). Stick with vanilla quotes (” and ‘). Just don’t use a word-processor (like Microsoft Word). Use a plain-text editor and you’ll be golden.

3 Bolean. These variables act as a switch (like a light switch). They are either “true” or “false.” This is handy in different parts of your script. JavaScript does some handy hacks with bolean variables. When something is “true,” it has the synonym of “1.” That way, a programmer can test if a variable is equal to 1. If so, something will happen. If not, something else will happen.

4 Object. This is not so much a type of variable. It’s more of a “pointer.” Imagine it like a cheerleader. “When I say variable, you say object!”

"Variable!"
"Object!"
"Variable!"
"Object!"

If a variable is assigned an object, the variable name may be used in the place of the object name. This has many different uses. Example:

var el = document.GetElementById('cost');
el.textContent = randomText;

Either you immediately see the handy use, or it will become clear later.

Photo of HTML book and JavaScript book on a shelf, being held up by a cactus
Photo by Greg Rakozy on Unsplash

How should I display my scripts in HTML?

When a web browser is laying down a page, it starts to stack HTML elements like bricks. When it encounters a <script>, it stops what it is doing and executes that script. The reason is that the <script> might tell the browser to do something it wouldn’t otherwise do.

You can load a script in the middle of your page. The below example will work just fine:

<p id='doggy'><script>document.write('Ooobie Doobie Doo!')</script></p>

When the browser hits this code, it pauses for a microsecond to execute your commands. The user might experienced a slight delay in a web page popping up. The more complicated the script, the longer the delay. Most users are very impatient waiting for pages to load.

To bypass that delay, programmers have devised a different method (literally). Look again at the previous example:

var randomText;
randomText = "Ooobie Doobie Doo!";
var el = document.GetElementById('doggy');
el.textContent = randomText;

Here, we use the method “GetElementById()” to find something in a page. In this case, it is an element with the id=’doggy.’ Then we replace the contents of that element with the contents of the variable “randomText.”

This will allow us to run the script at the very bottom of our code. That way, the page is displayed first without delay and then the script runs last, replacing one of the elements.

This is the preferred way to put your JavaScripts in an HTML page.

This doesn’t work in IE8, but I don’t much care. People shouldn’t be using IE8. If you really care, you can detect that the user has IE8 and should expect the page to not work correctly. That method will be covered in later chapters.

I’m tired of the hacks required to make things work in IE8. I would rather pretend that IE8 doesn’t exist. I’m not listening! Lalalalala…

Programmers don’t all agree on this way. Some insist that “<script>” tags should be in the “<head>” of the document with the “async” or “defer” attributes. Let the hackers supreme fight this one out and be ready for this whole method to change in about five years (2025 or so). Of course, the whole world could be different by 2025.

Atlas shrugs.

Now, you can structure your HTML code a bit differently:

<p id='doggy'>This text will be replaced if you are not using IE8</p>

Lastly, we use another trick to keep your code clean. The script, above, can be saved as a separate text file with the .js extension. When you want to use it in your HTML code, it will use the “src” attribute, just like the <img> tag. Example:

<script src="/pathToJSCode/sampleCode.js"></script>

Place this at the very bottom of your HTML, before the final “</body>” tag.

Sign saying, "Goodbye, Friends"
Photo by Jan Tinneberg on Unsplash

Until next we meet…

Thanks for learning some language basics with me. These are the most basic building blocks for JavaScript as well as other languages we will learn in the future.

If you have any questions, leave them below in the comments. I love questions! Questions help in our learning! You never know if something is confusing for other people. If I see more than one person struggling with a point, I must not be explaining it very well!


Note: This will be the final lesson in the Learning to Program Series. I’m not angry or bitter or anything. I’m just giving the readers what they want. I can spend an hour learning and then two hours writing, or I can spend 3 hours learning to program. It’s a matter of pros and cons. I can abandon the writing and concentrate exclusively on learning. That’s the decision I have made.

I still write every weekday, and that will not stop. I am just not going to write about programming any more.

Was this useful to anybody? If so, I might reconsider my decision. My suspicion is that nobody is listening. If that’s the case, I can get a lot more done without the writing bit.

Matt believes that anyone can learn to program.

☝ ️Start from the beginning

👉 Sign up for the MWMcCabe newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.