JavaScript has become a staple in modern web development. This powerful language has evolved into an essential tool for any web developer to understand.

JavaScript has special features that make it different from traditional programming languages. We're going to dig into what it is, how it works, and what you can do with it. Let's break it down.

What Is JavaScript?

JavaScript is a scripting language for the web. It is an interpreted language, which means it does not need a compiler to translate its code like C or C++. JavaScript code runs directly in a web browser.

The latest version of the language is ECMAScript 2018 which was released in June 2018.

JavaScript works with HTML and CSS to build web apps or web pages. JavaScript is supported by most modern web browsers like Google Chrome, Firefox, Safari, Microsoft Edge, Opera, etc. Most mobile browsers for Android and iPhone now support JavaScript as well.

JavaScript controls the dynamic elements of web pages. It works in web browsers and, more recently, on web servers as well. Application Programming Interfaces (API) are also supported by JavaScript, giving you more functionality.

Understanding all the ways JavaScript works is a little easier when you understand how web programming works, so let's learn more.

Web App Building Blocks

There are three components that build websites and apps: Hypertext Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript. Each one has a role in creating a web app.

  • HTML is a markup language that creates the skeleton of the web page. All the paragraphs, sections, images, headings and text are written in HTML. The content appears on the website in the order they are written in HTML.
  • CSS controls the style and the additional aspects of the layout. CSS is used to create the design of the website creating the colors, fonts, columns, borders, etc. It takes the website from plain text elements to colorful designs.
  • The third element is JavaScript. HTML and CSS create the structure, but they don't do anything from there. JavaScript creates dynamic activity on your app. Scripting in JavaScript is what controls functions when buttons are clicked, how password forms are authenticated, how media is controlled.

All three parts work in harmony with each other to create full-scale apps. It would be a good idea to learn more about HTML and CSS if you're not entirely comfortable with them.

How Does JavaScript Work?

Before writing JavaScript it's important to know how it works under the hood. There are two important pieces to learn about: How the web browser works, and the Document Object Model (DOM).

How JavaScript works

The web browser loads a web page, parses the HTML, and creates what is known as a Document Object Model (DOM) from the contents. The DOM presents a live view of the web page to your JavaScript code.

The browser will then grab everything linked to the HTML, like images and CSS files. The CSS information comes from the CSS parser.

The HTML and CSS are put together by the DOM to create the web page first. Then, the browsers' JavaScript engine loads JavaScript files and inline code but does not run the code immediately. It waits for the HTML and CSS to finish loading.

Once this is done, the JavaScript is executed in the order the code is written. This results in the DOM being updated by JavaScript code and rendered by the browser.

The order here is important. If the JavaScript did not wait for the HTML and CSS to finish, it would not be able to change the DOM elements.

What Can I Do With JavaScript?

JavaScript is a full-fledged programming language that can do most things a regular language like Python can do. These include:

  • Declaring variables.
  • Storing and retrieving values.
  • Defining and invoking functions, including arrow functions.
  • Defining JavaScript objects and classes.
  • Loading and using external modules.
  • Writing event handlers that respond to click events.
  • Writing server code.
  • And much more.

Warning: Since JavaScript is such a powerful language, it is also possible to write malware, viruses, and browser hacks to inflict them on the users. These range from stealing browser cookies, passwords, credit cards to downloading viruses onto your computer.

Using JavaScript

Let's look at some JavaScript basics with code examples.

Declaring variables

JavaScript is dynamically typed, which means you do not have to declare the type of your variables in your code.

        let num = 5;
let myString = "Hello";
var interestRate = 0.25;

Operators

Addition

        12 + 5
>> 17

Subtraction

        20 - 8
>> 12

Multiplication

        5 * 2
>> 10

Division

        50 / 2
>> 25

Modulus

        45 % 4
>> 1

Arrays

        let myArray = [1,2,4,5];
let stringArray = ["hello","world"];

Functions

JavaScript can write functions, here's a simple function that adds numbers.

        function addNumbers(num1,num2){
return num1 + num2;
}
>> addNumbers(10,5);
>> 15

Loops

JavaScript can perform loops for iteration, loops like for loops and while loops.

        for(let i = 0; i < 3; i++){ 
console.log("echo!");
}
>> echo!
>> echo!
>> echo!

        let i = 0;
while(i < 3) {
console.log("echo!");
i++;
}
>> echo!
>> echo!
>> echo!

Comments

        // Writing a comment
        /*Writing a multi-line comment
You can use as many lines as you like
to break up text and make comments more readable
*/

In a Web Page

The most common way to load JavaScript in a web page is to use the script HTML tag. Depending on your requirements, you can use one of the following methods.

  • Load an external JavaScript file into a web page as follows:
            <script type="text/javascript" src="/path/to/javascript"></script>
  • You can specify the complete URL if the javascript is from a different domain from the web page as follows:
            <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  • JavaScript can be directly embedded in the HTML. Here is an
            <script type="text/javascript">
    alert("Page is loaded");
    </script>

Other than these methods there are ways of loading JavaScript code on demand. In fact, there are frameworks dedicated to loading and running JavaScript modules with proper dependencies resolved at run time.

Those are more advanced topics, right now you're learning the basics.

Sample JavaScript Code Snippets

Here are some simple JavaScript code samples to illustrate how it is used on web pages. These are examples of code that work with the DOM.

  • The following selects all bold elements in the document and sets the color of the first to red.
            var elems = document.getElementsByTagName('b');
    elems[0].style.color = 'red';
  • Want to change the image in an img tag? The following associates an event handler for the click event of a button.
            <img id="myImg" src="prev-image.png">
    <button onclick="document.getElementById('myImg').src='new-image.png'">Change Image</button>
  • Update the text content of a paragraph (p) element? Set the innerHTML property of the element as shown:
            <p id="first-para">Hello World</p>
    <button onclick="document.getElementById('first-para').innerHTML = "Welcome to JavaScript!"'>Click me</button>

These code samples offer just a glimpse into what you can do using JavaScript on your web page. There are plenty of tutorials that can teach you how to code to get you started. You can try it out on any web page, even this one! Open up your console and try out some JavaScript code.

Now You Know What JavaScript Does

Hopefully, this introduction has brought some insights into JavaScript and gets you excited about web programming. You can recap it all in our handy JavaScript cheat sheet. There is much more to learn about JavaScript. Once you feel more comfortable why not try to learn how to use the Document Object Model? You might also be interested in learning about TypeScript.