top of page

Web Development: JavaScript



 

JavaScript is a crucial programming language and can be found all over the Internet. With 97.7% of all websites employing JavaScript as a client-side programming language, it is the most widely used. As a result, if you wish to work as a web developer, JavaScript abilities are a prerequisite. 

 

Begin your web development career by learning about the use of JavaScript, why it is so popular, practical JavaScript applications, and how to become a JavaScript professional.

 

What exactly is JavaScript, and what is it used for?

 

You must first understand what something is and what it does before you can start learning about it. This is incredibly beneficial Whenever you plan to learn a new programming language.

 

A programming language primarily used to create interactive websites is called JavaScript. A website's primary content and structure are described and specified in HTML. At the same time, CSS instructs the browser on how to display this HTML material by setting elements like color and typeface.

 

With only HTML and CSS, you can create a website that looks nice but doesn't do much. JavaScript adds functionality to the webpage, bringing it to life. It is in charge of items the user can interact with, for example, drop-down menus, modal windows, and contact forms. It can also make animations, video players, and interactive maps.

 

JavaScript is now an all-purpose programming language used across the entire software stack. The most common application is on the client side (aka front-end); however, since the introduction of Node.js, many people have used JavaScript on the server side (or back-end) as well.

 

JavaScript code is read, interpreted, and executed in the user's web browser when utilized on the client side. It is run on a remote computer when used on the server side. 

 

JavaScript is for more than just building websites. It can also be used to create browser-based games and, with specific frameworks, mobile apps for various operating systems. Developing additional libraries and frameworks enables the language to build back-end programs like web and server apps.

 

What is the appeal of JavaScript?

 

JavaScript is used in nearly every computing device we use today, including iPhones, Androids, Mac OS, Windows, Linux, and Smart TVs. The following are fundamental reasons why JavaScript became widely used for web development:

 

  • It may be utilized in both the front-end and back-end of web development and can benefit everyone from beginners to intermediate to advanced developers.

  • It can be used on any device.

  • It does not require any environment setup.

  • Standardized and new versions are routinely released.

  • Open Standards and Collaboration

  • Responds to user interactions using the Document Object Model (DOM).

  • Web browsers have been transformed into application platforms.

  • A diverse set of frameworks and libraries to aid in the development of complicated applications

 

A broad definition

 

A popular scripting or programming language called JavaScript makes adding intricate functionality to web pages possible. You can bet that JavaScript is used whenever a web page does something other than sit there and present static information for you to look at, such as timely content updates, interactive maps, animated 2D/3D visuals, scrolling video jukeboxes, and so forth. 

 

It is the third layer of a layer cake made up of standard web technologies, the previous two of which, HTML and CSS, have already been covered in other sections of the Learning Area.

 

We use HTML to structure and give meaning to our web content, such as establishing paragraphs, headings, and data tables or embedding images and videos.

 

CSS is a style rule language to add styling to our HTML content, such as changing background colors and fonts and arranging material in multiple columns.

 

