JavaScript: A Wonderful Language for a Beginner
Tags: beginners, html, javascript
Published: 2021-08-22 22:24:48

Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. It is the programming language of the web, having various applications. Over 97% of websites use it client-side for web page behaviour. All major web browsers have a dedicated JavaScript engine to execute the JavaScript code on the user's device.

JavaScript is an easy language to learn and use. It does not require a lot on initial setup. What you need to deploy applications are a major web browser and an editor. I see JavaScript as an excellent language for a beginner to learn programming with. Hopefully, at the end of the article, you would agree with me.

##Brief History

JavaScript was introduced about 26 years ago. It was officially released on December 4, 1995. It was developed by Brendan Eich.

In the early days of the web, web pages were only static. They lacked dynamic behaviour once loaded. Netscape, the company that owned Netscape Navigator – the most widely used web browser at that time – decided to add a scripting language that would allow dynamic content to be served to their browser and Eich was hired.

A common misconception is JavaScript and Java are directly related but that is not so. The idea behind the name JavaScript has been seen to be a marketing strategy by Netscape to make their new language gain popularity as Java as the new programming language making great headway at that time.

##Features of JavaScript

One of the features of JavaScript is it is a multi-paradigm language. This makes it very flexible and easy to use. Instructions can be written in different styles and they would still run as expected. For a beginner, this can be viewed as a haven. You would not have to bother about the structure of code, just follow the basic rules of the language and it would be alright.

This “loose” nature of JavaScript makes it very beginner-friendly. It is not required that you end each line of code with a semi-colon. You can omit it and the code will function properly. It is not required but it is recommended you end lines of instructions with a semi-colon. Many programming languages end their instructions with a semi-colon, it is a good way to train yourself to do so. You can also write two or more instructions on the same line of code and it would not throw any errors. When doing this, you would need to end each separate instruction with a semi-colon.

These lines of code
```
let sum = 4 + 5
console.log(sum)
```
and these lines
```
let sum = 4 + 5;
console.log(sum);
```
would both give the same expected output with no errors. Also, writing
```
let sum = 4 + 5; console.log(sum);
```
would work just fine too.

Typing is not strict in JavaScript as a variable can hold various types of data throughout the execution of the program without throwing any exceptions. In other words, it supports dynamic typing. The various data types JavaScript supports are Strings (`“name”`, `“16 September”`, `“”`), Numbers (`1`, `17.557`, `31e12`), Arrays (`[“lord”, 16, [“award”]]`), Objects(`{name: “France”, capital: “Paris”}`), Booleans (`true` and `false`) and undefined.

JavaScript supports Object-Oriented Programming (OOP). You can create objects, assign them properties and methods and use these properties and methods in code to achieve certain tasks.

##Linking JavaScript to an HTML file

For you to visibly see the effects of the instructions you write in a JavaScript file, you should link it to an HTML document.
In an HTML document, JavaScript is written with the script tag.


![image of a script element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/www1p2xnihmdqy66zwq7.png)

The script tag can be placed in the head or the body of the HTML document.

![placing the script element in the head element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sb1efs5jkyut6tnkqrid.png)
<figcaption>Screenshot of code showing Script tag in the Head Element</figcaption>


![placing the script element in the body element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xh35z5248ib9y4w066z9.png)
<figcaption>Screenshot of code showing Script tag in the Body Element</figcaption>

JavaScript files can be written in the HTML document as shown in the snippets above or they can be written in separate .js files and then linked to the HTML document. 

![placing the script element with the src attribute in the head element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gocm2zmal080dalpqwti.png)

![placing the script element with the src attribute in the body element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r757mkbi22sy29m14q08.png)

The linking can also be done absolutely by using the URL to the JavaScript as the value for the `src` attribute.

##What can JavaScript do?

As a programming language, JavaScript provides you with features other languages have. JavaScript supports different selection and looping constructs. When you have to run a particular block of code when a particular condition is met, you are making a selection. A selection statement checks a certain condition and allows for the execution of a block of code if the condition is met. Selection statements supported in JavaScript include the `if` statement, the `if … else` statement, the `if … else if` statement and the `switch` statement.

The `if` statement can be used when there is a block of code to be run if a certain situation is encountered. When the condition set is not met, it does not run the code and moves on with the program execution as intended. In natural language, this can be put as perform this action if this happens. For example, if you see a dog, shout dog.

