Intro to JavaScript

January 30, 2021

This tutorial is designed to provide a basic introduction to coding in JavaScript which can be applied to web design and web app projects. This tutorial includes explanations of some of the key principles involved as well as some simple working code examples that you can follow along with.

What You Will Need

  1. This tutorial is designed for complete beginners so you do not need any prior experience with coding in JavaScript. However, the JavaScript code will be included in basic HTML code so it is preferable (but not necessary) that you have some experience with HTML coding. You may want to check out my tutorial that shows you how to code a basic webpage using HTML first.
  2. You will need a basic code editor, such as Atom, Brackets or Visual Studio Code.
  3. For this tutorial I will also be using the Google Chrome browser however you should be able to follow along using other browsers such as Firefox or Safari if you prefer.

Table of Contents

  1. What is JavaScript?
  2. What is JavaScript Used For?
  3. How Does JavaScript Work?
  4. How to Incorporate JavaScript in a Webpage
  5. How to Use and Apply Comments in JavaScript
  6. What is a Variable?
  7. Types of Variables
  8. Assigning Values to a Variable
  9. Casing in JavaScript
  10. Working with the Console
  11. How to Use Variables and JavaScript to Dynamically Update HTML Content
  12. The Document Object Model (DOM)
  13. Recap
  14. References
  15. Next Steps

What is JavaScript?

Javascript is a scripting / programming language. There is plenty of information about Javascript on the web so I won’t go into it in too much detail here. If you’re interested in knowing more about Javascript, including the history and capabilities of Javascript I would recommend this article, titled ‘Javascript World Domination‘.

What is JavaScript Used For

JavaScript is most commonly used to update website content dynamically. I will explain how this works later. Whereas HTML could be described as the language of content and structure, and CSS could be described as the language of visual styling, JavaScript could be described as the language for handling interactions and ‘doing things’.

How Does JavaScript Work?

JavaScript code is run by the browser on your device and is therefore considered a ‘client side’ scripting language. With JavaScript typically the browser executes the code to dynamically change the webpage content on your device only. Alternatively with coding languages like PHP for example, the code is run by the website server, so PHP is referred to as a ‘server side’ scripting language. Typically PHP is used to preassemble webpage content on the website server to then make available for the browser to access in a static form.

How to Incorporate JavaScript in a Webpage

In an HTML webpage document (.html) JavaScript is commonly incorporated either ‘inline’ or linked to as an external document. In the case of ‘inline’ the JavaScript code is included within the HTML code in the between the opening and closing script tags, or as an external document, in which case the the JavaScript is created in it’s own .js (JavaScript) file and linked to from the HTML document.

When JavaScript is included inline it is commonly included either between the head tags or immediately before the closing body tag:


<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script>
        // JavaScript here
    </script>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>
    <script>
        // JavaScript here
    </script>
</body>
</html>

Similarly when JavaScript is linked to as an external document it is commonly linked to from between the head tags or immediately before the close body tag:


<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script src="javascript-file-1.js"></script>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>
    <script src="javascript-file-2.js"></script>
</body>
</html>

I find that when getting started and for simple one page web applications it seems to make the most sense to include the JavaScript inline. That way everything is contained within the one file. If by chance you want to create your JavaScript as a separate file the JavaScript file won’t need to include the opening and closing script tags, and of course the extension will be .js.

So now is a good time to get started.

  1. In you code editor make a new empty document.
  2. Go to the W3Schools HTML webpage and copy and paste the sample HTML code into your document.
  3. Change the contents of the title tag to ‘My First JavaScript’.
  4. Add the opening and closing script tags immediately before the closing body tag and include and empty line to add your javaScript code.
  5. Save the document as ‘my-first-javascript.html’.

Your code should look like this:


<!DOCTYPE html>
<html>
<head>
    <title>My First JavaScript</title>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>
    <script>
        
    </script>
</body>
</html>

Now would be a good time to test running the code in a web browser. Code editors usually include a menu item or shortcut to do this. Alternatively, with a browser open you could select ‘Open File’ (or similar) from the browser’s menu.

