Core Programming Syntax

Why JavaScript?

JavaScript is used throughout these tutorials because it is friendly for beginners and it does not require special software. It's not the most the most powerful, or the most flexible language out there, but it's certainly popular and it's certainly relevant - it's a great language for exploring these concepts. Last, but not least, JavaScript is a very practical language to know.

JavaScript is a language that works with, and manipulates, web pages - it was invented for that reason. That means that it is specialized and intentionally limited. JavaScript is not used to write desktop applications like C++, Java, C# or Objective-C. Programs that you write in these languages would run directly on the operating system, whereas JavaScript wouldn't, it runs in the browser, which runs on the operating system. Despite the name, Java and JavaScript are totally different languages and are not related in any meaningful way.

While JavaScript is a programming language, you often hear it referred to as a scripting language. This is a description you hear for any language with "script" at the end, such as ActionScript, AppleScript or VB Script. Scripting languages are more limited programming languages that are embedded inside another program. For example, ActionScript is the programming language that we use inside Flash and VB Script can be used inside Microsoft Office applications. Similarly, JavaScript also only works inside another application - the web browser. All web browsers have a JavaScript engine, a JavaScript interpreter inside of them. Scripting languages in general are more limited than the general purpose programming languages, but they are often easier to learn and they are very good at what they do.

JavaScript, like most scripting languages, is an interpreted language - we do not have to manually compile it to machine code. The web browser compiles it when it tries to run the JavaScript.

JavaScript is also a case sensitive language. For example:

document.getElementById("example").style.display - "none";

document.getElementByID("example").style.display - "none";

One of these is right and one of these is wrong because one is using a lowercase 'd' and the other is using an uppercase 'D'. This is the level of case sensitivity we have to be aware of in any language that is case sensitive and most of them are. Even if you have a language that isn't, you will probably want to make it a habit of paying close attention to it.

Here is some more JavaScript:

// show and hide sections of a form
function preparePage() {
    document.getElementById("brochures").onclick = function() {
        if (document.getElementById("brochures").checked) {
            // use CSS style to show it
            document.getElementById("first").style.display = "block";
        } else {
            // hide the div
            document.getElementById("first").style.display = "none";
        }
    };
    // now hide it on the initial page load.
    document.getElementById("first").style.display = "none";
}

window.onload = function() {
    preparePage();
};

When you see any programming language with a lot of curly braces being used ({}) and when you see statements that all seem to end in a semi-colon (;) (and a few other notable things), this is a clue that this language is influenced by the C programming language. C has been around since the early 70's and shapes the look of many of the most popular languages today. Some even share the name - C++, C# and Objective-C, and some don't - Java, ActionScript and JavaScript. Knowing the C style language makes it easier to jump into any of these other languages.

JavaScript is a C based, interpreted, case sensitive language. It's highly relevant and it's very friendly for beginners.

Creating your first program in JavaScript

You can't just write some JavaScript and have it magically run by itself - you need to create the program and have it run inside of another program. It's not unusual to have multiple levels of this in programming.

As an example:

  1. You have a computer.
  2. That computer is going to be running an operating system inside of it.
  3. Within the operating system, you are going to be opening up and running a web browser.
  4. The web browser itself is going to be opened up and run a web page.
  5. That web page itself is going to open up and interpret some JavaScript.

You already have the computer, the operating system and the web browser. What you need to do now is to create the last two pieces - the web page that will open up in the web browser and the web page will be the container that is going to take care of interpreting and running the JavaScript that is going to be written. There is no need to worry about a web site, a web server or any of the other files associated with a website - all that is needed is a single, simple web page, an HTML file, who's only purpose is so that you can open it and have it point to the JavaScript and say, "Go and do this."

folder options window

For Windows users, ensure that you don't have the "Hide extensions for known file types" selected in Folder Options/View. Folder Options can be accessed via the Control Panel.

Creating a Simple HTML Page

html code for simple html page

01. Open Notepad and enter the following into it:

<html>
    <head>
        <title>Simple Page</title>
    </head>
    <body>
        <p>This is a very sinple HTML page</p>
        <script src="/script.js"></script>
    </body>
<html>

Note: HTML is not a programming language, but rather, it is a markup language. HTML stands for HyperText Markup Language and a markup language is a set of markup tags used to describe web pages.

The code snippet - <script src="/script.js"></script> - is the important piece. It is how we point from the HTML file to the JavaScript file called "script.js".

saving the file as...

02. Cick File and select "Save As..."

saving the file as a html file

