DEV Community

loading...
Cover image for Introduction to JavaScript: Basics

Introduction to JavaScript: Basics

Neha Soni
Software Engineering Intern at FICO | Technical Blogger
・9 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 
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
  • 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>
Enter fullscreen mode Exit fullscreen mode
  • 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>
Enter fullscreen mode Exit fullscreen mode

script.js

function greet()
{
    document.getElementById("greet").innerHTML = "Hello World!";
}
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode
  • 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Incorrect JavaScript variables=>

<script>
var  123=30;  
var *aa=320;  
</script>
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Example:-

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

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
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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  
}  
Enter fullscreen mode Exit fullscreen mode

Example:-

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

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);
Enter fullscreen mode Exit fullscreen mode

Example:-

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

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  
}  
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)