Learning JavaScript Data Structures and Algorithms
上QQ阅读APP看书,第一时间看更新

JavaScript basics

Before we start diving in to the various data structures and algorithms, let's have a quick overview of the JavaScript language. This section will present the JavaScript basics required to implement the algorithms we will create in the subsequent chapters.

To start, let's look at the two different ways we can use JavaScript code on an HTML page. The first example is demonstrated by the following code. We need to create an HTML file (01-HelloWorld.html) and write this code in it. In this example, we are declaring the script tag inside the HTML file and, inside the script tag, we have the JavaScript code:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
  </head> 
  <body> 
    <script> 
      alert('Hello, World!'); 
    </script> 
  </body> 
</html> 
Try using the Web Server for Chrome extension or the http-server to run the preceding code and see its output in the browser.

For the second example, we need to create a JavaScript file (we can save it as 01- HelloWorld.js) and, inside this file, we will insert the following code:

alert('Hello, World!'); 

Then, our HTML file will look similar to this:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title></title> 
  </head> 
  <body> 
    <script src="01-HelloWorld.js"></script> 
  </body> 
</html> 

The second example demonstrates how to include a JavaScript file inside an HTML file.

By executing any of these two examples, the output will be the same. However, the second example is the most used by JavaScript developers.

You may find JavaScript include statements or JavaScript code inside the head tag in some examples on the internet. As a best practice, we will include any JavaScript code at the end of the body tag. This way, the HTML will be parsed by the browser and displayed before the scripts are loaded. This boosts the performance of the page.