In the browser you won’t see much yet, just the title in the browser tab and the sample HTML H1 heading and paragraph.

Whenever you make changes to the code and you want to view the updated webpage in the browser, follow these simple steps:

  1. Save the document
  2. Return to the browser (where hopefully the document is still open)
  3. Refresh the page in the browser

I think that when learning coding it really helps to type out the code manually, however of course you can always copy and paste the code from the examples provided if your prefer. I find that if I copy and paste code rather than typing it out myself I am more likely to get in the habit of needing to copy and paste it in the future. Also, if by chance your page is not loading correctly this is most likely because there is at least one simple spelling error in the code. When coding the code needs to be exact and you will need to learn how to look at your code closely to spot any errors.

From now on whenever I reference javascript it needs to go between the script tags.

How to Use and Apply Comments in JavaScript

Commenting is a way of including text within your JavaScript code that will not be executed by the code. Commenting is commonly used to leave notes within the code that describe what the code is doing. This can be useful for your own reference and or for other developers that may be working with your code. Comments are also often used as a general organisational method to help identify different sections of code.

I often use comments to comment out sections of code that I am having trouble with or trying different variations with. I also use comments when planning an app or website using ‘pseudocode’. This is like writing in plain language first, all the steps and processes that I need that app to do. (You will see demonstrations of this as we move along).

In JavaScript to comment a single line of code you simple put a // in front of the line:


// A single line comment

or for multiple lines you would use a /* … */ (This is the same commenting protocol as for CSS and PHP)


/* 
  A multi-line
  Comment
*/  

What is a Variable?

In simplistic terms, a variable is a something that has a value that may change and in scripting a variable generally has two main properties, a name and the corresponding value, that is the current value of the variable at a given time. In maths variables are often identified with alphabetical symbols such as x, y or z.

Sometimes it is useful to think of a variable as a type of container that holds a value.

For example, you may have three glasses on a table, one contains milk, one contains orange juice, and one contains water. In order to refer to each glass, you may call call them ‘Glass A’, ‘Glass B’, and ‘Glass C’. In this example the value of Glass C = ‘water’. However this could change if something else is put into Glass C.

Types of Variables

In JavaScript there are different types of values that a variable can have. Some of the most common types of variables are numbers, strings, and arrays.

Obviously numbers are used when the variable has a basic numerical value. Something like x = 5, or score = 1, etc.

Strings are used when the value is a ‘string’ of text including spaces, something like username = ‘John Doe’.

Arrays are used to store multiple values in one variable, something like fruitsalad = [“Apple”, “Orange”, “Banana”].

Assigning Values to a Variable

In JavaScript In order to use a variable you must first declare it as a variable. In older versions of JavaScript (prior to 2015) this was done by simple using the term ‘var’, eg:


var glassA = "water";
// or
var score = 12;

Note, that a string value needs to be enclosed in single or double speech / quotation marks, whereas a numerical value does not.

Note, in JavaScript, semicolons are used to separate statements. However, JavaScript also has a feature called automatic semicolon insertion (ASI), which can add semicolons to your code automatically when your code runs. Personally I often don’t include the semicolons when I am scripting on my own projects, however most commonly you will see semicolons included. I have also found that when I have switched to languages like C# (in Unity) I have regretted getting in the habit of not including the semicolons as in C# the code won’t run correctly without them.

You can also declare a variable without giving it a value yet, eg ‘var score’. Sometimes it is useful to declare variables first before giving them values.

In most cases declaring a variable using the var term works fine however in some cases there can be issues relating to where variables are declared in relation to the overall code structure. At some point I will discuss the issue of ‘variable scoping’.

In the 2015, most recent version of JavaScript (also called ES6 / ECMAScript) other methods for declaring variables using ‘let’ and ‘const’ were introduced. These were introduced to allow for a finer control of how the variables operate. I think that when starting out with learning JavaScript it is easiest to simply use ‘var’ and then introduce the other terms later after you understand the fundamentals.

For a thorough outline of variables I would recommend this page on w3Schools.

Casing in JavaScript

