JavaScript – An Introduction to JavaScript

JavaScript – An Introduction to JavaScript

What is JavaScript?


A small, interpreted, or just-in-time compiled programming language containing first-class functions is called JavaScript (JS). Many non-browser contexts, like Node.js, Apache CouchDB, and Adobe Acrobat, employ it even though it is best recognized as the scripting language for Web pages. JavaScript is a dynamic, prototype-based language that supports object-oriented, declarative (like functional programming), and imperative programming paradigms. Study up on JavaScript.

You may have been aware that JavaScript is widely used in the field of software development today. The main component of frameworks like ReactJS, Angular, and VueJS, it serves as the cornerstone of front-end web development. Additionally, it may be used to build reliable backends using platforms like Node.js, run desktop programs like Slack, Atom, and Spotify, and function as Progressive Web Apps on mobile devices (PWAs).

In other words, it’s prevalent everywhere for good reasons. For starters, learning JavaScript is often simpler than learning other languages like C and Java. When we use the word “easier,” we’re referring to how rapidly you can advance from a JavaScript beginner to a coder who can genuinely support themselves by producing professional-level JavaScript. Therefore, it is more approachable than some other languages like C and Java in that regard.

Additionally, JavaScript is an enjoyable and rewarding language, which is crucial when you’re just starting out in software development. If you run into trouble, there’s a significant possibility that the issue and a solution are already documented online thanks to the excellent community assistance.


After getting a high-level overview of JavaScript, let’s move on to more specific technical information. JavaScript was developed to give websites “life.” JavaScript is written in plain text files with the.js extension, just like HTML and CSS.

As was already noted, JavaScript may be used to carry out a variety of helpful tasks on the frontend, like alerting users, validating forms, doing computations, and storing temporary data, to name a few.

Advice: JavaScript and Java have nothing to do with each other, other than the name. Beginners frequently mix up the two languages. Although it still runs on some website backends, keep in mind that Java is a whole separate language designed for a different purpose.

Finally, before we look at the schedule for today, keep in mind that JavaScript is a large language, much like HTML and CSS (maybe even more so). We’ll only cover the portions of it that are pertinent to our lives right now, but if you’re interested in learning more, we’ll provide some excellent resources at the end.

Basics of JavaScript

  1. Basics of JavaScript

As with most programming languages, JavaScript has several fundamental building blocks that we’ll examine. In JavaScript, a program is similar to a series of actions. Similar to how humans would offer directions to a stranger, a computer requires thorough instructions, expressed as stages, to carry out any task, no matter how straightforward or difficult.

Let’s start by going over some fundamentals.

Scripting in Java

The portfolio directory will now contain a new file called “script.js” for writing JavaScript, much like we did for CSS. Open the index.html file now, and add this line just before the closing body tag ().

That’s all. View code modifications on GitHub. Our HTML includes a link to our script file. Write the following code into your script.js file to make sure it functions.

Save the page, and then reload it.

View modifications to the code on GitHub

A dialog window can be seen at the top. Your alert code’s first line of JavaScript is currently running. Change the text and then try refreshing. That is also possible in the CodePen below!

The script file has been appropriately set up if you followed the instructions in the previous section. Let’s start writing some JavaScript now! Let’s take a closer look at a few key ideas.


Variables are descriptive names for data storage. Consider how you address people by name as opposed to using generic terms like “human” or “one head, two eyes, one nose…,” etc. Simply put, variables are just descriptive labels for data elements that are also user-friendly. Let’s look at an illustration.

Here, we’re creating a greeting variable and giving it the value “Hello world.” See how it almost sounds English: “let greeting be Hello world”? Now, a greeting can be used in place of the literal word “Hello world” because it contains the value “Hello world” in it.

You might type:

The outcome should remain the same if you refresh the page. Variables are incredibly helpful for storing data in the real world, despite the fact that it may appear like we are doing more work to get the same outcome. Additionally, many forms of data, including strings, numbers, and other variables, can be stored in variables.

Have you noticed that the word “let” came before the variable name? In JavaScript, you can declare a variable in one of several ways.

Observe how each line is punctuated with a semicolon (;). Although not strictly necessary (save in a few limited circumstances), using them is best practice, thus we advise you to do so.

Calculus Operators

JavaScript functions as a calculator as well. In truth, a lot of the code you’ll encounter in the real world will be filled with elementary computations. It is compatible with all common operations, such as plus (+), minus (-), multiply (*), division (/), and so forth. You might try the following, and as you might anticipate, it would output “5”. You should see a popup appear in the active browser window if you try running the CodePen below.

