JavaScript

Introduction

JavaScript is a very popular programming language. The language was developed by Brendan Eich in 1995. It is also called client-side scripting language but now a day it can also be used for server-side development, desktop application development, and more. It is a versatile and dynamic language that allows developers to add interactivity and functionality to websites.

Features of JavaScript

Here are some key aspects and features of JavaScript:

  • Client-Side Scripting
  • High-level Language
  • Interpreted Language
  • Object-Oriented
  • Event-Driven
  • Asynchronous Programming
  • Cross-platform
  • Libraries and Frameworks
  • Security
  • Standardization: JavaScript is standardized through the ECMAScript specification. The latest version of ECMAScript, as of my knowledge cutoff date, is ECMAScript 2022 (ES13).

A simple example of JavaScript program in html file

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Fun</h2>

<script>
    alert("Welcome in JavaScript World!");
</script>

</body>
</html>

JavaScript Variables

Variables are containers of keeping data. JavaScript can be declared in 4 ways which are:

var, let, const, and using nothing

  • The var keyword was used in all JavaScript code from 1995 to 2015 and it should be used for only old browser.
  • The let keyword was introduced in ES6 (2015)
  • let and const variables have Block Scope. Variables declared inside a { } block cannot be accessed from outside the block. However, before ES6,JavaScript had Global Scope and Function Scope for var variable.
  • let and const can not be redeclared but vat can be redeclared.

<html>
<body>

<h1>JavaScript Variables</h1>
<p id="showdata"></p>

<script>
var x = 10; 
let r = 5; 
const pi = 3.14; 
// here var, let and const are keywords
area = pi*r*r; /* formula of circle. 
area is declared without any keyword*/
document.getElementById("showdata").innerHTML = "The area of a circle is: " + area; 
</script>

</body>
</html>

JavaScript Output

In JavaScript output can be shown using innerHTML, document.write(), window.alert(), and console.log(). You will learn more about these in next chapters.

JavaScript Operators

As like as other programming language, JavaScript has different types of operators which are:

Arithmetic Operators

OperatorDescriptionExample
+Additionx + y
Subtractionx – y
*Multiplicationx * y
**Exponentiationx**y
/Divisionx / y
%Modulus (Remainder)x % y
++Incrementx++ or ++x
– –Decrementy- – or – -y
Table: arithmetic operators

Assignment Operators

OperatorExampleTraditional wayOperator Type
=x = yx = ySimple Assignment
+=x += yx = x + yAddition Assignment
-=x -= yx = x – ySubtraction Assignment
*=x *= yx = x * yMultiplication Assignment
/=x /= yx = x / yDivision Assignment
%=x %= yx = x % yModulus (Remainder) Assignment
**=x **= yx = x**yExponentiation Assignment
<<=x <<= yx = x << yLeft Shift Assignment
>>=x >>= yx = x >> yRight Shift Assignment
>>>=x >>>= yx = x>>> yUnsigned Right Shift Assignment
&=x &= yx = x & yBitwise AND Assignment
| =x |= yx = x | yBitwise OR Assignment
?=x ?= yx = x ? yBitwise XOR Assignment
&&=x &&= yx = x && yLogical AND assignment
||=x ||= yx = x || yLogical OR assignment
??=x ??= yx = x ?? yNullish coalescing assignment
Table: Assignment operators

Comparison Operators

OperatorDescriptionExample
==equal tox == 100
===equal value and equal typex ===100
!=not equalx != 100
!==not equal value or not equal typex !== 100
>greater thanx >100
<less thanx < 100
>=greater than or equal tox >=100
<=less than or equal tox <= 100

Logical Operators

Type Operators

Data Types

JavaScript has several built-in data types. Primarily, JavaScript has two types data which are:

  1. Primitive data types
  2. Reference data types

Primitive types are stored by value, while reference types are stored by reference.

Primitive data types:

Number:

Example:

let x = 10;
let age = 21.34;
let pi = 3.14159;

String: String data are enclosed by single quotation(‘) or double quotation (“)

Example:

let name = "Nazim Uddin";
let message = 'Hello, world!';

Boolean:

let x = true;
let y = false;

Undefined: Represents a variable that has been declared but has not been assigned a value.

Example:

let x;
document.write(x); // undefined

Symbol (ES6): Used to create unique values, primarily as object property keys. Symbols are immutable datatype and act as unique identifiers for object keys.

Example:

const uniqueSymbol = Symbol("unique");

Reference Data Types:

Array: A special type of object used to store ordered collections of values.

Example:

let colors = ["red", "green", "blue"];
let ages = [20, 30, 40];

Object: Represents a collection of key-value pairs. Objects can be used to store various data types and functions.

Example:

let car = {
  company: "Toyota",
  model: "Camry",
  year: 2020
};

RegExp: Used for regular expressions to match patterns in strings.

let pattern = /USA/;

