How to Write JavaScript – Master What is JavaScript Fast

Welcome to our comprehensive tutorial on how to write JavaScript and its diverse applications. Whether you’re a beginner who’s just diving into the world of coding, or an experienced developer aiming to refine your skills and learn something new, this tutorial is designed for you. We’ll tackle the basics of JavaScript, why you should consider learning this language, and how to set up and run JavaScript code. You’ll also get to grips with documented object models and even learn how to manipulate web page elements using JavaScript. Sound exciting? Let’s get started!

Before you begin, it’s essential to note that some familiarity with HTML and CSS will prove beneficial as we’ll be delving into modifying some HTML elements and CSS properties throughout the tutorial. Don’t worry if you’re not completely comfortable with these, though, as each concept is thoroughly explained.

Project Files

For your convenience, we have included a complete copy of the code used in this tutorial, allowing you to follow along effortlessly in learning how to write JavaScript. Download them and let’s dive into the world of JavaScript.

Download Project Files Here

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

What is JavaScript

JavaScript was originally designed in 1995 as a scripting language to make websites interactive. Over the last 25 years it has evolved to be a core building block of the modern web and beyond. JavaScript is now used in everything from web development, games, mobile apps, desktop software, server-side functionality and even space exploration technology. In 2020, GitHub (used by more than 50 million developers to build and maintain software) noted that JavaScript remains the most popular programming language in the world.

For those more technologically savvy in programming languages, you might be asking, “Is JavaScript an interpreted language or a compiled language?” The answer here is interpreted, so it is closer to the vein of popular languages like Python. This said, just-in-time compilers are fairly popular for JavaScript applications, so there are options.

Why Learn to Code in JavaScript?

Beyond being ranked as the most popular coding language by GitHub, it’s important to note that 70% of companies hiring developers are looking for people with JavaScript skills with average salaries above $100,000 a year.

popular language rank

JavaScript has become a powerful and versatile language used by the world’s top companies, on their flagship products and services, including Facebook, Google, Microsoft, eBay, Netflix, Uber, NASA and SpaceX.

Running JS Code

In this section, we look at how to run JavaScript code – as you can’t learn how to write JavaScript if you can’t run it.

