Introduction to JavaScript: Basics

Introduction to JavaScript: Basics

·

10 min read

Hello, amazing people 👋,
In this blog article, I am going to explain the basics of javascript.

Let's get started.

This Blog post will cover:

- What is JavaScript?
- How JavaScript is different from other programming languages like
 Java or C?
- How to include JavaScript in your HTML page?
- How to Write Comments in JavaScript?
- Variables in JavaScript
- Data types in JavaScript
- Operators in JavaScript
- Conditional Statements in JS
- Loops in JavaScript
- Functions in JavaScript

Prerequisites

Before starting this article, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS.

What is JavaScript?

JavaScript is a scripting language used to create and control dynamic web content. It is an interpreted, lightweight object-oriented programming language that enables dynamic interactivity on websites. It can be anything from animated graphics to an automatically generated Facebook timeline. Once you have created your basic structure(HTML) and elegant vibe(CSS), JavaScript makes your website dynamic(automatically updateable).

If you are a software developer gravitated towards web development then you must learn javascript and once you have learned JavaScript there are many frameworks available which you can use to create multiple web applications. Nowadays javascript is also used in mobile app development, desktop app development, and game development. This opens many possibilities for you as a JavaScript developer.

How JavaScript is different from other programming languages like Java or C++?

The major difference is that JavaScript is a scripting language i.e it is not compiled and executed like C++ and java. It is dynamically typed whereas Java or C++ is statically typed. JavaScript is traditionally used to write scripts for web applications. The client receives the whole source of the script and the browser executes it - the browser has a JavaScript interpreter while the browser couldn't execute Java or C++ programs. Javascript does not support multithreading while java or C++ is a multi-threaded language.

Now, javascript can run on the server via Node.js.

How to include JavaScript in your HTML page?

JavaScript can either be embedded directly inside the HTML page or placed in an external script file and referenced inside the HTML page. There are three places to put javascript code-

  • between head tag of HTML page
    Example-
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Embedding JavaScript</title>
      <script>
          document.getElementById("greet").innerHTML = "Hello World!";
      </script>
    </head>
    <body>
      <div id="greet"></div>
    </body>
    </html>
    
  • between body tag of HTML page
    Example
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Embedding JavaScript</title>
    </head>
    <body>
      <div id="greet"></div>
      <script>
          document.getElementById("greet").innerHTML = "Hello World!";
      </script>
    </body>
    </html>
    
  • In .js file(external javascript file)
    Example-
    index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Linking External JavaScript</title>
    </head>
    <body>
      <div id="greet"></div>
      <button onclick="greet()">Show message</button> 
      <script src="script.js"></script>
    </body>
    </html>
    
    script.js
    function greet()
    {
      document.getElementById("greet").innerHTML = "Hello World!";
    }
    

How to Write Comments in JavaScript?

Comments are a meaningful way to deliver messages. It is not necessary but recommended to use comments to add information about the code, warnings, or suggestions so that others can easily understand and interpret your code.

Types of comments in javascript

  • Single-line comment => Single-line comments are represented by double forward slashes (//).
    Example

    <script>  
    var x=1;  
    var y=2;  
    var z=x+y;              // It adds values of x and y variable  
    document.write(z);      // prints sum of x and y  
    </script>
    
  • Multi-line comment => It is represented by forward slash with an asterisk(/*) then asterisk with forward slash(*/).
    Example

    <script>
    /*
    The code below will change the heading with id = "myP" and the 
    paragraph with id = "myP" in my web page:
    */
    document.getElementById("myH").innerHTML = "My First Page";
    document.getElementById("myP").innerHTML = "My first paragraph.";
    </script>
    

Variables in JavaScript

Variable means anything that can vary. These are the containers for storing data values. Also, JavaScript variables are loosely typed which means it does not require a data type to be declared. There are some rules while declaring a variable in js:-
1.) variable name must starts letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2.) after the first letter we can use digits (0 to 9), for example- abc1
3.) javascript variables are case sensitive(x and X are different variables)

Example of JavaScript variables
Correct JavaScript variables=>

