JavaScript

What is JavaScript? – Beginners Guide

For web developers, HTML and CSS were there to display content on the website and make it look aesthetically pleasing. But, they were unable to handle the interactivity of the web pages. For this purpose, another language was required, specifically to handle the programming aspect of your website. So that it could handle your website’s dynamic and interactive behavior.

Hence came JavaScript. It’s one of the most popular scripting languages that work on the client-side to handle the interactivity of your web page. Furthermore, it can increase the dynamic behavior of the website by manipulating the content it receives from the web server. There is a whole bunch of stuff that JavaScript can do, we’ll learn it in this article along with how it works and some basic concepts.

Various Functions that You Can Do With JavaScript:

  • Modify web page content by adding and removing the elements.
  • Monitor various mouse clicks, hover events and handle their actions.
  • Control various animations and transitions.
  • Event handling when a user enters some input.
  • Validate the input that the user provides before submitting to the server.

And so many more, You can control how your page behaves.

Why learn JavaScript?

JavaScript was considered to be a tool only for interactive web pages. But those days are gone, and now you can build full mobile and web applications as well as networking applications using various frameworks provided by JavaScript.

You can also design browser games with JavaScript. It is out-growing other languages and famous companies are building their applications around JavaScript. Now, you know the importance of learning JavaScript so let’s see how it works.

JavaScript Code Editor

For JavaScript code, you can use the browser’s console or even online JS editors. But, it’s best to use code editors. There are various code editors out there like Visual Studio Code, Sublime Text, Atom, and more You can check various JavaScript editors available through this article. Out of these, Visual Studio Code is highly recommended as it is the most commonly used Code Editor, and the reasoning behind that is its constant support for upcoming technologies and Easy-to-use User interface.

How to add JavaScript to your file?

There are two ways of adding JavaScript to your HTML file:

Internal Script (Configuring JavaScript inside HTML file using <script></script>tag)

<script>


let con;

con = Boolean('');

console.log(con)    
     
</script>