03. Name the file container with the file extension of .html and save it inside an empty folder that is easily accessible to you - your desktop will suffice. We use the .html extension so that when we open it, it will open up in the default web browser.

Note: The file must be saved in plain text format and not rich text format.

the saved html file in a folder in windows explorer

04. Navigate to the folder that you saved the "container.html" file in, open it and double left click the "container.html" file.

opening the html file with firefox

You should see the above, or something similar to it. Close the web browser.

Creating the JavaScript file

the javascript code for hello world

01. Open Notepad and enter the following classic, one statement, into it:

alert("Hello world");

saving the file as...

02. Cick File and select "Save As..."

saving the file as a javascript

03. Name the file script with the file extension of .js and save it in the same folder that you saved the "container.html" file in. Because we are using just the name (script.js) in the code snippet - <script src="/script.js"></script> (from "Creating a Simple HTML Page" above) - the file needs to be placed in the same folder as the HTML file.

Note: The file must be saved in plain text format and not rich text format.

the html and javascript file in a folder in windows explorer

04. Navigate to the folder that you saved the "script.js" file and the "container.html" file in, open it and double left click the "container.html" file.

opening the html file with firefox

You should see the above, or something similar to it. The web browser loaded the web page. The web page HTML file points to the JavaScript file and it loads it in, interprets it and it runs it. Clicking the "OK" button will close the Alert Box and then close the web browser.

selecting to open a file with notepad

To view the code from either of the "script.js" or the "container.html" files, right click either one and in the menu that pops up, select to open it with Notepad. Again, for any program other than Notepad, the files must be opened in plain text mode. Once you are finished viewing the code, close Notepad.

Note: If Notepad is not in the program option list, click "Choose Program..." and then select Notepad from the additional list of programs.

Requesting input

Computer programs are all about input and output. The input might be click the button, move the mouse, or wave your hand in the air and the output could be change what is displayed on the screen or cause the game controller to vibrate. The different languages favour different kinds of input and output.

JavaScript is all about the web page - it doesn't read files on your hard drive and it doesn't talk directly to your printer. It's interested primarily in what's on the web page and what you might interact with on the web page. The alert box above might not be impressive output, but it is output. It's our computer program causing something to happen on the screen.

Requesting Input with JavaScript

01. Navigate to the folder that you saved the "script.js" file and the "container.html" file in, right click the script.js and select to open it with Notepad.

02. Delete the line of code - alert("Hello world"); - and enter the following 2 lines of code:

var name = prompt("What is your name?");
alert("Hello, " + name);

03. Click File in the Menu and select "Save" and then close Notepad.

the javascript prompt - what is your name

04. Double left click the "container.html" file and you should see the above or something similar to it.

entering data into the javascript prompt

05. Enter your name and then click the "OK" button.

the execution of the second line of javascript code

06. You should see the above image or something similar to it. Click the "OK" button to close the Alert Box and then close the browser.

Note: Because I used Firefox and multiple Alert Boxes were opened during the session, I'm being asked if I want to prevent anymore from opening. Selecting this option at this time is not necessary.

Two JavaScript Statements

01. var name = prompt("What is your name?");

The first statement is using the JavaScript prompt command to ask for a name and then stores that name in a variable (var), a container that can hold some data, and that's so it can be used on the next line. If you don't tell your program some way of remembering it, you won't have any way to use it on the next line.

Usually the code will just start at line one and then move through all the different statements as quickly as possible, but what's actually happening here is when you call 'prompt' in JavaScript, it's not just "What is your name?", it's "What is your name?" and then wait for a response. It actually pauses at this line, waits until somebody types in an answer, and when the "OK" button is clicked, does it actually come back. The value typed in will be stored in a variable called name (var name). Whether that was five seconds later or five minutes later, it's been paused at that point and then runs the next line of code only when the "OK" button is clicked.

02. alert("Hello, " + name);

This statement is going to combine the "hello, " with whatever was typed in (("Hello, " + name);) using the plus sign (+) to combine the two parts of the message and then pop up another dialogue box.

If you want to run the code again, you could close the browser and then reopen it or you could click the "Reload" button in the browser.

With the above example, there is nothing to ensure somebody actually types a name here. You could type in a number and click "OK" and it would just combine that message. You can even leave the input field blank and click the "OK" button. Here it doesn't matter, but if the program, if the code, was expecting something very specific to work with, like a birth date, or an amount, or an email address, the wrong kind of input could cause it to crash because, again, programs are all about input and output. There is an old phrase called GIGO - for "Garbage In, Garbage Out." Whatever you are asking for and whatever you get better make sense.

JooComments powered by Bullraider.com