The results might then be stored in a different variable after the values were stored in their respective variables.

Run it again; did you receive 5 this time? No? Go to the Console tab in the Chrome Developer Tools. Does it make a statement?

Ah, line 4 of the script.js file contains a mistake (notice the script.js:4 on the right corner of that red error message). Have you noticed the mistake on line 4? The alert is the one that lacks the final parenthesis. Correct it, then try running your code once more.

Operators for Comparison Comparison operators compare two items jointly. We frequently ask questions like “Is it warmer today than yesterday?” or “Are these two buildings the same size?” in English and other languages. These questions typically compare two objects, and the response is either yes or no (today vs yesterday, building 1 vs building 2, etc). In terms of programming, it is either “true” or “false.” Such inquiries are also possible with JavaScript! We have the following comparison operators in JavaScript:

Operator Question in asks
=== Are the two things equal?*
!== Are the two things unequal?*
>= Is the first thing greater than or equal to the second?
<= Is the first thing less than or equal to the second?
> Is the first thing greater than the second?
< Is the first thing less than the second?

*Less restrictive versions of these include == and! =, which make it possible to compare items that might not be of the same type.

“1” === 1 is false because it is a string instead of a number, but “1” === 1 is true.

We advise against using == and!, and to stick to strict equal/not equal (=== and!==).



Blocks of code that have names assigned to them so that we can reuse them are called functions. Let’s say that adding two integers is a frequent task on our website. The code mentioned above can be placed inside a function.

Watch how the function accepts two numbers (number1 and number2, officially referred to as the function’s parameters), adds them, and then “returns” the result, or sends it back to you. Although the “add” function is defined here, it is not being used. We must ‘call’ this code in order to use it. A function is called by simply writing its name and the “arguments” in parentheses (actual parameters).

Take yet another illustration. Think of a function that “alerts” anything that is sent to it.

There is no return value in this function, which has the name alertMessage and the parameter message (notice the missing return statement).

The function’s argument is the part that starts with “Hello World” when we call it alertMessage(“Hello World”) In terms of functions, this is merely the top of the iceberg, but it is sufficient to get us started.

You’d be fair to claim that repeating what we mentioned about variables makes this feel like more work to accomplish the same task. This will assist us in getting ready for more than just multiplying two integers together, though.

Flow Management

A JavaScript program typically runs line by line. However, there are times when we want to execute a statement depending on a condition or repeat a set of statements. Changing the sequence in which code runs is referred to as flow control.

It will be clearer with an example. Suppose you want to display different messages to your users based on whether or not they are 18 or older. Your reasoning would sound like this in plain English:

You’re not an adult if you’re under the age of 18, else, you are.

You would write the code as follows in JavaScript:

Take note of how similar the JavaScript code and the plain English translation are. An if..else statement is what we just demonstrated. Take note of the 18-section. That is the circumstance. The less-than operator from the comparison operators section was utilized in this case.

If..general else’s syntax is as follows:

Every time we need to make a decision in the code, such as verifying that the users have input the correct data, we’ll utilize the if..else construct.

Objects The JavaScript object is the final crucial idea we require for our website. Simple key-value pair containers, like those in a dictionary, are what make up an object. In a dictionary, a word serves as the key, and its meaning serves as the value. A key is a name in a JavaScript object, and a value could potentially be another object. Let’s examine an illustration:

FirstName and LastName are the keys, and John and Doe are the values, in our sample object, fullName. We can use the dot (.) notation to get the firstName. The alert “John” will be displayed as follows.

As was already explained, objects can include both other objects and functions.

This time, we can convey a warning by saying: Once we move on to the next part, you’ll see this pattern employed all over again.

  1. Choosing HTML components

The ability of JavaScript to choose and alter HTML code is what gives it power on the web. For instance, we might create a JavaScript code that runs whenever the “submit” button in our footer form is clicked.

Let’s choose our submit button and add a “click listener” function to it first to accomplish that. When a button is clicked, an element to which a click listener has been attached will call the listener function.

In our HTML file, we will assign our button an ID property with a specific ID so that it may be selected.

Now that we have an ID to choose from, let’s head over to our JavaScript program and select our element using the document.querySelector() JavaScript function. Using this function, we may pick HTML components in JavaScript the same way we can in CSS: by their names, class attributes, or IDs.

