JavaScript tutorial for beginners

 Published on 2018-10-15

JavaScript is one of the most popular programming languages, and one of the three core technologies of the World Wide Web (besides HTML and CSS). Most websites use JavaScript either on the frontend (to add interactivity), or on the backend (to serve content from a server, store data, etc).

The language itself has APIs for working with text, numbers, arrays, objects, dates, regular expressions, manipulating page content (on the frontend), or serving dynamic web pages (on the backend, through Node.js).

In this tutorial, which you can follow even if you have no programming experience with JavaScript, we will focus on the main features of the language. We will finish up with a look at jQuery – a popular library designed to simplify page and event manipulation.

A simple example

JavaScript can be directly included in an HTML document using the "script" tag. Multiple scripts can be embedded into one document. The actual JavaScript code can be included inline (right inside the script tag), or in a separate file (in which case, we need to set the "src" attribute to point to the file location).

Let's look at a basic example where we use JavaScript to calculate a simple math expression, and then present the result inside a paragraph.

<!doctype html>
<html lang="en">
  <head>
    <title>A JavaScript example</title>
  </head>

  <body>
       <p id="math-operation-paragraph"></p>

       <script>
           var result = 2+5;
           document.getElementById('math-operation-paragraph').innerHTML = result;
       </script>
  </body>
</html>

The "script" tags are usually placed at the end of the "body" section of a document, although (traditionally), it was placed inside the "head" section. By making sure we read/execute the JavaScript code at the end, we don't block the loading of the page, and we have a pretty good idea that elements have already been rendered on the page, so we can start dynamically manipulating them through our JavaScript code.

You might have guessed that the code given above will print "7" (because 2+5=7), and you (of course) would be right. However, to really understand how to write JavaScript code correctly, we need to know the main elements of the JavaScript grammar.

Syntax

Any programming language offering as many features as JavaScript has the notion of expressions, storing values in variables, calculating or comparing values (with operators), conditionally executing some code (i.e. if a condition has been met), etc. The JavaScript grammar has all of those elements. Let's see this inside a table summarizing the key details:

OperatorsOperators can be used to compare or calculate values (from other values or variables). For example, we can use the "+" operator to calculate that 2+5=7, as we did in the example above. JavaScript supports multiple math and comparison operators.
VariablesVariables are storage locations paired with a symbolic name, allowing us to store values and reference them later in a program. In the example given above, we have a variable named "result", which holds the value 7.
ExpressionsYou can think of expressions as combinations of values, variables and operators that produce a meaningful result. For example, "2+5" is an expression.
StatementsIn JavaScript, statements are (usually) separated with a semicolon ";", and take the form of conditionals, loops, manipulations, etc. For example, "if (result > 5) alert('We have a problem');" is a statement where we conditionally show an alert if the value stored in the "result" variable is larger than 5.
ObjectsObjects are collections of many properties, where each property (basically) acts as a variable holding a certain value. For example, we can have an object called "person" which has several properties: firstName, lastName, age, etc. By grouping all of these parameters under one object, we can manipulate it more easily, send it as a parameter to other locations in our code, etc.
FunctionsA function is a set of instructions/statements that perform some action. For example, we can have a function called "max" that returns the maximum of two (or more) numbers. A lot of functions are already available in JavaScript, but we can easily create new functions as we will see below.

Variables and operators

We use variables to store, manipulate and operate on data. Variables should be given meaningful names, and those names usually start with a letter – but later may also contain digits and underscores (_). Names are case-sensitive.

We use the "var" keyword to create variables, after which we specify the name of the variable (like "total", "firstName", "age", "socialSecurityNumber", etc). Variables may store various types of data – JavaScript allows us to manipulate numbers (like 5 and 5.1239), strings (like "Mike"), Booleans (like true or false), Objects, and more. There are two special values commonly used in JavaScript – null (something that has no value and means nothing), and undefined (which is the default thing stored in a variable that has been declared, but no value has been assigned/stored there). Variable values can be changed throughout the execution of a given function, and variables initialized with the "var" keyword are scoped (i.e. can be used), inside the entire function where that variable has been defined. We'll talk more about functions, scopes and variables later on.

Before we move on to viewing several examples, let's take a look at some common operators available in JavaScript. First, we should point out that we can do the common four math operations: addition (+), subtraction (-), multiplication (*) and division (/). When we need to divide two integers, it's possible that we can end up with a remainder. In that case, we can use the modulus (%) operator to calculate the remainder (for example, 10%3=1, because 10 = 3*3 + 1).