Unlike names for elements in HTML and CSS, JavaScript doesn’t support hyphens in variables names. So for variable names made up of multiple words people most often use what is referred to as ‘camel case’, or sometimes people prefer other conventions such as ‘snake case’. Camel case tends to be most common.

In camel case words are joined together and the second word onwards is capitalised. In snake case words are lowercase and separated by an underscore.


// Example of Camelcase
myVariable = 1;
// Example of Snakecase
my_variable = 1;

Working with the Console

Browsers usually contain a ‘console as part of the developer/ inspector tools. The console is a great tool for getting feedback from the browser and for verifying whether your code is working or not. Let’s try it out with this code:


console.log("hello");

Now save your code, go to the browser, and view the inspector tools – console. To do this in Chrome:

  1. Right-click on the page and select ‘Inspect’.
  2. Click on the tab for console.

You should the console logging your text.

Now let’s get the console to log the value of a variable:


var myLuckyNumber = 14;
console.log(myLuckyNumber);

* Note, when you want to log some arbitrary text to the console you include it between speech marks, however if you simply include the name of the variable the console will return the value.

Sometimes it can be useful to get the value as well as a description of what the value refers to, eg:


var myLuckyNumber = 14;
console.log("My Lucky Number is " + myLuckyNumber);

* Note that here I have used the + symbol to return the text combined with the variable called ‘myLuckyNumber’. Notice that I also included a space after the word ‘is’. Try this and test it in the console.

Now let’s add a bit more:


// declare variables (with values)
var myName = "JavaScript Learner";
var myLuckyNumber = 14;
var myMotto = "Seize The Day!";
// log to the console
console.log("My Name is " + myName);
console.log("My Lucky Number is " + myLuckyNumber);
console.log("My Motto is " + myMotto);

So if you’ve made it this far you’ve done well, and this is probably a good point to save your file.

Now, let’s learn how to use variables and JavaScript to dynamically update a website.

How to Use Variables and JavaScript to Dynamically Update Html Content

Start with a new HTML Document, save it as ‘dynamic-javascript.html’ (or similar), and include the following code:


<!DOCTYPE html>
<html>
<head>
<title>Dynamic JavaScript</title>
</head>
<body>
    <h1>Hi, my name is ...</h1>
    <p>My favorite number is ...</p>
    <p>My motto is ...</p>
</body>
</html>

Save it and test it in the browser.

Now, in order for our JavaScript to easily talk to the HTML we are going to define some elements with unique ID tags. (Again, you may want to look at my web / HTML tutorials for more information about how this works.) So what I will do in this example is add some id tags around the ‘…’s as follows:


<!DOCTYPE html>
<html>
<head>
<title>Dynamic JavaScript</title>
</head>
<body>
    <h1>Hi, my name is <span id="name-holder">...</span></h1>
    <p>My favorite number is <span id="lucky-number-holder">...</span></p>
    <p>My motto is <span id="motto-holder">...</span></p>
</body>
</html>

In this case I am using a span tag which works well for defining sections of text within a sentence or similar. I also decided to name the element ID ‘…-holder’ because I think it may help to consider them as the items that will hold data, and also to help differentiate them from the JavaScript variables.

Note that when defining my ID tags I used a hyphen ‘snake case’ format rather than camel case like I have been doing in the previous JavaScript. In HTML you can use underscores however in HTML and CSS it is best practice to avoid capitals. I use hyphen case in my HTML / CSS and either camel case or snake case in my JavaScript.

Now let’s add some of the javaScript that we created earlier:

<!DOCTYPE html>
<html>
<head>
<title>Dynamic JavaScript</title>
</head>
<body>
    <h1>Hi, my name is <span id="name-holder">...</span></h1>
    <p>My favorite number is <span id="number-holder">...</span></p>
    <p>My motto is <span id="motto-holder">...</span></p>
    <script>
        var myName = "JavaScript Learner";
        var myLuckyNumber = 14;
        var myMotto = "Seize The Day!";
    </script>
</body>
</html>

So the last thing we will do now is get our variable data into our HTML document. To do this we need to create additional variables in the JavaScript that represent the HTML elements. Let’s do this by adding the following code to the JavaScript section.