![if statement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6g3cvdpzzwuh9xq52o4.png)
<figcaption>An if statement that outputs the value of the variable animal if it is equal to dog</figcaption>


The `if … else` statement in JavaScript allows you to state a certain condition to be passed and when the condition is passed, the code in the `if` block gets executed and the code in the `else` block is neglected. When the condition is not passed, the code in the `if` block is neglected and the code in the `else` block is executed. In natural language, you can put it as if this happens, perform this action, else, perform that action. For example, if a sports car passes, shout “a sports car”, else, shout “a normal car”.

![if … else statement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2gugs187u56a4ru0iid.png)
<figcaption>An if … else statement that checks if the type property of an object car is equal to "sports car"</figcaption>


The `if … else if` statement is similar to the `if … else` statement. The first condition is checked and if it passes, the code contained in that `if` block is executed and the code in the other blocks are neglected. If the first condition set does not pass, it checks the next condition. If the next condition passes, the code in its block is executed with the rest neglected and if it does not pass, it checks the next condition. It repeats this process till all conditions are checked. You can choose to give your `if … else if` statement an `else` block and the code contained in it will run when no initial conditions set are met. For example, listen to the scores the teacher calls out in class if the score is above 90 and below or equal to 100, write A, else if the score is above 80 and below 91, write B, else if the score is above 70 and below 81, write C, else write F.

![if … else if statement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9g46iu98pto44o8mgxd.png)
<figcaption>The if … else if statement for the example stated above</figcaption>


The `switch` statement works like the `if … else if` statement but here, a condition, usually an expression, is given and then different `cases` of expected outputs are provided. Each case having instructions that are to be executed if the output matches it. Switch statements usually have a `default` case that gets executed when the other cases are not matched. At the end of each case, a `break` statement is written, this ensures other cases do not get checked after a case has been matched. It “breaks” out of the selection construct once a case is matched. For example, if we are to read input from a user and display different content based on the user's input, a switch statement is a good fit.

![switch statement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jj2cnwi82jcu57xp1439.png)
<figcaption>A switch statement that displays an ouput message based off a user's input</figcaption>


In a `switch` statement, you can merge two or more cases if they will all execute the same block of code if any of them gets matched.

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. Loops are handy, if you want to run the same code over and over again, each time with a different value. They help you reduce writing unnecessary lines of code and help you stick to the DRY (Don’t Repeat Yourself) principle.

Let us take into consideration the code below

![repeated code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clcy9ktl170e0eei01pd.png)

Here, I was trying to extract all the elements of the cars array and store them in a carList variable. The cars array has 6 elements so it was easy to write this out. Now, let us imagine that the cars array had 100 elements, writing this out, line by line would take a couple of minutes. Now, say I have to fetch this array from an API where all the names of all cars in the world were stored and the total number of elements in the array is over 10,000. You would agree with me that writing it out line by line would be burdensome and time-consuming. 

Another case is if I do not know the total number of elements in the array. I would not know where to stop indexing at. So, we need a way to extract all the elements without undue stress and uncertainty. This is where a loop comes in.

Loops are meant to terminate, hence, a condition or limit is put and when the condition for the running of the loop is met, the loop terminates. If the condition is wrongly set that it would never be met or is omitted totally, the loop will run infinitely and this can cause problems for your program. When using loops, be careful to set a condition that will ensure the loop will terminate when it has run for the number of times it is expected to run for. Loops supported in JavaScript are for loop, for … in loop, for … of loop, while loop and do … while loop. These loops mostly do the same thing but differ in syntax and implementation.

The for loop has this syntax 

```
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
```

Statement 1 is used to initialise the variables used in the loop, statement 2 is the condition at which when met, the loop terminates and statement 3 is used to increment or decrement the value of the initial variable initialised. For loops can be used to loop through arrays, strings, node lists and so on. Let us use a for loop to solve the problem we ran into earlier.

![for loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd0rxjdr4vxaevbrgm28.png) 


The for … in loop in JavaScript loops through the properties of an Object. It is written like this 

```
for (key in object) {
  // code block to be executed
}
```

The for … in loop iterates over the object. Each iteration returns a key. The key is used to access the value of the key. The value of the key is object[key]. The value can then be used as the programmer wishes.

![for … in loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fcbim36kb7kw6bskr1zy.png)
</figcaption>A screenshot of a for … in loop that iterates over an object</figcaption>