Two other common operators are the increment (++), and decrement (--) operators. These operators work on just one variable, and they either increase (++) or decrease (--) the value inside the variable by 1. So, if the value stored in the variable x is equal to 5, after the operation x++, the value stored inside x will be equal to 6.

It is also possible to compare variables and/or values. The result of these operations will be either true or false (i.e. booleans), because the comparison will be either true or false. For example, 5 < 3 will return false, because 5 is not smaller than 3.

Let's take a look at some examples:

   var x = 5;
   var y = 3;

   var firstName = "Donald";
   var lastName = "Trump";


   var sum = x+y; //sum now stores the value 8
   var name = firstName + " " + lastName; //name = "Donald Trump"

There are more operators that we can use in JavaScript. The following operators can be used to compare variables and values: < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and != (not equal). That's right, to compare if two values are equal, we should use the == operator, because = (one equals sign) is used for assigning values to variables.

Statements

Before we start with some practical examples of using JavaScript to create awesome interactions and pages, we must dive deeper into statements. In programming, we use statements to define the programming flow. Normally, these statements are executed sequentially (one by one, starting from the top), but, as we shall see in a moment, we can alter this behavior with things like conditionals (executing statements only if a certain condition is met) and loops (repeatedly executing statements or blocks).

We can surround several statements with blocks. Blocks are created with braces {}, and all statements between braces belong to the block. You will understand the benefits of blocks as we take a look at conditionals (if-else) and loops.

Let's start with conditionals – i.e. control structures that allow us to execute statements only when certain conditions are met. The most common way of doing this in JavaScript is through the if-else statement. Let's take a look at an example that alerts the user if he entered a number larger than 10 or not.

if (number > 10)
{
	alert("You entered a number larger than 10").
}
else
{
	alert("You entered a valid number").
}

Notice how we specified the condition right after the if keyword. Similarly, we used blocks in this example, even though that is not really necessary here, because we only have one statement inside the blocks. However, it's good practice to always use blocks with if-else statements and loops. In the example above, we also specified what should happen if the (number > 10) condition is not met - with the "else" keyword. That part of the code is optional – i.e. sometimes you don't want to define an "else" block, and JavaScript allows you to omit it.

Loops are also common in programming. They allow us to repeatedly execute one or more statements. In JavaScript, we use either the "for" loop (typically, when we know how many times we want to execute the loop), or the "while" loop (when we have some other condition that we want to check). For example, the code below will calculate the sum of all integers between 1 and 10, and store it in a variable called "sum".

   var sum = 0;
   for (var i=1; i<=10; i++) {
      sum = sum + i;
   }

   alert("The sum is: " + sum);

This might look strange to you at first, but it won't once we explain what's going on here. At the start of the for loop, we initialize a variable "i" to the value 1. Then, because 1<=10, the statement inside the block will execute and increase the variable "sum" by "i". Afterwards, the value of "i" is increased by 1, because after the statements inside the block are executed, the program flow jumps to the statement in the top-right of the for-loop. After that step, the condition (i<=10) is checked again, statements are executed again, and the whole process continues until "i" becomes larger than 10 (i.e. i<=10 is no longer satisfied). For loops are very common in programming, so make sure you take as much time as needed to understand what is happening in the code presented above. In short, when we define the for loop, we start with an initial value for a variable, in the middle we have the condition that is checked before each iteration, and on the right we have code that is executed after the block of statements is executed (usually, here, we update the variables that are part of the condition that is checked before each execution of the for loop - because we want to cause, at some point, the end of the for loop – in this case, after 10 iterations).

The "while" statement is much simpler to define, as we should only set the condition that needs to be checked before each iteration of the loop. Here is how we can calculate the sum of the first 10 integers using a while loop:

   var sum = 0;
   var i = 1;

   while (i <= 10) {
		sum = sum + i;
		i++;
   }

   alert("The sum is: " + sum);

When it comes to loops, we may sometimes need to "break" out of a loop (i.e. jump to the next statement after a loop if some "unexpected" condition happens). We can use the "break" statement to achieve that. Similarly, we may want to stop the current iteration of the loop and jump to the top of the loop (i.e. continue with the next iterations of the loop). In that case, we can use the "continue" statement. The following code will calculate the sum of the first 5 integers (1+2+3+4+5), because we're going to jump out of the loop when "i" becomes larger than 5.

   var sum = 0;
   var i = 1;

   while (i <= 10) {
		sum = sum + i;
		i++;

		if (i > 5) {
			break;
		}
   }

   alert("The sum is: " + sum);