Set: Set allows to store and work with a set of distinct values. Sets are part of the ECMAScript 6 (ES6) standard, so they are available in modern JavaScript environments.

Example:

const numberSet = new Set([1, 2, 3, 4, 5]);

Function: A first-class object in JavaScript that allows you to define and execute reusable blocks of code.

function add(a, b) {
    return  a + b;
}

Map: A Map can store any data type as both keys and values.

Example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <h1>Map Data Type</h1>
    <script>
      const Colors = new Map();

      // Add entries to the Map
      Colors.set("Sky", "Blue");
      Colors.set("Rose", "Red");

      // Retrieve and display colors
      document.write("Find Colors: <br />");
      document.write("Sky:", Colors.get("Sky"), "<br />");
      document.write("Rose:", Colors.get("Rose"));
    </script>
  </body>
</html>

Conditional Statements

Conditional statements in JavaScript allow you to execute a certain code block based on the result of a condition. There are several conditional statements in JavaScript: if, if-else, if-else-if, switch etc.

The if statement: It is used to execute a block of code if a specified condition is true. The syntax is as follows:

if (condition) {
  // code to be executed if condition is true
}

The if…else statement: It is used to execute a block of code if a specified condition is true, and another block of code if the condition is false. The syntax is as follows:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

The if…else if…else statement: It is used to select one of several blocks of code to be executed. The syntax is as follows:

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

The switch statement: It is used to select one of many blocks of code to be executed. The syntax is as follows:

switch (expression) {
  case value1:
    // code to be executed if expression == value1
    break;
  case value2:
    // code to be executed if expression == value2
    break;
  ...
  default:
    // code to be executed if expression is different from all the values
}

Using Ternary Operator: In JavaScript, the ternary operator is a concise way to write conditional statements. The ternary operator takes three operands and returns a value based on a condition. Its syntax is as follows:

condition ? expression_if_true : expression_if_false;
<script>
      let x = Number(prompt("Enter First Number: "));
      var result = x > 0 ? "Positive number" : "Negative number";
      document.write(result);
</script>

JavaScript Loops

The following loops are available in JavaScript.

  • for
  • for / in
  • for / of
  • while
  • do/while

For loop Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<script>
for (let i = 1; i <= 10; i++) {
  document.write(i + "<br>");
}
</script>

</body>
</html>

For / in Loop

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For/In loop Example</h2>

<p id="data"></p>

<script>
const arr = [10, 20, 30, 40, 50];

let n = "";
for (let x in arr) { // x is the key/index of the object 
  n += arr[x] + "<br>"; 
}

document.getElementById("data").innerHTML = n;
</script>

</body>
</html>

For of loop

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For/In loop Example</h2>
<p id="data"></p>
<script>
const arr = [10, 20, 30, 40, 50];
let n = "";
for (let x of arr) {  // x is the value of the object 
  n += x + "<br>"; 
}
document.getElementById("data").innerHTML = n;
</script>
</body>
</html>

While Loop

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while loop Example</h2>
<p id="data"></p>
<script>
let n = "";
let i = 1;
while (i <= 10) {
  n += "<br>" + i;
  i++;
}
document.getElementById("data").innerHTML = n;
</script>
</body>
</html>

Do While Loop

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do while loop Example</h2>
<p id="data"></p>
<script>
let n = "";
let i = 1;
 do{
  n += "<br>" + i;
  i++;
}while (i <= 10)
document.getElementById("data").innerHTML = n;
</script>
</body>
</html>

JavaScript Functions

JavaScript function is declared by function keyword using following syntax.