var myNameHolder = document.getElementById("name-holder");
var myLuckyNumberHolder = document.getElementById("lucky-number-holder");
var myMottoHolder = document.getElementById("motto-holder");
var myName = "JavaScript Learner";
var myLuckyNumber = 14;
var myMotto = "Seize The Day!";

Now we will add the code to update the HTML with our variable values.


var myNameHolder = document.getElementById("name-holder");
var myLuckyNumberHolder = document.getElementById("lucky-number-holder");
var myMottoHolder = document.getElementById("motto-holder");
var myName = "JavaScript Learner";
var myLuckyNumber = 14;
var myMotto = "Seize The Day!";
myNameHolder.innerHTML = myName;
myLuckyNumberHolder.innerHTML = myLuckyNumber;
myMottoHolder.innerHTML = myMotto;

Save your document and run it in the browser. You should see the page update with your JavaScript variable values thanks to the .innerHTML element. I’m going to talk a bit more about the significance of how all this stuff works in sec, but firstly just a few points…

This example is in itself somewhat naff. For the same result that we see on the webpage the data could simply be included in the HTML. The idea here however is to show you in a simple way how the website content can be updated dynamically with values generated from the JavaScript.

Secondly the code in the above example could be abbreviated by writing something like:

//document.getElementById("name-holder").innerHTML = "John Doe";
// or
// document.getElementById("name-holder").innerHTML = myName;

However I have found that when developing apps etc, the code actually ends up being more graceful in the long run if I follow the standard practice of:

  1. Declaring the variables that I need, either with an initial value or without.
  2. Declaring variables for the HTML elements that will hold updating data.
  3. Assign the values of the variables to the innerHTML of elements. (Later I will show how this will be done using JavaScript functions).

The Document Object Model (DOM)

The way JavaScript works is by updating something called the Document Object Model or ‘DOM’. JavaScript can’t update the static code that we provide to the browser but it can update the browser’s ‘representation’ of the HTML code.

I’m not the best person to explain what the DOM is exactly, or how it works. – There is plenty of information about this on the net. For now however I’m simply going to show you how you can see it in action.

Firstly open the webpage we created previously in the browser and view the course code. In Chrome you can easily do this by right-clicking on the webpage and selecting ‘View Page Source’. Here chrome will simply open the code file in a new tab.

Now go back to your webpage tab and right-click and select ‘Inspect’. Then click on the Elements tab and look at your code there. You will see that in this version of the code the code has been updated by the JavaScript. This is essentially the DOM you are looking at. Like I said I’m far from an expert on the DOM but I think of it as a type of dynamic representation or virtualisation of the otherwise static HTML code.

References

There are plenty of places on the net to access JavaScript learning material. I think a good place to start is the JavaScript section of w3Schools.

Recap

It might not seem like all that much, but a lot of the fundamentals for coding in JavaScript have been covered here. By now you should hopefully:

  1. Understand what JavaScript is and what it is used for.
  2. Understand the basics of how JavaScript can be applied, eg inline or as an external document.
  3. Understand the basics of JavaScript formatting, eg:
    1. Commenting
    2. Casing
    3. Ending lines with a semicolon
  4. Understand what a variable is.
  5. Understand how to work with Variables, eg:
    1. Declaring variables
    2. Assigning number or string values to variables
  6. Know how to access and utilise the Browser console.
  7. Know how to update HTML content with JavaScript variable values.
  8. Have a basic understanding of how JavaScript works with the DOM and how you can view the DOM.

Next Steps

From here, for me the next steps in the JavaScript learning journey would include:

  1. Learning methods to capture user input though things like forms and buttons and use this data to update the HTML.
  2. Learning how to extend the JavaScript with ‘functions’.
  3. Understanding variable scope.
  4. Learning how to work with simple arrays of data.
  5. Consolidating all these things by creating some simple apps.

Otherwise I hope you found this tutorial / guide useful.

Next Javascript Tutorial

I would love to make it my thing to create tutorials and learning resources that are 100% free with no strings attached.

If this tutorial was useful for you please consider showing your appreciation and offering your support. It will make my day!

Buy me a coffee