Table of Contents
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
andconst
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
andconst
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
Operator | Description | Example |
---|---|---|
+ | Addition | x + y |
– | Subtraction | x – y |
* | Multiplication | x * y |
** | Exponentiation | x**y |
/ | Division | x / y |
% | Modulus (Remainder) | x % y |
++ | Increment | x++ or ++x |
– – | Decrement | y- – or – -y |
Assignment Operators
Operator | Example | Traditional way | Operator Type |
---|---|---|---|
= | x = y | x = y | Simple Assignment |
+= | x += y | x = x + y | Addition Assignment |
-= | x -= y | x = x – y | Subtraction Assignment |
*= | x *= y | x = x * y | Multiplication Assignment |
/= | x /= y | x = x / y | Division Assignment |
%= | x %= y | x = x % y | Modulus (Remainder) Assignment |
**= | x **= y | x = x**y | Exponentiation Assignment |
<<= | x <<= y | x = x << y | Left Shift Assignment |
>>= | x >>= y | x = x >> y | Right Shift Assignment |
>>>= | x >>>= y | x = x>>> y | Unsigned Right Shift Assignment |
&= | x &= y | x = x & y | Bitwise AND Assignment |
| = | x |= y | x = x | y | Bitwise OR Assignment |
?= | x ?= y | x = x ? y | Bitwise XOR Assignment |
&&= | x &&= y | x = x && y | Logical AND assignment |
||= | x ||= y | x = x || y | Logical OR assignment |
??= | x ??= y | x = x ?? y | Nullish coalescing assignment |
Comparison Operators
Operator | Description | Example |
---|---|---|
== | equal to | x == 100 |
=== | equal value and equal type | x ===100 |
!= | not equal | x != 100 |
!== | not equal value or not equal type | x !== 100 |
> | greater than | x >100 |
< | less than | x < 100 |
>= | greater than or equal to | x >=100 |
<= | less than or equal to | x <= 100 |
Logical Operators
Type Operators
Data Types
JavaScript has several built-in data types. Primarily, JavaScript has two types data which are:
- Primitive data types
- 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:
- We wrap the entire function declaration in parentheses to turn it into an expression.
- Immediately after the closing parentheses of the function, we add
(10, 20)
to invoke the function immediately with the arguments10
and20
.
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:
- Object: An unordered set of key-value pairs surrounded by curly braces (
{}
). - Array: An ordered collection of values surrounded by square brackets (
[]
). - String: A sequence of Unicode characters surrounded by double quotes (
""
). - Number: A numeric value (integer or floating-point) without quotes.
- Boolean: Either
true
orfalse
without quotes. - 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
abstract | double | instanceof | switch |
arguments | else | int | synchronized |
await | enum | interface | this |
boolean | eval | let | throw |
break | export | long | throws |
byte | extends | native | transient |
case | final | new | try |
catch | finally | null | typeof |
char | float | package | var |
class | for | private | void |
const | function | protected | volatile |
continue | goto | public | while |
debugger | if | return | with |
default | implements | short | yield |
delete | import | static | FALSE |
do | in | super | TRUE |