function FunctionName(parameters) {
  // code
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions Example with parameter</h2>
<script>
function sum(a, b) { // function declartion
  var n =  a + b;
  return n;
}
document.write("Total = " + sum(4, 3)); // calling function and show output 
</script>
</body>
</html>

JavaScript function can be written in different ways. Follow the below examples in which all are same according to output.

Example-1: A tradition way

function sum(a, b) { // function declartion
  var n =  a + b;
  document.write(n);
}
sum(10,20); // function calling

Example-2: using function expressions

const sum = function(a, b) { 
  document.write(sum);
};

sum(10, 20); // function calling

Example-3: IIFEs function (IIFEs = Immediately Invokable Function Expressions)

Here I will convert the Example-1 to IIEFS functions. for IIEFs, function calling is not needed!

(function(a, b) {
  var n = a + b;
  document.write(n);
})(10, 20);

In this code:

  1. We wrap the entire function declaration in parentheses to turn it into an expression.
  2. Immediately after the closing parentheses of the function, we add (10, 20) to invoke the function immediately with the arguments 10 and 20.

This way, the function is defined and executed in one go as an IIFE.

Example-4:Using Arrow Function

const sum = (a, b) => a + b;

JavaScript Input

Using Prompt

let input = prompt("Enter your Name: ");
document.write(input);

Using HTML Forms

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <form id="frm">
      <input type="text" id="inputData" />
      <input type="submit" value="Submit" />
    </form>
    <script>
      document
        .getElementById("frm")
        .addEventListener("submit", function (e) {
          e.preventDefault(); // Prevent the form from submitting
          var userInput = document.getElementById("inputData").value;
          document.write("You entered: " + userInput);
        });
    </script>
  </body>
</html>

Using Event Listeners:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <button id="myButton">Click Me</button>

    <script>
      document
        .getElementById("myButton")
        .addEventListener("click", function () {
          var userInput = prompt("Please enter your name:");
          document.write("You entered: " + userInput);
        });
    </script>
  </body>
</html>

OOP in JavaScript

JavaScript Class

classes in JavaScript are template to create object. Classes are used to encapsulate data with code.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Class</h2>

<p id="data"></p>

<script>
class Flowers { // class declaration
  constructor(smell, color) { //The constructor method is called automatically when a new object is created.
    this.smell = smell;
    this.color = color;
  }
}

const rose = new Flowers("sweet", "red");
document.getElementById("data").innerHTML =
"The rose is " + rose.smell + " and " + rose.color;
</script>

</body>
</html>

Class Inheritance

extends keyword is used to create a class inheritance in JavaScript.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Inheritance</h2>
<p id="data"></p>
<script>
class Animal {
  constructor(name) {
    this.name = name;
  }
  puppy() {
    return 'I have a ' + this.name;
  }
}
class Pet extends Animal {
  constructor(name, type) {
    super(name); //The super() method refers to the parent class
    this.type = type;
  }
  show() {
    return this.puppy() + ', it is a ' + this.type;
  }
   static greetings(){ // static method can not be called by class object. It can be called by class name (classname.method()).
    return "Hello Dog!";
   }
}
let mypet = new Pet("Dog", "German Shepherd");
document.getElementById("data").innerHTML = mypet.show();
document.write(Pet.greetings()); //calling static method
</script>

</body>
</html>

JavaScript Object Notation (JSON)

JSON stands for JavaScript Object Notation and is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is used for exchanging data between a server and a web application, as an alternative to XML.

Data Types used in JSON

The data types used in JSON are:

  1. Object: An unordered set of key-value pairs surrounded by curly braces ({}).
  2. Array: An ordered collection of values surrounded by square brackets ([]).
  3. String: A sequence of Unicode characters surrounded by double quotes ("").
  4. Number: A numeric value (integer or floating-point) without quotes.
  5. Boolean: Either true or false without quotes.
  6. Null: A special value null without quotes.

Note: JSON does not support all data types available in programming languages, for example it does not have a separate data type for dates.

JSON Object

A JSON object is a collection of key-value pairs surrounded by curly braces ({}). Each key is a string and its corresponding value can be a string, number, Boolean, null, another JSON object, or an array.

Here is a simple JSON example:

{
    "name": "Nazim Uddin",
    "age": 44,
    "address": {
        "street": "123 Khilgaon Dhaka",
        "city": "Dhaka",
        "state": "BD",
        "zip": "94113"
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "0088-555-1234"
        },
        {
            "type": "work",
            "number": "0088-555-5678"
        }
    ]
}

In this example, the JSON object contains a person’s name, age, address, and phone numbers. The address and phone numbers are nested within the object and the phone numbers are in an array.

JSON Parse

JSON parse refers to the process of converting a JSON-formatted string into a JavaScript object or data structure that can be easily manipulated or analyzed in the code.

To parse a JSON string in JavaScript, you can use the JSON.parse() method. For example:

const jsonString = '{"name": "Nazim Uddin", "age": 44}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Nazim Uddin

In this example, the JSON string jsonString is passed as an argument to the JSON.parse() method, which returns a JavaScript object. The properties of the object can be accessed using dot notation (e.g. obj.name).

Json Stringify

JSON stringify refers to the process of converting a JavaScript object or data structure into a JSON-formatted string.

To stringify a JavaScript object into a JSON string, you can use the JSON.stringify() method. For example:

const obj = {name: "Nazim Uddin", age: 44};
const jsonString = JSON.stringify(obj);
document.write(jsonString); // Output: {"name":"Nazim Uddin","age":44}

In this example, the JavaScript object obj is passed as an argument to the JSON.stringify() method, which returns a JSON-formatted string. This string can be saved to a file, sent to a server, or used in another application.

JavaScript Reserved word

abstractdoubleinstanceofswitch
argumentselseintsynchronized
awaitenuminterfacethis
booleanevalletthrow
breakexportlongthrows
byteextendsnativetransient
casefinalnewtry
catchfinallynulltypeof
charfloatpackagevar
classforprivatevoid
constfunctionprotectedvolatile
continuegotopublicwhile
debuggerifreturnwith
defaultimplementsshortyield
deleteimportstaticFALSE
doinsuperTRUE