"

15 Getting Started in JavaScript

Decoration Connections

JavaScript’s core syntax is very similar to C, Java, C#, and many other languages. But don’t be fooled by surface appearances. Some deep differences lurk beneath.

Because JavaScript is based on C syntax and was modeled loosely on Java, you might already know most of its syntax. Statements, comments, operators, comparisons, if, for, and while statements all work pretty much exactly how you would expect them to.

If you learned Python or another language with a different syntax, don’t be alarmed – the concepts are very similar, it’s only the syntactic details you have to learn. On the other hand, you will have no issues with JavaScript’s support for purely imperative programming and its dynamically-typed approach to variables.

Either way, this is great news. No matter what language you learned first, you already know many of the basic concepts and maybe even the syntax and you haven’t even done anything yet!

image Do it Yourself

If you have some programming experience, but not with a C-like language, or if you need to brush up on your syntax, w3schools is a great place to go for a refresher (you might want to make sure you have a decent ad blocker first). Just click on the JavaScript link and then choose the topics from the list on the left. The sections on comments, logical operators (&&, ||, !), if-else, while loop, and for loop might be particularly helpful.

Even if you know C or Java syntax well, you should still take a look at the sections on the String and Math methods (including Math.random)to familiarize yourself with these basic libraries.

Imperative Programming

Decoration Connections

Statements. In Java, every statement must be part of a class or method. In C, most statements must be part of a function. This is not true in purely imperative languages like Python or JavaScript.

JavaScript allows you to add code to a web page in purely imperative style. Imperative programs consist of a list of statements in the order they are to be executed. These statements do not need to be part of a class, object, method, function or any other structure.

In human languages, imperative sentences are commands: “Do this. Now do that.” Imperative programs read just like that to the computer. There are no pleasantries required such as class, method, or function definitions. You can just get straight to the instructions.

The Browser Console

The easiest way to execute JavaScript statements is using the JavaScript console of your favorite browser. In Chrome, hit ctrl-shift-i or F12 to open the developer tools, then choose “Console” from the tabs that appear at the right of the page.

The console will appear as a new panel to the right of the web page, like this.

(What’s that you say? Chrome isn’t your favorite browser? Well you have two options. You can either make Chrome your new favorite, or you can search through the menus on any another browser for “Developer Tools”, “JavaScript Console” or something similar.)

image Do it Yourself

If you’re reading this on a desktop or laptop browser, open the JavaScript console now (F12 or ctrl-shift-i in Chrome). If you’re on a mobile device, go to a laptop or desktop and open any web page in Chrome or another browser, then go to the developer console.

Now you’re ready to execute your first JavaScript statement. At the flashing cursor beside the ‘>’, type:

window.alert("Hello, World!");

…and hit enter. See the popup message?

Decoration Connections

Semicolons. In JavaScript, you usually don’t need a semicolon at the end of a statement, but sometimes you do. Instead of trying to remember which case is which, it’s better to always include one.

What you have just done in the DIY box above is execute a JavaScript function named alert that is part of the built-in window object. JavaScript functions are a lot like Java methods or Python functions – you call them by typing their name followed by a list of arguments inside rounded brackets. If a function belongs to an object (technically making it a method), you type the name of the object first followed by the . (dot) operator.

No matter what browser you are using, you will always have access to a window object containing variables and functions pertaining to the currently active panel of the browser. And because you are always “inside” the window object when executing JavaScript, you don’t actually need to type the “window.”  part. So this would have worked, too:

alert("Hello, World!");

Decoration Connections

String Literals. In Java and C, double quotes are for Strings and single quotes are for chars. JavaScript, like Python, doesn’t have a char type, so you can use either type of quote character for a string. This means you don’t have to use escape characters to put quotes inside a string (e.g. instead of "\"Murder,\" she wrote", you can use single quotes like this: '"Murder," she wrote').

image Do it Yourself

Here are a couple more window functions to try in a Chrome console window.

prompt('What is your name? ');
confirm("You're programming in JavaScript!");

Note the return values of each function that appear in the console window when you try these statements. Just like in most other languages, you can use the return value of one function to assign to a variable, as part of an expression, or as an argument to another function.

Try to predict what the following statements will do. Then try them out in the console to see if you were correct (use shift-enter to enter a multi-line block of code in the console).

alert(prompt('What do you want to say? '));

if (confirm('OK?')) 
    alert("You're OK"); 
else 
    alert("You're not OK?");

confirm("Is your name " + prompt("What is your name?") + "?");

The prompt, alert, and confirm functions are pretty straightforward and are discussed under the heading JS PopupAlert on w3Schools.

The Chrome console is a great tool for testing out JavaScript statements and expressions to get the syntax right before incorporating them into a web page. It can also help you remember method names by popping up suggestions as you type…

image Do it Yourself

Type “Math.r” in the Chrome console window and look at the suggestions that pop up

The console can also evaluate JavaScript expressions for you.

image Do it Yourself

Try the following in a Chrome console window. (Make sure you get the upper and lower case right in these examples or they won’t work.)

5 + 3 * 2
5 <= 3 
Math.round(Math.PI*2) 
Math.round(Math.PI*2) < Math.PI*Math.PI
Math.floor(Math.random()*10+1)

Before we move on, a few more useful console tips:

  1. To repeat a command in the Chrome console, hit the up arrow to cycle through recent commands, tweak them, and try again
  2. To enter a multiple line command, use shift-enter.
  3. To complete a command using a pop-up suggestion, navigate to it using up and down arrows, then complete the command using the right arrow
  4. To clear the console screen, use ctrl-L (or you can use the console.clear() function)
  5. To detach the console and use it in a separate window, press the three dots icon on the top right (beside the X icon). If you change your mind, press the same button again to reattach it.

The HTML script Element

Of course the real point of JavaScript is to embed a program into a web page. You can put JavaScript statements anywhere you want in an HTML document, as long as they are inside a script element, as in the example below:

<script>
  alert("Hello, world!"); 
</script>

To help maintain a strict separation of concerns, you can also write your script in a separate file (usually with a .js extension) and include it using the src attribute of the script element, like this:

<script src="js/hello.js"></script>

Note that you still need the closing </script> tag. Many developers will put their JavaScript files in a separate js folder (and their CSS files in a css folder, their images in an images folder, etc.)

You can put any number of script elements anywhere inside the body or head elements of an HTML document. The browser will read the page from top to bottom as it loads it. When it gets to a script element, it will execute the commands inside before moving on. But because most browsers will not display the page until they have finished parsing it, all the scripts on the page will execute before any part of the page is displayed.

image Do it Yourself

Use Visual Studio Code or your favorite code editor to add some script elements to template-mobile.html from the Full Stack Example Pack. Make at least one .js file and load that from a script element as well.

Your script elements and .js files can contain alert, confirm, or prompt statements. Try adding a few in different places, then loading or reloading the page to run them.

Once we get past this opening chapter, we won’t use alerts and other popup boxes very much to talk to the user. They’re rather inelegant and obtrusive. But you might still want to have a way to create debugging output to let you know what is going on inside your JavaScript programs. For this, you can use the console.log function. It’s a bit like the print, println, or puts statements you might know from other languages. It sends output to the browser’s console where nobody but us developers will see it.

image Do it Yourself

Go back to the last DIY box and change the alert function calls to console.log. Refresh the page to see the messages end up in the browser’s Console window.