JavaScript is a scripting language that permits you to generate dynamically updated information, manipulate multimedia, animate graphics, and do various other things. (Okay, not everything, but it's amazing what a few lines of JavaScript code can do.)

 

The three layers smoothly stack on top of one another. Consider a simple text label. We can use HTML to organize and purpose it:

 

<p>Player 1: Kunal</p>

Then we can throw in some CSS to make it seem nice:

p { 
font-family: "helvetica neue", helvetica, sans-serif; 
letter-spacing: 1px;
text-transform: uppercase;
  text-align: center;
  border: 5px solid RGB(0 0 200 / 0.5);
  background: RGB(0 0 200 / 0.5);
  color: RGB(255 0 255 / 1);
  box-shadow: 3px 3px 4px RGB(0 0 200 / 0.4);
  border-radius: 10px;
  padding: 3px 10px;
  display: inline-block;
  cursor: pointer;
}

 

Finally, some JavaScript can be used to implement dynamic behavior:

 

const para = document.querySelector("p");
 
para.addEventListener("click", updateName);
 
function updateName() {
  const name = prompt("Enter a new name");
para.textContent = `Player 1: ${name}`;
}

 

So, what exactly can it do?

 

The fundamental client-side JavaScript language includes specific popular programming tools that enable you to perform things like:

 

Keep valid values in variables. In the above example, we will now ask for a new name and store it in a variable titled as the name.

Operations on text strings (sometimes called "strings" in programming). In the preceding example, we add the string "Player 1: " to the name variable to form the full-text label, e.g., "Player 1: Kunal."

 

Executing code in reaction to particular events on a web page. In our last example, we utilized a click event to detect when the label was clicked and then ran the code that updated the text label. And a lot more!

 

However, the functionality added to the client-side JavaScript language is much more fascinating. Application Programming Interfaces (APIs) give you more powers to employ in your JavaScript code.

 

APIs are pre-packaged collections of code-building pieces that enable developers to implement otherwise tricky or impossible programs. In that, it is much simpler to take pre-cut panels and screw them together to make a bookshelf than it is to design one yourself, find the suitable wood, cut each panel to the appropriate size and shape, find the right-sized screws, and then put them together to make a bookshelf, they function similarly to ready-made furniture kits.

 

They are commonly classified into two types.

 

1.     Browser APIs

 

Browser APIs are always built into your web browser and can reveal data from the surrounding computer environment and perform functional, sophisticated tasks. As an example:

 

The DOM (Document Object Model) API allows you to create, remove, and change HTML and dynamically apply new styles to your website. The DOM operates whenever a popup window appears on a page, or new content is presented (as we saw above in our simple experiment).

 

The Geolocation API returns geographical data. This is how Google Maps locates and plots your location on a map.

 

You can build animated 2D and 3D visuals using the Canvas and WebGL APIs. As evidenced by Chrome Experiments and web samples, people do incredible things with various web technologies.

 

Audio and video APIs such as HTMLMediaElement and WebRTC enable you to do fascinating things with multimedia, such as playing audio and video directly on a web page or grabbing video from your web camera and displaying it on someone else's computer (try our simple Snapshot sample to get the idea).

 

Note: Many of the following demos will not function in an earlier browser; when exploring, it's best to execute your code in a current browser like Firefox, Chrome, Edge, or Opera. When you come closer to providing production code (i.e., actual code that real customers will use), you'll need to consider cross-browser testing in greater depth.

 

2.     Third-party APIs

 

Third-party APIs are not incorporated into browsers by default, and you must often obtain their code and information from someplace on the Internet. As an example:

 

For instance, you can use the Twitter API to display our most recent tweets on your website.

The Google Maps API and OpenStreetMap API allow you to embed custom maps and other such capabilities into your website.

 

Please remember that these APIs are sophisticated, and we will not address them in this module.

 

What is the purpose of JavaScript on your page?

 

In this section, we'll look at some code and see what happens when you run JavaScript on your page.

 

Let's quickly summarise what happens when you load a web page in a browser (initially discussed in our How CSS Works article). When you open a new web page in your browser, your code (HTML, CSS, and JavaScript) is executed within an execution environment (the browser tab). This is analogous to a factory that takes raw materials (the code) and produces a finished product (the web page).

 

The Document Object Model API (described above) is a popular way to edit HTML and CSS to update a user interface dynamically. It is always crucial to note that the code in the web documents is typically loaded, and then it gets executed in the order it appears on the page. If JavaScript is loaded and run before the HTML and CSS intended to modify, errors may arise. 


 

 

Browser Safety

 

Each browser tab has its separate bucket for running code in (technically, these buckets are called "execution environments") — this means that the code in each tab is typically run entirely independently, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a sensible security strategy; otherwise, pirates could start building programs to steal information from other websites, among other things.

 

JavaScript execution sequence

 

When the browser sees a JavaScript block, it executes it from top to bottom. This means you must be cautious about the sequence in which you arrange things. Returning to the JavaScript block from our first example:

 

const para = document.querySelector("p");
 
para.addEventListener("click", updateName);
 
function updateName() {
  const name = prompt("Enter a new name");
 
para.textContent = `Player 1: ${name}`;
}

 

Here, we choose a text paragraph (line 1), then connect an event listener to it (line 3) so that when the paragraph is selected, the updateName() code block (lines 5-8) is executed. The updateName() code block (these types of reusable code blocks are referred to as "functions") prompts the user of the new name and will then insert that name into the paragraph to update.

 

It would stop working if you reversed the first two lines of code; instead, you would see a TypeError: para is an undefined problem message in the browser developer console. 

 

It means that the para object has yet to exist over here. Thus, we cannot add an event listener to it.

 

How do you incorporate JavaScript into your website?

 

JavaScript is added to your HTML page in the same way that CSS is. Whereas CSS employs link> elements to apply external stylesheets and style> elements to apply internal stylesheets to HTML, JavaScript only has one HTML buddy — the script> element. 

 

1.     Internal JavaScript

 

  • Firstly, make a local copy of our example file apply-javascript.html first. Save it in an appropriate directory.

  • Open the file in both your web browser and a text editor. You'll notice that the HTML generates a simple web page with a clickable button.

  • Next, open your text editor and type the following directly before your closing /head> tag:

 

<script>

  // JavaScript goes here

</script>

 

  • To make the page more interesting, we'll add some JavaScript inside our script> element. You can add the following code below the "// JavaScript goes here" line:

 

document.addEventListener("DOMContentLoaded", () => {
  function createParagraph() {
    const para = document.createElement("p");
   
para.textContent = "You clicked the button!";
   
document.body.appendChild(para);
  }
 
  const buttons = document.querySelectorAll("button");
 
  for (const button of buttons) {
   
button.addEventListener("click", createParagraph);
  }
});

 

  • Save your file and restart your browser; when you click the button, a new paragraph should be generated and inserted below.

 

Note: If your example does not appear to function, repeat the instructions and ensure you did everything correctly. Always ask this question Did you save your local copy of the initial code as a.html file? Did you put your script> element before the /head> tag? Did you input the JavaScript exactly as shown? JavaScript is case-sensitive and finicky, so you must input the syntax precisely as stated; otherwise, it will not work.

 

2.     External JavaScript

 

This is fine, but what if we wanted to put our JavaScript in a separate file? Let's look into it now.

 

  • First, make a new file in the same directory as your sample HTML file. Call it script.js, and make sure it includes the.js filename extension, as it is how JavaScript is recognized.

  • Replace your existing script> element with the following.

 

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

 

  • Add the following script to script.js:

 
function createParagraph() {
  const para = document.createElement("p");
 
para.textContent = "You clicked the button!";
 
document.body.appendChild(para);
}
 
const buttons = document.querySelectorAll("button");
 
for (const button of buttons) {
 
button.addEventListener("click", createParagraph);
}

 

  • You will notice and see the same thing if you save and refresh your browser! It works the same as earlier, but now we have our JavaScript in an external file. This is a valuable idea for organizing and reusing your code across multiple HTML files. Furthermore, the HTML is easier to read without large amounts of script.

 

Comments in JavaScript

 

As with HTML and CSS, you can insert comments into your JavaScript code that the browser will ignore and serve to inform your fellow developers (and you if you come back to your code after six months and can't remember what you did). Comments are essential and should be used frequently, especially in more extensive programs. There are two varieties:

 

  • After a double forward slash (//), a single-line comment is written, e.g.

 

// It is a single-line comment

 

  • Between the strings /* and */, a multi-line comment, e.g.

 

/*

  It is a multi-line

  comment

*/

 

So, for example, we could annotate the JavaScript in our previous sample as follows:

 

//Function: adds a new paragraph at the bottom of your HTML body
 
function createParagraph() {
  const para = document.createElement("p");
  para.textContent = "You clicked the button!";
 
document.body.appendChild(para);
}
 
/*
  1. Gather references in an array format for each button on the page.
  2. After looping through all the buttons, give each one a click event listener.
 
  The createParagraph() Function will be run when any button is pressed.
*/
 
const buttons = document.querySelectorAll("button");
 
for (const button of buttons) {
 
button.addEventListener("click", createParagraph);
}

 

In general, more comments are preferable to fewer comments, but be cautious if you find yourself adding many comments to describe what variables are (your variable names should be more intuitive) or clarify relatively simple actions (your code may be overcomplicated).

 

Conclusion

 

That concludes your introduction to the world of JavaScript. We started out with only theory to get you accustomed to using JavaScript and the types of things you can accomplish with it. Along the way, you saw and understood a few code samples and discovered how, among other things, JavaScript integrates with the rest of the code on your website.

 

JavaScript could appear intimidating at this time, but don't worry; in this course, we'll walk you through it in straightforward steps that will make sense afterward.

 

 

 

 

 

13 views

Recent Posts

See All
bottom of page