<script>
var x=10;
var _value=1.1;
var flag1=true;
var Name;               //declaration of variable
Name="neha";            //initialization of variable
</script>

Incorrect JavaScript variables=>

<script>
var  123=30;  
var *aa=320;  
</script>

There are two types of variables in javascript:

1.) Local variables
2.) Global Variables

JavaScript local variable =>

Local variables are the variables that are defined inside block or function. They have a local scope which means that they are accessible within the function or block.
Example-

<script>  
function fun()
{  
var x=10;    //local variable
console.log(x);   
}  
</script>

JavaScript global variable =>

Global variables are the variables that are defined outside the functions or declared with a window object. They can be accessed from any function.
Example-

<script>  
var data=200;     //global variable  
function a()
{  
console.log(data); 
}  
function b()
{  
console.log(data); 
}  
a();               //calling JavaScript function  
b();  
</script>

Data types in JavaScript

Data types basically specify what kind of data can be stored and manipulated within a program. JavaScript provides different data types to hold different types of values. In JS we don't need to specify the type of the variable because it is dynamically used by the JavaScript engine. Mainly there are two types of data types in javascript:-
1.) Primitive data types
2.) Non-Primitive data types

Primitive data types:-

Primitive data types can hold only one value at a time. There are five types of primitive data types in JS:-

Screenshot (197).png

Non-primitive data types:-

Non-primitive data types can hold collections of values and more complex entities. There are mainly three types of non-primitive data types:- Screenshot (182).png

Operators in JavaScript

Operators are special symbols used to perform operations on operands. For example,

var a=10,b=20;
var sum=a+b;

Here, the + operator that performs addition, and 'a' and 'b' are operands.

Screenshot (179).png

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic calculations. The arithmetic operators are as follows:-

Screenshot (184).png

JavaScript Assignment Operators

Assignment operators are used to assign values to variables. The following are assignment operators in js:-

Screenshot (185).png

JavaScript Comparison Operators

Comparison operators compare two values and return a boolean value, either true or false. The following are Comparison operators in js:-

Screenshot (187).png

JavaScript Bitwise Operators

Bitwise operators perform operations on binary representations of numbers. The bitwise operators are as follows:

Screenshot (188).png

JavaScript Logical Operators

Logical operators perform logical operations and return a boolean value, either true or false. The following are logical operators in js:-

Screenshot (190).png

Conditional Statements in JS

Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run.

JS if Statement

The most common type of conditional statement is the if-else statement. This statement only runs if the condition enclosed in parentheses () is true. There are three forms of if statement in JavaScript:-

  1. If Statement
  2. If else statement
  3. if else if statement
    If statement example
    <script>  
    var a=20;  
    if(a>=20)
    {  
       alert("value of a is greater and equal to 20");  
    }  
    </script>
    
    if-else statement example
    <script>  
    var a=20;  
    if(a>=20)
    {  
       alert("value of a is greater and equal to 20");  
    }  
    else
    {
       alert("value of a is less than 20"); 
    }
    </script>
    
    if-else if statement example
    <script>  
    var a=20;  
    if(a>20)
    {  
       alert("value of a is greater than 20");  
    }  
    else if(a==20)
    {
       alert("value of a is equal to 20");
    }
    else
    {
       alert("value of a is less than 20"); 
    }
    </script>
    

    JS switch Statement

    Switch statement is used to execute one code from multiple expressions. If there is a match, the associated block of code is executed and if there is no match, the default code block is executed.
    Example:-
    <script>  
    var grade='C';  
    var result;  
    switch(grade){  
      case 'A':  
        result="A Grade";  
        break;  
      case 'B':  
        result="B Grade";  
        break;  
     case 'C':  
       result="C Grade";  
       break;  
     default:  
       result="No Grade";  
    }  
    alert(result);  
    </script>
    

    Loops in JavaScript

    Loops are used for executing a block of statements repeatedly until a particular condition is satisfied. It makes the code compact. JavaScript supports different kinds of loops:
    1.) for loop
    2.) for-in loop
    3.) while loop
    4.) do-while loop

JS For loop

The for loop iterates the elements for the fixed number of times. Syntax of for loop is as follows:

for(initialization; condition; increment)
{
     //code block to be executed
}

Example:-

<script>
     for(i=0;I<10;i++)
     {
          document.write(i + " ")  
     }
</script>

Output:- 1 2 3 4 5 6 7 8 9

JS For-in loop

The for-in loop iterates through the properties of an Object. Syntax of for loop is as follows:

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

Example:-

<script>
var user = "";
var person = {fname:"Neha", lname:"Soni", age:20}; 
var x;
for (x in person) {
  user += person[x] + " ";
}
document.write(user);
</script>

Output:- Neha Soni 20

JS while loop

The while loop iterates through a block of code as long as a specified condition is true. Syntax of while loop is as follows:

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

Example:-

<script>  
var count=0;  
while (count<=5)  
{  
document.write(count + " ");  
count++;  
}  
</script>

Output:- 0 1 2 3 4 5

JS do-while loop

A do-while loop is similar to a while loop with one exception that the code is executed at least once whether condition is true or false. Syntax of do-while loop is as follows:-

do
{  
   //code to be executed  
}while (condition);

Example:-

<script>  
var i=1;  
do{  
document.write(i + "<br/>");  
i++;  
}while (i<=5);  
</script>

Output:-1 2 3 4 5

If you want to learn more about loops, Click here

Functions in JavaScript

Functions are one of the major pillars of JavaScript. It is a set of statements that performs some tasks or does some computation and then returns the result to the user. It helps you to divide a large program into small and makes a program a lot more efficient. The syntax of declaring a function is given below:-

function functionName(arg1, arg2, ...argN)
{  
 //code to be executed  
}

Let’s first see the simple example of a function in JS that doesn't have any arguments.

<html>
  <body>
    <input type="button" onclick="msg()" value="call function"/> 

    <script>
      function msg(){              //function definition 
        alert("Hello amazing people!");   //create an alert in browser
      }
    </script>
  </body>
</html>

Function Parameters and Arguments=>

When you begin programming you may get confused between these two terms, but it is crucial to understand what they are and how are they different from each other. So Let's understand the difference between these two:- Screenshot (191).png To learn more about parameters and arguments Click here.

Function with Return Value=>

This is an optional JavaScript statement that returns a value from the function. We use the keyword return, followed by the statement or expression we want to return.
Example:-

<html>
<body>
<p>What is the value of PI?</p>

Ans:-<span id="demo"></span>

<script>
document.getElementById("demo").innerHTML = getPI();

function getPI() {
  return Math.PI;
}
</script>

</body>
</html>

Note:- Return statement should be written in the last because it skips all code in the block written after that.

Function Scope=> As we know there are two types of variables in JS, local variables and global variables. Local variables are defined inside a function and cannot be accessed outside it. But a function can access any variable defined as a global variable.
Let's understand exactly what I mean with the help of following code:

<html>
  <body>
    <h3>Function Scope</h3>

    <script>
      var num1 = 2;     //global variable
      document.write("Value of number 1 is " + num1 + "</br>");  //global scope
      function parentFunction(){
        var num2 = 4;       //local variable
        num1 = 8;
        document.write("Number 1 is " + num1 + "</br>");  //inside parent func.  
        document.write("Number 2 is " + num2 + "</br>");  //local scope

        childFunction();      //child function called

        function childFunction(){      //nested function
          var num3 = 0;
          document.write("Number 2 is " + num2 + "</br>");  // inside child func.
          document.write("Number 3 is " + num3 + "</br>");  //local scope
        }
      }
      parentFunction(); //parent function called
    </script>
  </body>
</html>

Output:-

Screenshot (193).png

Conclusion:-

HTML is the language of web content, but JavaScript is the language of web functionality. It is one of the fastest evolving languages, in terms of practices, tooling, and ecosystem. It’s an incredibly exciting language to be using right now.

In this blog, we have just scratched the surface of JavaScript. If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝

Thanks for reading 😃

I would ❤ to connect with you at Twitter | LinkedIn | GitHub Let me know in the comment section if you have any doubt or feedback.

Resources

Did you find this article valuable?

Support Neha Soni by becoming a sponsor. Any amount is appreciated!