The for … of loop loops through the values of an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, Node Lists and so on. 

```
for (variable of iterable) {
  // code block to be executed
}
```

For every iteration of the iterable, the value of the next property is assigned to the variable. The iterable is an object that has iterable properties.

![for … of loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ir989kenlpqf9jsabzw1.png)
<figcaption>A screenshot of a for … of loop that loops through the values of an array</figcaption>

The while loop loops through a block of code as long as a specified condition is true.

```
while (condition) {
  // code block to be executed
}
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr4y5bl51cn0p73btgae.png)

If you forget to increase or decrease the variable used in the condition, the loop will never end. This will crash your browser.

The do-while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9j7s2xfuh9hmqcf740st.png)

In a while loop, it is possible for the while block of code not to run, that is, when the condition is not met, but in the do … while loop, the do block of code would run, at least once because the condition is checked after the execution of the do block.

Furthermore, JavaScript is an event-driven and functional programming language. With this, it is widely used for HTML DOM manipulation. The Document Object Model (DOM) is the data representation of the objects (elements) that comprise the structure and content of a document on the web. The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory.

With JavaScript, HTML elements are accessed through the DOM and can be edited. HTML elements’ contents can be changed with JavaScript. Their attributes can be changed also, styles applied to those elements can be edited and even the display and visibility status of the elements can be controlled with JavaScript. JavaScript can add more elements to the DOM and also remove existing elements from the DOM. The DOM is not a programming language but just a representation of a web page. The DOM can be accessed by calling the document object and using the available methods to manipulate the element(s).

![DOM methods for accessing html elements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/is3d819j5rl1axd47hpt.png)
<figcaption>DOM methods for accessing elements in the DOM</figcaption>


The manipulations to the DOM with JavaScript are usually event triggered. Various HTML events can occur in the course of viewing a web page. As you would guess, JavaScript employs the use of event listeners to detect when these events happen. These event listeners have provisions for functions to be executed when the event they listen for has occurred. Events can be grouped into different categories. Examples of common events are click event, dblclick (double click) event, mousedown event, mouseenter event, mouseleave event, drag event, play event, ended event, etc.

![Adding a click event listener to an element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8p8m8ohdy92y7espnmh.png)
<figcaption>Adding a click event listener to an element</figcaption>

In addition, JavaScript provides a lot of functions and methods that allow you to control and handle audio and video files. At the occurrence of certain events or completion of functions, you can play your audio and video. Some people take advantage of this and create their custom audio and video player as built-in players by browsers that might have limited functions. When designing a custom media player, HTML and CSS comes in also. Common audio and video methods you can take advantage of in JavaScript are load(), play() and pause() and common events associated with audio and video are ended event, play event, timeupdate event, volumechange event and so on.

![common audio events](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7l0qjrfcka2i5g4hpbn.png)


It is also vital to note that JavaScript can connect to web servers, get information from them and also post information to them. This can be done asynchronously using AJAX (Asynchronous JavaScript And XML). AJAX is not a programming language. With AJAX, you can update a web page without reloading the page and send data to a web server - in the background.

##Applications of JavaScript

JavaScript has grown over the years. It was initially created for making web pages dynamic and now, we see it used in different aspects like server-side scripting and even hybrid application development.

JavaScript is applied in front-end development. With the development of various frameworks and libraries, front-end development is easier and also more powerful as these frameworks and libraries give you the platform to harness the full power of JavaScript in your web application stress-free.

JavaScript can be used in server-side scripting though it was originally meant for front-end web development. [Node.Js] (https://nodejs.org/) is an open-source development environment that allows you to run JavaScript on a server. This is helpful for front-end developers with JavaScript knowledge as they can write server-side scripts in JavaScript and it would run efficiently. There is no need to learn another language.

Writing JavaScript for the server-side is possible, also writing JavaScript for mobile applications and desktop applications is also possible. [Apache Cordova] (https://cordova.apache.org/) is a free mobile application development framework that allows you to develop an application in HTML/JavaScript and then it wraps it into a native container that can access the device functions of several platforms and hence enables the web app to work on mobile devices. [Electron] (https://www.electronjs.org/) is a free and open-source framework for creating native desktop applications with web technologies. It allows building cross-platform desktop apps with JavaScript, HTML, and CSS. There are other examples of such development frameworks that exist like [Ionic] (https://ionicframework.com/) and [NativeScript] (https://nativescript.org/).