External Script (Creating a seperate file for JS code and adding the link in the tag <script src =?></script>

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

consol.log, alerts, and document.write in JavaScript

A useful command to debug and log your code is console.log. It’s useful indirectly writing content in the web console.

console.log("Hello World");

Alerts are used to provide alerts to the end-user who is accessing the web page.

alert("Hello World");

Document.write modifies the content on the web page by adding additional content to your web page.

document.write("Welcome to the Web Page!");

In JavaScript, the console has a bunch of methods. More in-detail information is here.

How to add comments in JavaScript

While programming, writing comments are extremely useful. It helps you remember what you coded and if there is any extra information you need to write for the other person who’s checking your code. Both single and multiple line comments can be written. To use a single-line comment in code (JavaScript) we use //:

// This whole sentence is one big single-line comment.

Whereas, in the case of multiple line comment use /* in the begging and close it using */:

/* This is a multi-line comment. You can even your blog here if you want to. */

Variables in JavaScript

Just like in any other programming language, variables are also used in JavaScript. The job of a variable is to hold a data type in a named reference. In JavaScript we can set variables using three ways: var, let, const.

The var is used since the beginning of JavaScript and it’s globally scoped, which means that all the functions on that page, or in that program can access it.

var x = 15;

var y = 4;

console.log(x + y);

Output:

Because it is globally scoped, it’s better to use let and const. The reason is that sometimes you want to declare a variable in an if statement, and outside that if statement you want to declare the variable with the same name. Using var will cause problems. To understand more about global variables in JavaScript, you can check this article.

The Remaining two types of variables that are available in JavaScript are let and const. Using let we can declare any data type, whereas, in the case of const, only constant values are declared.

let msg= "Hello World";

console.log(msg);

msg= 10;

console.log(msg);

Output:

Here, we declared a string as well as a number data type using the let variable. Now, using const, if we try to declare any value other than constant, it’ll give us an error.

// Below will cause an error.

const pi = 3.142;

console.log(pi);

pi = 3.15;

console.log(pi);

Data Types in JavaScript

JavaScript provides us with various data types such as Numbers, Strings, Booleans, Float, Objects, and more. If you want to read about the Data Types in JavaScript then you can head over to the official MDN Docs. It tells the program what type of data they’re working with and manipulating.

Number: The data type to represent a positive, negative integer or floating-point is Number.

let num = 11;

console.log(num);

console.log(typeof num);

num = -12;

console.log(num);

console.log(typeof num);

Output:

String: To store a sequence of characters, the String data type is used.

let x = "Welcome"

console.log(x);

console.log(typeof x);

Output:

Boolean: A data type that represents true and false values in a program.

let x = true

console.log(x);

console.log(typeof x);

Output:

Objects: To store the collection of various data types in a single variable, Objects are used.

let movie = {

    name : "Inception",

    genre: "Thriller",

    yearOfRelease : "2010",

    numberOfCopies : 10

   
};

console.log(movie);

console.log(type of movie);

Output:

Arrays in JavaScript

To store the collection of data of any type we can use Arrays. Simply initialize the array using the array constructor:

let months = new Array();

Or with [ ] initialization:

let months = [];

Or simply create an Array with explicit data:

let months = ["January", "February", "March", "April", "May"];

The index in Array starts with zero, and to access any element you simply have to write array[indexPosition]:

let months = ["January", "February", "March", "April", "May"];

console.log(months[3]);

Output:

To better understand the Array concept in JavaScript, check this article.

Methods for Different Data Types in JavaScript

Various methods are out there to manipulate the values of various data types.

String Methods: To modify the values of a String, there are numerous different methods available to us. These can be used to check the length of a string, find the position of a certain word in a string or convert it into different data types.

let x = "Hello, Welcome Home"

//To check string length

console.log(x.length);

//To cut a specific part of string

console.log(x.slice(3, 7));

//To replace a specific word in a string

console.log(x.replace("Home","Here"));

//To convert string to Lowercase letters

console.log(x.toLowerCase());

Output:

Of Course, there are several other methods, if you want to learn more check this article as well.

Number Methods: Similarly for manipulating the value of a Number data type, there are various methods. Some of these are provided below:

let x = 4445.4

//To convert numbers to a string

console.log(x.toString);

//To convert number to its exponential form console.log(x.toExponential());

//Returns the number with specified length

console.log(x.toPrecision(2));

Output:

Javascript provides us with methods for objects, boolean, arrays, and more.

Conditions in JavaScript

Another fundamental part of programming is to make decisions and cause some actions based on these decisions. This can be done through conditional statements in JavaScript. You can use:

If..else:

let balance = 1200;

if(balance < 1000)

{

    console.log("Balance less than 1000");

}

else

{

        console.log("Balance more than 1000");

}

Output:

If.. else if…else:

let balance = 1200;

if(balance <1000)

{   console.log("Balance less than 1000");  }

else if(balance >1000 && balance <1500)

{ console.log("Balance between 1000-1500");  }

else { console.log("Balance more than 1500"); }

Output:

Switch:

let alphabet = 'B';

switch(alphabet)

{

    case 'A':

        console.log("Egg");

        break;

    case 'B':

        console.log("Mango");

        break;

   
    default:

        console.log("Tea!");

}

Output:

To understand the topic better you can check these articles of if-else and switch conditional statements in detail.

Loops in JavaScript

Until a certain condition is met. Loops keep repeating a chunk of code (could be a single-line and even multiple-line) JavaScript provides for, while, do-while, and for each loop. Here is how they work along with examples:

For Loop

It loops through a given code several times.

for(let i=0; i < 10; i++)

{

    console.log(i + " ");

}

Output:

You can understand the concept and work of this through this article.

While Loop

Loops through a specified given code until the given conditions are met.

let i = 0;

while( i <4 )

{

    console.log(i + " ");

    i++;

}

Output:

Do While Loop

Similar to the while loop, there is a do-while loop. It differs in this aspect that here at least the loop will be executed once. The reason is that the conditions are checked at the end of the loop.

let i = 0;

do

{

    console.log(i + " ");

    i++;

}while(i < 3);

Output:

Output:

For Each Loop

To iterate over a collection like Arrays, for each loop is used.

let letter = ["m", "a", "n", "g", "o"];
letter.forEach(

    function(entry)

    {

        console.log(entry + " ");

    }

);

Output:

This is just to give you a basic understanding. If you want to understand this in-depth, check this article, or to understand the for-in loop you can check this article as well.

Functions in JavaScript

Functions are blocks of code that are assigned to perform some task. For example, you want a message to display when you click a button. So this will happen through the use of functions. To understand the concept in detail you can check this article.

Here’s a demonstration of how it works:

function addition(i, j=5)

{

    return i + j;

}


let result = addition(3,5);

console.log("add(3,5) is " + result);

Output:

In the above example, two numbers were passed into the function of addition() and were stored in the variable result.

JavaScript provides us with various data types, functions, methods, and more in-depth. These are extremely useful and make the understanding of the program easy. There are so many ways you can learn JavaScript, Through books, as well as through online resources.

Conclusion:

In today’s guide, we learned the basics of JavaScript. JavaScript has become nothing less than essential for interactive, and attractive web pages. Nowadays, JavaScript provides us with various frameworks that even help us in developing web and mobile applications. Developers are also creating browser games using JavaScript.

With the increase in demand for JavaScript, the resources to learn the language are also increasing. You can learn it through online tutorials, courses, or even through books. But, no matter what your medium of learning is, the only thing that makes you an expert is practicing.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.