Comments

You probably noticed this already, but we should mention it once again nonetheless. In JavaScript, as in other programming languages, we can add comments to our code to help us (and other developers) understand what's going on. Comments are optional, but very useful. They are not executed by the interpreter, so you can put anything you want inside comments. However, aim for short comments that explain the key details of your code – especially details that are not clear from the code itself.

To add a single line comment, you should use two backslashes (//). For multi-line comments, you begin the comment with /*, and end it with */. Here is an example:

   var sum = 0;

   /* calculate the sum of all
   integers between 1 and 10 */
   for (var i=1; i<=10; i++) {
      sum = sum + i;
   }

   //now, show an alert with the result
   alert(sum);

Objects

Objects are collections of variables (called properties), grouped under one name. For example, we can have an object called "person" storing details about, well, a person: his name, age, social security number, phone number, etc. By grouping all of those properties under one name, we can manipulate them more easily, send them to different parts of our code, etc. (Note: objects can also have functions, called methods, that can be called on that object – for example, a method call() to dial a person's phone number. We will talk about methods later on in this tutorial)

We access (set, read and update) the properties of an object with the dot operator, like so: "person.firstName". Similarly to other variables, properties are also case-sensitive, so you should always type them the same (i.e. firstName is not the same as FIRSTNAME).

We can create objects by calling "new Object()". Later, you can assign and read properties as outlined above. Let's look at an example to see objects in action:

   var person = new Object();
   person.firstName = "Donald";
   person.lastName = "Trump";
   person.age = 60 + 3;

   person.fullName = person.firstName + " " + person.lastName;
   alert(person.fullName + " is " + person.age + " years old.");

Simple, right? Please note that there are other methods of creating an object. For now, let's look at another common problem with objects: how to iterate through all properties. As it turns out, this is very simple in JavaScript by using the for..in statement. To be more specific, the following code will iterate through all properties of the object called "person":

   for (var property in person) {
         //a property name (ex. "firstName") is stored in "property"
         //we can access the property value with person[property]
   }

Please note how, if we have a property name stored in a variable, we can access the object's value stored at that property as person[property] and not person.property. The difference here is that the second notation (person.property) will search for a property called "property" in the person object. The first notation will search for a property named according to the value inside that variable (so if property="firstName", it will access the "firstName" property).

Arrays

An array is a special variable that can store multiple values. In JavaScript, arrays are objects that use numbers to access elements, compared to regular objects (that use "names" to define properties). We can loop through the elements of an array, push new elements inside an array (with the push method), get the number of elements inside the array (with the length property), and more.

Let's look at an example, where we store 5 numbers (and let's imagine that those numbers represent student grades). Please note how we create an empty array [] at the start of the source code, and how we add new elements to the array with the push() method.

   var arr = [];
   arr.push(4);
   arr.push(5);
   arr.push(3);
   arr.push(2);
   arr.push(4);

   alert("Array has a total of " + arr.length + " items.");

We access (read and set) items inside the array with indexes (numbers). The first element inside the array can be accessed with the number 0 (arr[0]), the second with the number 1 (arr[1]), etc. The code below will calculate the average grade based on the array defined in the code above. Please note how we use the length property to determine the number of elements inside the array.

   var sum = 0;
   for (var i=0; i<arr.length; i++) {
          sum = sum + arr[i];
   }

   var average = sum / arr.length;
   alert("The average grade is: " + average);

Pretty easy right? Arrays are a powerful mechanism of storing multiple values. Imagine a social network (ex. Facebook), and the fact that each user has multiple friends on it. These friends can be stored inside an array, and we can then perform various calculations on that array.

Functions

We can use functions to group statements that perform or solve a particular task. In JavaScript, we can use the "function" keyword to define a function, after which we set the name of the function, and the parameters it needs to complete it's job. We can easily "call" a function when we need it by providing the name of the function and the necessary parameters (arguments). Let's see an example of a function that returns the maximum of two values.

  function max(a, b) {
    if (a > b) {
      return a;
    } else {
      return b;
    }
  }

Please note how we use the "return" statement to return a result from the function (in the example above, that will be the larger value of a or b).

We can easily call this function in our code by naming it: max(3, 5), max(7, 2), max(x, y), etc (note that x and y are variables in the last example). When you call max(3, 5), for example, the function will execute with a=3 and b=5, because the first parameter in the function definition is called a (and you provide the value 3 as a first argument), while the second parameter is called b (and you provide the value 5).

Please note that we were calling functions in the previous examples of this tutorial as well (alert was one of them). Functions are very useful, and you should separate your code into functions to make sure it's readable and easy to extend in the future.

Real examples

Ok, ok, enough talk. Let's see how we can use JavaScript to solve common problems that appear on the frontend side. Let's write a page that contains two input boxes (where the user will provide two numbers), a button, and a paragraph. When a user clicks on the button, the page should calculate the sum of the two numbers and print it inside the paragraph.

We are going to take our job seriously in this example, and warn the user if he makes a mistake – i.e. if he doesn't type a real number in the input boxes, and instead types something else there (for example, a name or something).

Let's look at the code that solves this problem.

<!doctype html>
<html lang="en">
  <head>
    <title>Sum calculator</title>
  </head>

  <body>
       <input type="text" id="number1" />
       <input type="text" id="number2" />
       <button type="button" onclick="calculate()">Calculate</button>

       <p id="result"></p>

       <script>
           function sum(a, b) {
                a = parseInt(a, 10);
                b = parseInt(b, 10);

                return (a+b);
           }

           function calculate() {
                 var a = document.getElementById("number1").value;
                 var b = document.getElementById("number2").value;

                 var result = sum(a, b);
                 if (isNaN(result)) {
                     return alert("One of the boxes doesn't contain a valid number.");
                 }

                 //else, show their sum
                 document.getElementById('result').innerHTML = 'The sum is: ' + result;
           }
       </script>
  </body>
</html>

The example above doesn't contain a lot of lines, but it allows us to discuss three other things we weren't able to mention before.

First, notice how we make sure that whenever someone clicks on the button, the function called "calculate()" is called. We do this using the "onclick" event handler. This means that, whenever someone clicks on the button on which we defined the onclick handler with the "onclick" attribute, the appropriate function will get called.

Second, note how we find the elements we need with the "document.getElementById" function. Once we do that, we either read a value from the input boxes (from the "value" property), or we set an appropriate text into an element with the "innerHTML" property (we can provide html as well here, not just text).

Finally, it's worth pointing out what the parseInt() functions do in the sum() function. As it turns out, the user can type anything into the input boxes (including text), and the browser has no idea if you want it to return a number for you, or text (as a string). Therefore, because the user can type random strings there, it will always return data in text format (even if it's just a number, like "35"). To convert a string (like var a="5") to number format, we can use the parseInt() method. As the first argument, we provide the text string, and as a second argument the number base (when humans work with numbers, we usually use base 10, so we provide 10 as the second argument).