For that we require a web browser and code editor. When it comes to code editors there are many good choices for JavaScript. We will be using Visual Studio Code (VS Code) which is free, widely used, and available for all operating systems. We will also demonstrate repl.it (https://repl.it/) – one of the many online options available for anyone wanting to get started without installing any software on your local computer.

Follow along with the relevant VS Code installation (Windows or Mac) or skip past the VS Code sections to run your first line of JavaScript in an online environment.

VS Code Installation (Windows)

To install VS Code on Windows, browse to the VS Code homepage (https://code.visualstudio.com/) and follow the installation instructions for your operating system For Windows, click Download for Windows which will download the executable file to your computer. Once that completes, run the installation exe and follow the installation prompts accepting or adjusting the default settings. When installation completes, you can run VS Code from the installation window or from the Windows Start Menu.

visual studio

visual studio installation

vs code download

vs code installation

vs code welcome screen

VS Code Installation (Mac)

To install VS Code on Mac, browse to the VS Code homepage (https://code.visualstudio.com/) and follow the installation instructions for your operating system. For Mac, click Download for Mac and select the option to Open with Archive Utility to extract it. When the file finishes downloading you should see the extracted VS Code file in your Downloads folder. From there, drag the VS Code file to the Applications folder if you want it in your task bar otherwise just double-click to open code editor. You may be prompted with a security warning. If so, click open.

VS Code homepage

Open with Archive Utility

download for mac

drag to applications

open and install

vs code for mac welcome screen

Demonstrate Simple JavaScript in VS Code

With VS code installed, we can now work on the actual how to write JavaScript part of this guide.

With your editor setup, choose a place to store your code files. If you don’t already have a place, you can simply create a folder in your Documents or on your Desktop to get started. Inside VS Code, choose the File menu option and Open Folder menu item. In the example below, we create a new folder named JS Course inside our Documents folder (you are free to choose any location).

Open Folder menu

new folder

Documents folder

On the VS Code side bar you will see the Explorer on top. Click this icon to see the folder we just created. Once we create files for this project they will show here.

VS Code side bar

Create the first file by clicking on the New File icon (as shown below) or through the menu option choosing File | New File. Name the new file index.html.

New File

index.html

This html file represents a web page so anything written here will be displayed to the user. Type hello world into the index.html file.

hello world

There are many ways to open this file in a web browser. For simplicity either locate the file using File Explorer or right-click on the file in VS Code and choose open in browser from the context menu. The text we typed into the html page will appear in the browser. Of course, this isn’t exactly how to write JavaScript – so what’s the next step?

open in browser

In order to run JavaScript from within a html file we must put inside <script></script> tags. Inside these script tags we can write JavaScript code such as the following command to display a dialog box to user with the text Hello World. Save the file (control+s on windows or cmd+s on mac) then open the file again in the web browser to see the text displayed to the user in a dialog box. We are now running JavaScript code in the browser.

<script>
    alert('Hello World')
</script>

script tags

Demonstrate Simple JavaScript in repl.it

As mentioned in the introduction, there is an alternative to installing software on your computer in order to master how to write JavaScript code. We can use an online environment such as repl.it. If you want to try this option to go (https://repl.it/) and sign-up for a free account. Then, from the dashboard, create a New REPL with HTML, CSS, JS as the Language option.

Language option

HTML, CSS, JS

Delete all the code inside index.html and replace it with:

<script>
    alert('Hello World')
</script>

script run

Press the Run button and the dialog box with Hello World appears in the browser running the repl.it  website.

repl.it website

Final Notes on How to Write JavaScript

While online coding environments provide a great place for demos, learning, sharing or testing snippets of code, trying out the basics of new languages, and more, it is important to mention that if you are serious about programming and want to move to real projects, we recommend using VS Code or another code editor that allows you to set up a computer-based development environment.

And yes, this applies even if you’re just learning how to write JavaScript. There is a whole wide world of JavaScript out there – from simple browser-based activities using pure JavaScript to the hundreds of JavaScript frameworks that power web apps.

Intro to the DOM API

We’ve already shown the basics of how to write JavaScript, but how do we apply this practically? Let’s talk about JavaScript’s main use at the moment – altering web pages.

The DOM refers to the Document Object Model which is the JavaScript representation of the HTML  on a web page. The HTML page is made up of elements which are created using tags such as <body><h1>, and <p> as shown below:

<body>
  <h1 id="first-heading">JavaScript</h1>
  <p>Learn coding at <a href="https://zenva.com/">Zenva</a></p>
</body>

The DOM is represented in the browser by a tree-like structure where you start with a top node and then you have sub-nodes that contain all of the content.

DOM structure

The DOM API is the Application Programming Interface that JavaScript uses to access and modify DOM elements. In this lesson we’ll learn DOM API basics such as selecting an element by its ID, changing its text or HTML content, and lastly modifying its CSS style properties.

Challenge

Our client’s website welcome sign has been hacked. Its message has been changed along with its color. Since the sign uses HTML, our challenge is to access the DOM from JavaScript to select the DOM element we need to change, modify its text or innerHTML, and finally change its color using the DOM element’s style property. Specifically we need to:

DOM element style property

Requirements
Change welcome sign text back to “Welcome, travelers!”
Change the font color back to blue

Create DOM Elements

Our first step in mastering this aspect of how to write JavaScript is to discover how to target elements.

The first thing to do is re-create the welcome sign from our client’s web page so we can work on a solution from JavaScript to meet the requirements we defined above. To do this we add a HTML <div> tag element and give it an ID, style to set its color, and include the hacked welcome text to be displayed on the web page.

Note that we will also create a separate script.js file. By putting this in the script tag’s src, we can link to that file and keep our code base cleaner. This will be common when you master how to write JavaScript. So, while you can include all the code directly in the same file, practicing with a different file is good.

<!-- index.html -->
<div id="sign" style="color:red;">Welcome, pirates!</div>

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

Browser Web Page:

welcome text

Select DOM Element

We now switch our focus to the JavaScript file. When working with the DOM, it’s important to remember that if we want to affect it we must select it. We select a DOM element from JavaScript by using the document Object. One method available to us is getElementById (be cautious of the method’s casing… it needs to be exact). This method allows us to select a specific DOM element based on ID. The ID we provided above is sign so that is what we use to select the associated DOM element. Notice in the Browser Developer Console that the <div> with an ID of sign has been selected.

// script.js
// 1. Select
let sign = document.getElementById('sign');
console.log(sign);

Browser Developer Console output:

<div id="sign" style="color:red;">Welcome, pirates!</div>

Modify Text Content

If you need to modify the actual HTML content you could use the document.innerHTML method. If you just need to modify the HTML element’s Text content you could use the document.textContent  method.

// script.js
// 1. Select
let sign = document.getElementById('sign');

// 2. Modify
console.log('BEFORE:', sign.textContent);

sign.textContent = 'Welcome, travelers!';

console.log('AFTER:', sign.textContent);

UPDATED Browser Web Page:

UPDATED Web Page

Browser Developer Console output:

BEFORE: Welcome, pirates!
AFTER: Welcome, travelers!

Change DOM Element Style

We now have the correct message showing on the client’s web page but it still does not look quite right. Our next step is to change the HTML element’s font color. We do this by accessing the HTML element’s style property which gives us access to all of the CSS for the DOM element so you can change color, size, and more. In fact, you can access all CSS properties and the assignment to the element’s style property is any value that is valid CSS.

// script.js
// 1. Select
let sign = document.getElementById('sign');

// 2. Modify
sign.textContent = 'Welcome, travelers!';

// 3. change style
sign.style.color = 'blue';

UPDATED Browser Web Page:

UPDATED Web Page

Congratulations! Mission Complete!

Conclusion

And voila! You’ve now successfully navigated the world of JavaScript, from understanding why learning this language is beneficial to running JavaScript code and manipulating HTML elements using the DOM API. We hope this tutorial has clarified some key concepts and helped you bolster your coding arsenal.

Of course, this is just skimming the surface of what JavaScript can do. To truly master JavaScript and its potential, consider immersing yourself in more complex projects, diving into libraries and frameworks, and continuously practicing your skills. You might also consider other educational resources that delve into more complex topics, such as web development, game development, or even machine learning.

The sky’s the limit, and JavaScript can be your ticket to a thrilling career in coding. We hope you enjoyed this tutorial as much as we enjoyed guiding you through it, and we very much look forward to seeing what you create in the future. Happy coding!

Want to learn more? Try our complete JAVASCRIPT PROGRAMMING FOR BEGINNERS course.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.