JavaScript

About JavaScript

JavaScript is a very popular programming language. The language was developed by Brendan Eich in 1995. It is also called client-side scripting language.

Introduction

JavaScript code run through the browser. A code is shown below:

<!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

<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>

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

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:

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
}

Conditional statements allow you to control the flow of your code, making it more dynamic and flexible.

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>

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