What is jQuery?

We can use a very popular library, called jQuery, to attach event handlers, change element's behavior, content or style, and a lot more – right from our JavaScript code. The purpose of jQuery is to make JavaScript easier to use, handle various differences between browsers (Firefox, Chrome, IE, Edge, Safari, etc) transparently, make our code shorter and extendable, and make common tasks much simpler. To get started, we need to reference the library with a script tag (either from a CDN, or we can download a local copy of it), and then simply use the methods and features it offers.

Let's see an example. Please note how we use CSS selectors to find an element ('#' is used to indicate that we search for an element by id), how we handle the onclick event with the "click" method, how we extract values from elements with val(), and how we edit the element content with the html() method. Although this might look complicated at first, this example actually shows a lot of the features offered by jQuery, including the selectors, the click event, val() and html(). Please note how we include jQuery inside the head section, and how we precede selectors with $.

<!doctype html>
<html lang="en">
  <head>
    <title>Sum calculator</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
  </head>

  <body>
       <input type="text" id="number1" />
       <input type="text" id="number2" />
       <button type="button" id="calculate-button">Calculate</button>

       <p id="result"></p>

       <script>
           function sum(a, b) {
                a = parseInt(a, 10);
                b = parseInt(b, 10);

                return (a+b);
           }

           $('#calculate-button').click(function(){
                 var a = $("#number1").val();
                 var b = $("#number2").val();

                 var result = sum(a, b);
                 if (isNaN(result)) {
                     return alert("One of the boxes doesn't contain a valid number.");
                 }

                 $('#result').html('The sum is: ' + result);
           });
       </script>
  </body>
</html>

A lot of people find jQuery much easier to write, read and test. It's also much easier to use methods like html(…) instead of fighting properties like innerHTML. Similarly, we can use jQuery selectors to find elements instead of document.getElementById() and other methods, so make sure you take a look at jQuery. It's pretty cool.