The HTML element that matched the selector is returned as an Object by the function document.querySelector, which accepts the selector as an argument (remember that Objects are just containers for key-value pairs of data). The HTML element can then be saved in a variable and used for a variety of actions.

Just like when you pick IDs in CSS, the ID must be preceded by the pound sign (#). If it were a class name, you would use a period (. ), for example, submit button.

Try fiddling around with the development tools in general. It takes some practice, but once you get the hang of it, “debugging” (the process of determining what went wrong) is simpler.

  1. Incorporating a “click” listener

Let’s add a click listener function to the HTML element we’ve chosen and placed in a JavaScript variable. As implied by the name, a click listener watches or waits for a click. We add click listeners to specific items that are relevant to us, such as form submit buttons.

The click listener function is triggered when the specified HTML element is clicked.

You’ll see that the addEventListener() function accepts the click listener function as an argument, which is exactly like any other function. This is because JavaScript allows and encourages the passing of functions as arguments to other functions.

But in order to make sure the code above runs correctly, we must make some changes to it before we try to run this.

Attempt running the CodePen snippet as well. The Developer Console will then open in the same window that you are reading this course in once you click the “Send Message” button. The console should display the text Button clicked.

In essence, we use the event parameter provided to our function, which holds the click event details (such as what was clicked, button characteristics, etc.), to stop the form from refreshing the page ()

Reload and save. Click the button once in the Developer Tools, Console tab.

The next step is to use JavaScript to retrieve the values entered into the form.

  1. Obtaining values entered by the user

Our website has a form, but we haven’t discussed how we’ll extract the data a user might enter there.

In order to make any form “work,” we typically get the data—in this case, text—from the form’s inputs, textareas, and other form elements into JavaScript variables before sending it to the server. Many developers like to perform optional validations (i.e., checks) on the data before submitting it to the server. The format of the entered email could be checked as an example of validation.

Keep the document in mind.

We used the querySelector in the earlier section. It was used to choose HTML elements. We may use the same document because form inputs are nothing more than HTML elements and the data that a user may enter in those inputs is stored inside of the HTML elements. choose our HTML components using querySelector.

Then, we require knowledge of a critical fact. The ‘value’ key provides access to the data included in an HTML input’s value. Recall the objects? The ‘value’ key of the HTML input element object will store the text that is currently present in the element.

We will then offer comfort.

Check the emailText and messageText variables after logging the values from the input and textarea.

  1. JavaScript checks for errors

You probably noticed anything strange in the preceding section if you fiddled around a little. Despite the fact that the input fields for email and message state such things, you can pretty much type anything and have it accept it and print it.

You can even insert a message and email address that are both empty. That is not ideal. We’ll need to impose some limitations on what users can enter, particularly in the email area. For our purposes, it will be sufficient to see if the text typed in the email field has a “@” symbol. You’ll want to perform more thorough tests on the data in the real world.

We must create a validation function in order to validate emails. Checks are part of the validation, as was indicated in the section above. They could be verifications that the data is in the expected format, filters to remove any offensive terms from the text, or anything else. They provide a quick means of informing users about any mistakes they may have made when submitting their data.

In our example of validating email addresses, our check for “@” may capture cases in which users accidentally omit “@” or enter incorrect email addresses.

This function determines whether the character “@” is present in the supplied text argument email. The “if” and “else” you see are examples of a conditional, which is what is being used.

It can be understood as if true, it returns true. Otherwise, false is returned. Let’s test it by logging it into the console in our clickListener method.

I see; it works! Although it isn’t flawless, it does show how expressive JavaScript is. Now that everything is put together, we can display the proper message inside of our clickListener method.

Try it in CodePen and check the outcomes in the Developer Tools console of your browser.

Here, we start by looking at the email. We record the error message and return false if it fails (which is one way of preventing further execution of a function, meaning that our last console.log will not be executed).

We presume everything went according to plan and output a success message if the “if” block is not executed, which means a return false wasn’t encountered and the function is still running. Really lovely, huh?


Congratulations! Your brief course in web building is now complete. It’s been a very exciting few days, and we hope you’ve enjoyed this little adventure as much as we have.

We began by configuring your developer environment and entering our initial lines of code there. After that, we added HTML, data, and CSS to it. The page was then further enhanced with CSS. Finally, we added some JavaScript wizardry to finish it off and brought the page to life. We applaud you for persevering through to the end and wish you the best of luck on your fantastic web development journey.