0% found this document useful (0 votes)
463 views

Java script matrial

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
463 views

Java script matrial

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

Ameerpet technologies

JAvAscript - the beginning

vineeth goDishelA
Note:The Remaining Js topics will be covered along with React js
Ameerpet technologies

JavaScriptDay-1

DOM(Document Object Model):


 it is primarily created with html ,DOM represents the structure of webpage and allows programs
and scripts to interact with and manipulate the
1. Content
2. structure
3. style
 DOM represented in tree structure ,the top of the tree is 'document' object
 the tree has nodes in this case the nodes here are
1. elements
2. attribute
3. content

Definition:- JavaScript is a dynamic,interpreted,client-side highlevel programming language


primarily used for DOM manipulations.
 JavaScript is a versatile, high-level programming language primarily used for web development.
It runs in web browsers, enabling interactive and dynamic web pages.
 It manipulates the DOM, allowing real-time updates and user interactions. JavaScript can also be
used on the server-side through technologies like Node.js.
 (Java is a compiled language where JS is an Interpreted language)

Compiled-Language:-
 in compiled language the source code is converted into machine code by the compiler before
execution,
 the compilation process typically happens before the program runs

Ex: Java ,C,C++

Interpreted-language:-
 JS is interpreted language ,the source code is executed line by line… by an interpreter at the run-
time , there is no separate compilation step and code is executed directly from the source code
files , ex :- JavaScript ,python.
 every browser has an inbuilt JavaScript engine that's why we can directly run the code in the
browser
 JS is called scripting language because it is used for writing small programs

1
Ameerpet technologies

 JavaScript is called a client-side programming language. because it runs in web browsers,


enabling dynamic and interactive features on websites. It's executed on the user's device,
facilitating real-time updates and reducing the load on web servers.
 While it can also be used on the server-side with Node.js, but its primary role is enhancing the
client-side web experience.
 JS can be written in three places in
 1)Body location ,
 2)Head location
 and 3)External js file
 if we write JS in body location  executes when web page is loading
 if we write JS in head location and External Js  it executes or script executes when we perform
any action(for ex : onClick )

In Body JS Examples:-
 When you place JavaScript code directly within the body of an HTML document (usually
between <script> tags within the <body> section), the script will execute as the web page is
loading.
 This means that the JavaScript code will run as soon as the browser encounters it while parsing
the HTML.

alert() : it is used to display a pop-up message to the user with only an OK button, providing information
or notifications.

Example1:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
alert("Welcome to JavaScript Class");
</script>
</body>
</html>

write():write() is a method used to manipulate document, what ever we write inside write() will display
on document(on webpage)

console.log(): what ever we write inside console.log() will display in console

2
Ameerpet technologies

Example 2:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
document.write("I'll display Myself on Web page");
console.log("I'll be displayed in Console");
</script>
</body>
</html>
Data types: Datatypes are two types the are:

 Primitive data type


 Non-primitive datatype(“reference data type”);
Primitive data :
 Number
 String
 Boolean
 Undefined
 Null

Non-primitive datatype(“reference data type”) :


1. function ()
2. object{}
3. Array[]

Variables:

 The name given to the container ,which is used store the data is called variables
 variable is an identity of memory location
 variables are used to store the information
 in JS we represent the variables either by using var and let key word

Declaration : a variable without value is called declaration

var a;
let b;

Assignment : assigning value to the variable which is already declared

var a;//declaration

3
Ameerpet technologies

a=10;//assignment
a=20;//assignment
Modify : updating the existing value of variable

var a;//declaring
a=200;//assigning
a=a-50;//modifying

Initialization : Assigning the value at the same time of declaration is called Initialization

var x=10;
Example:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
var a = 10;
var b = 20;
document.write(a + b);
</script>
</body>
</html>

FINDING TYPE OF EACH VARAIABLE

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
var a = 10;
var b = 20.009;
var c = true;
var d = "hello world";
var e = {};
document.writeln("type of a=" + typeof a + "<br>");
document.writeln("type of b=" + typeof b + "<br>");
document.writeln("type of c=" + typeof c + "<br>");
document.writeln("type of d=" + typeof d + "<br>");
document.writeln("type of e=" + typeof e);
</script>

4
Ameerpet technologies

</body>
</html>

prompt():

 It is a simple pop-up in JavaScript that lets you ask the user for information.
 When you use it, a box appears in their web browser with a message and a space for them to
type something, like their name or an answer to a question.
 When they type and press OK, the thing they typed gets stored in a variable in your program so
you can use it later.
 It's like having a conversation with your user and getting their input to make your program more
interactive.

Difference Between alert() and prompt():


 alert() is for displaying information, while prompt() is for taking input from the user.
 alert() doesn't gather user input, whereas prompt() is useful for collecting user data or responses
in interactive programs.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
var name = prompt("enter Your Name ");
document.write("your name is " + name);
</script>
</body>
</html>

Example that prompt collects value as string:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
var x = prompt("enter first number ");
var y = prompt("Enter Second Number");

5
Ameerpet technologies

document.write(x + y);
</script>
</body>
</html>

Converting String value to Int:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
</head>
<body>
<script>
var x = parseInt(prompt("enter first number "));
var y = parseInt(prompt("Enter Second Number"));
document.write(x + y);
</script>
</body>
</html>

EXTERNAL JS:
 When you link to an external JavaScript file using the <script> tag in either the head or body
of the HTML document, the script in the external file will be fetched and executed when the
browser encounters it.
 The external file might be fetched asynchronously or synchronously, depending on whether you
use the async or defer attribute in the script tag.

Example 1:
jspractice.js

function promptme(){

var x=parseInt(prompt("enter first number "));


var y=parseInt(prompt("Enter Second Number"));
document.write(x+y);
}

practice.html

<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>

6
Ameerpet technologies

<script type="text/javascript" src="jspractice.js"></script>


</head>
<body>
<button onClick="promptme()">promptme</button>
</body>
</html>

Example 2:
jspractice.js

function emailbox() {
var mail = document.getElementById("email").value;
if (mail != "") {
if (mail.length < 6) {
document.writeln("write mail length above 6 letters");
} else {
document.writeln("thank you for entering the mail");
}
} else {
document.writeln("mail cannot be empty");
}
}

practice.html

<!DOCTYPE html>
<html>
<head>
<title>Form Validation with External JavaScript</title>
<script src="jspractice.js"></script>
</head>
<body>
<form onsubmit="emailbox()">
<input type="text" id="email" placeholder="Enter your email" />
<input type="submit" value="submit" />
</form>
</body>
</html>
Internal javascript:
 If you place JavaScript code within the <head> section of an HTML document, the script will also
execute as the web page is loading, similar to placing it in the body.
 The key difference is that if the script interacts with HTML elements that are defined later in the
body, it might not find those elements yet, leading to potential issues.

7
Ameerpet technologies

Example 1:
<!DOCTYPE html>
<html>
<head>
<title>/title>
<script >
function add() {
var a=parseInt(document.getElementById("a").value);
var b=parseInt(document.getElementById("b").value);
//here we are adding the result (a+b) into the result box
document.getElementById("res").value=a+b;
}
</script>
</head>
<body>
Enter number a:<input type="text" id="a" /> <br>
Enter number b:<input type="text" id="b" /> <br>
Result:<input type="text" id="res" readonly />
<!-- here readonly attribute will help to keep the result box constant you
cant change it if you want to change it also
-->
<button onClick="add()">Add</button>
</body>
</html>

similarly try substarction,multiplication,division

Example 2:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function yellow() {
document.body.style.color = "yellow";
var a = document.getElementById("im");
a.innerText =
"You Bakwas fellow ,You changed me to yellow yellow dirty fellow!";
}
</script>

8
Ameerpet technologies

</head>
<body>
<h1 id="im">Dont Click Below Button ,I will be in a different color</h1>
<button onClick=" yellow()">green color</button>
</body>
</html>

Example 3:[Funny Example: with information]

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function green() {
document.body.style.color = "green";
var h = document.getElementById("im");
h.innerText = "You fellow, You changed me to Green. Shut!";
}
function sizechange() {
document.body.style.fontSize = "50px";
var a = document.getElementById("im");
a.innerText = "This is my Transformation";
}

function backround() {
document.body.style.backgroundColor = "red";
var a = document.getElementById("im");
a.innerText = "This is My Background";
}

function discipline() {
document.body.style.textAlign = "center";
var a = document.getElementById("im");
a.innerText = "See where I'm";
}
</script>
</head>
<body>
<h1 id="im">Please Don't Click Below Buttons, They Will Change Me</h1>
<button onClick="green()">Green color</button>
<button onClick="sizechange()">I go to gym</button>
<button onClick="backround()">You don't Know My Background</button>
<button onClick="discipline()">I'm a good button</button>
</body>

9
Ameerpet technologies

</html>

JavaScriptDay-2
Function:
In JavaScript, a function is a reusable block of code that performs a specific task or a set of tasks.

Function Definition:

function sayHello() {
console.log("Hello, world!");
}

Function Invocation:

To execute a function, you need to "invoke" or "call" it:

sayHello();
// This will call the sayHello function, and "Hello, world!" will be printed to the console

ES6:- which stands for ECMAScript 2015, introduced a significant set of new features and
enhancements to the JavaScript programming language.

1. These features were designed to make JavaScript more powerful, flexible, and
developer-friendly.
2. ES6 was a significant update to JavaScript, and its features were gradually adopted by
browsers and JavaScript environments.
3. It was a response to the growing complexity of JavaScript applications and the need for
better language features.

Variables:Until Es5 there was only var ,but in Es6 they added let, const

var is functional scope:

function varScopeEx() {
if (true) {
var x = 5;
}
console.log(x); // 5, x is accessible throughout the function
}

10
Ameerpet technologies

varScopeEx();

Example 2:

function varScope(){
for(var i=0;i<=12;i++){
console.log(i);
}
console.log("the value after loop is "+ i)
}
varScope();
output:
//0 to 12
// the value after loop is 13

let is a block scope or local scope

function letExample() {
if (true) {
let y = 10;
}
console.log(y); // Error: y is not defined in this scope //reference error
}

letExample();

Example2:

function varScope(){
for(let i=0;i<=12;i++){
console.log(i);
}
console.log("the value after loop is "+ i)
}
varScope();
output:
//0 to 12
// console.log("the value after loop is "+ i)
// ReferenceError: i is not defined

const is also block scope or local scope

function constExample() {

11
Ameerpet technologies

if (true) {
const z = 15;
}
console.log(z); // Error: z is not defined in this scope// reference error
}
constExample();

Example 2:

function varScope(){
for(const i=0;i<=12;i++){
console.log(i);
}
console.log("The value of i after loop "+ i);
}
varScope();
//output:
// for(const i=0;i<=12;i++){
// ^
// TypeError: Assignment to constant variable.

Redeclaration and modifiation of var is possible

var a = 5;
console.log(a); // 5

var a = 10; // Redeclaration is allowed


console.log(a); // 10

a = 15; // Updating is allowed


console.log(a); // 15

Redeclaration in Let is not possible but modification(updating) is possible

let b = 5;
console.log(b); // 5

// let b = 10; // Error: Identifier 'b' has already been declared (Redeclaration
not allowed)

b = 15; // Updating is allowed


console.log(b); // 15

12
Ameerpet technologies

//But redeclaration is possible in different scopes

let x="hello";
if(true){
let x="I said Hello";
console.log(x) // output: I said Hello
}
console.log(x);//output: hello

Redeclaration and updating are NOT possible in const

const c = 5;
console.log(c); // 5
// const c = 10; // Error: Identifier 'c' has already been declared
(Redeclaration not allowed)
// c = 15; // Error: Assignment to constant variable (Updating is not allowed)

var can be declared without initializing

var x; // Declaration without initialization


console.log(x); // undefined
x = 5; // Initialization
console.log(x); // 5

let can be declared without being initialized

let y; // Declaration without initialization


console.log(y); // undefined
y = 10; // Initialization
console.log(y); // 10

const must be initialized at the time of declaration

const z; // Error: Missing initializer in const declaration

Hoisting:

 This allows you to use variables and functions before you've actually declared them in your code.
 However, it's important to note that only the declarations are hoisted, not the initializations or
assignments.
 So, if you try to use a variable before it's initialized, it will have the value undefined.

13
Ameerpet technologies

 Hoisting with var:

console.log(x); // undefined
var x = 5;
console.log(x); // 5

Hoisting with let:

console.log(y); // ReferenceError: Cannot access 'y' before initialization


let y = 10;
console.log(y); // 10

Hoisting with const:

console.log(z); // ReferenceError: Cannot access 'z' before initialization


const z = 15;
console.log(z); // 1

Difference between var let const:

var let const

1)var is functional scope 1)let is a block scope or local 1)const is also a block
scope scope or local scope
2)Redeclaration and modifiation
of var is possible 2)Redeclaration is not possible 2)Redeclaration and
but modification(updating) is updating are NOT
3)var can be declared without possible possible
initializing
3)let can be declared without 3)it must be
4) var belongs to Es5 being initialized initialized at the time
of declaration
5)hoisting is possible declaration 4)let belongs to Es6
moves to top and if we print it 4)const belongs to
gives undefined 5)Hoisting is possible but if we Es6
want to access it will throw
reference error 5)Hoisting is possible
but if we want to
access it will also
throw reference
error

14
Ameerpet technologies

JavaScriptDay-3
Functions:

Function Definition:

In JavaScript, a function is a reusable block of code that performs a specific task or a set of tasks.

Syntax:

function sayHello() {
console.log("Hello, world!");
}

Function Invocation:

To execute a function, you need to "invoke" or "call" it:

sayHello(); // This will call the sayHello function, and "Hello, world!" will be printed to the console

Difference between method and function in js?

 A method is associated with an object, while a function is not.

Types of Functions :
 Named fnctions
 Anonymous functions
 Arrow functions

Named Functions:

Named functions have a name identifier and can be defined using the function keyword. They
are advantageous for better code organization and stack trace readability.

Functions without input and without any return:


Example 1

function greet() {
console.log("Hello!");
}
greet();

15
Ameerpet technologies

Example 2

function announceEvent() {
console.log("The event has started.");
}
announceEvent();

Example 3

function sayThanks() {
console.log("Thanks for your help!");
}
sayThanks();

Arguments and Parameters

 Arguments: The values that are declared within a function when the function is called are
known as an argument. (Or) the values which are passed while invoking function is called
arguments and they are actual values
 Parameters: The variables that are defined when the function is declared are known as
parameters.(Or ) The variables passed while defining a function is called Parameters

Functions with input and without return:


Example 1

function add(a, b) {
console.log(a + b);
}
add(5, 7);

Example 2

function greetPerson(name) {
console.log("Hello, " + name + "!");
}
greetPerson("Alice");

Example 3

function calculateArea(radius) {
console.log("Area:", 3.14159 * radius * radius);
}
calculateArea(5);

16
Ameerpet technologies

Functions without input and with return:


Example1

// Function to generate a greeting message

function getGreeting() {
return "Hello, world!";
}
const greeting = getGreeting();
console.log(greeting);
Example:2

function Factorial (){


let fact=1;
const num=3;
for(let I = 1;i<=num; i++){
fact=fact*I ;
}
return fact
}
const ans=abc();
console.log(ans)

Functions with input and with return:


Example 1

function multiply(a, b) {
return a * b;
}
const result1 = multiply(3, 4);
console.log(result1);

Example 2

function findMax(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
const maxNumber = findMax(42, 28);
console.log("Maximum:", maxNumber);

17
Ameerpet technologies

Anonymous Function:
 An anonymous function is a function that is defined without a name.
 Instead of having a function name, it is typically defined inline as part of an expression.
 Anonymous functions are also commonly referred to as "function expressions."

Functions without input and without any return:


Example 1:

const Message = function () {


console.log("I am anonymous ,so give me any name please");
};
Message();

Example 2:

const findsmall=function(){
let a=20;
let b=30;let c=10;
if(a<b && a<c){
console.log("a is small");
}
else if(b<a && b<c){
console.log("b is small");
}
else{
console.log("c is small");
}
}
findsmall();

== (Equality Operator):

 The == operator checks for equality of values without considering their data types.
 If the values being compared have different data types, JavaScript will attempt to
convert one or both values to a common data type before making the comparison.
 This can lead to unexpected results in some cases due to type coercion.
 Example: 1 == '1' would return true because JavaScript coerces the string '1' to a number
before making the comparison.

18
Ameerpet technologies

=== (Strict Equality Operator):

 The === operator checks for strict equality of both values and data types.
 It does not perform type coercion. Both the values and their data types must be
identical for the comparison to return true.
 This is generally considered safer and more predictable because it avoids unexpected
type conversions.
 Example: 1 === '1' would return false because the values have different data types.

Functions with input and without any return:


const findType = function (a) {
if (typeof a === 'number') {
console.log("Number");
}
else if (typeof a === 'string') {
if (a.length > 1) {
console.log("Word");
} else {
console.log("Alphabet");
}
}
else if (typeof a === 'boolean') {
console.log("Boolean");
}
}

findType(42); // This will output "Number" for 42


findType("Word"); // This will output "Word" for "Word"
findType("A"); // This will output "Alphabet" for "A"
findType(true); // This will output "Boolean" for true

 In the following example extra I added symbol logic here I used includes method : The
includes() method is a built-in JavaScript method that is typically used with strings and
arrays.
 It checks if a specified value exists within the string or array and returns true if the value is
found, and false if it is not found.

const findType = function (a) {


if (typeof a === "number") {
console.log("Number");
} else if (typeof a === "string") {
const specialChars = "!@#$%^&*";
if (a.length === 1 && specialChars.includes(a)) {

19
Ameerpet technologies

console.log("Symbol");
} else if (a.length > 1) {
console.log("Word");
} else {
console.log("Alphabet");
}
if (typeof a === "number") {
console.log("Number");
}
} else if (typeof a === "boolean") {
console.log("Boolean");
}
};

findType(42); // This will output "Number" for 42


findType("A"); // This will output "Alphabet" for "A"
findType("#"); // This will output "Symbol" for "#"
findType("AB"); // This will output "Word" for "AB"

Multiplication Table program

const mul=function(num)
{
for(var i=1;i<=num;i++){
console.log(num+"X"+i+"="+(num*i));
}

}
mul(10)

Functions with input and with return:


Example 1:

const check=function(num){
if(num%2===0){
return "even";
}
else {
return "odd";
}

}
console.log(check(15));

20
Ameerpet technologies

//prime number

const checkPrime = function (num) {


var count = 0;
for (var i = 1; i <= num; i++) {
if (num % i === 0) {
count++;
}
}
if (count == 2) {
return "prime";
} else {
return "not prime";
}
};
console.log(checkPrime(7));

Functions without input and with return:


const add=function (){
var a=10;
var b=20;
return (a+b);
}
console.log(add());
//sum of even numbers until given number

const evensum = function (n) {


var sum = 0;
for (var i = 1; i <= n; i++) {
if (i % 2 !== 0) {
sum = sum + i;
}
}
return sum;
};
console.log(evensum(5));

Arrow function:-
An arrow function, also known as a fat arrow function, is a concise way to write anonymous
functions (functions without a name) in JavaScript. Arrow functions were introduced in
ECMAScript 6 (ES6) and provide a more compact and expressive syntax for defining functions
compared to traditional function expressions.

21
Ameerpet technologies

Uses of Arrow Function:

 Concise Syntax: Arrow functions are shorter and more readable than traditional
function expressions, especially for simple functions with a single statement.
 Implicit Return: If the function body consists of a single expression, you can omit the
curly braces {} and the return keyword. The result of the expression will be automatically
returned.
 Implicit Return: If the function body consists of a single expression, you can omit the
curly braces {} and the return keyword. The result of the expression will be automatically
returned.
 Lexical this Binding: Arrow functions do not have their own this context; instead, they
inherit the this value from the enclosing (lexical) context. This makes them particularly
useful for callback functions and event handlers, as they can help avoid issues related to
the value of this.

Drawbacks of Arrow Function:

 Not Suitable for All Cases: While arrow functions are great for many situations, they are not a
complete replacement for traditional functions. Traditional functions still have their place,
especially when dealing with constructors or methods that require their own this context.

Functions without input and without any return:


Example1:

Factors of given number

const factors = () => {


var n = 10;
for (let i = 0; i <= n; i++) {
if (n % i === 0) {
console.log(i);
}
}
};
factors();

Example 2: Even numbers within the range

const evenNumbers = () => {


var n = 10;
for (let i = 1; i <= n; i++) {
if (i % 2 === 0) {
console.log(i);

22
Ameerpet technologies

}
}
};
evenNumbers();

Functions with input and without any return:


Example 1

const modifyName = (name) => {


if (name.length <= 4) {
name = "Ameerpet Technologies";
console.log(Name);
} else {
console.log(Name);
}
};
modifyName("Ameerpet");
Example2

const reverseNum = (num) => {


var rev = 0;
while (num > 0) {
var lastdigit = num % 10;
rev = rev * 10 + lastdigit;
num = parseInt(num / 10); // in Js by default it returns float value that’s
why I converted it to integer type
}
console.log(rev);
};
reverseNum(286);

Functions without input and with return:


const getWelcomeMessage = () => {
return "Welcome to our website! Enjoy your visit.";
};

const welcomeMessage = getWelcomeMessage();


console.log(welcomeMessage);

perfect Number:sum of factors excluding original number should be equal to original number then we
say it as perfect number

23
Ameerpet technologies

just to know:

1. 6: The sum of its proper divisors (1, 2, 3) equals 6.


2. 28: The sum of its proper divisors (1, 2, 4, 7, 14) equals 28.
3. 496: The sum of its proper divisors (1, 2, 4, 8, 16, 31, 62, 124, 248) equals 496.
4. 8128: The sum of its proper divisors (1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032,
4064) equals 8128.

const perfectNumbers = () => {


const num = 28;
let sum = 0;
for (let i = 1; i < num; i++) {
if (num % i === 0) {
sum = sum + i;
}
}
if (sum === num) {
return "perfect Number";
} else {
return "Not a perfectNumber";
}
};
console.log(perfectNumbers());

Functions with input and with return:


Example 1:

const subtract=(x, y)=> {


return x - y;
}
const result2 = subtract(15, 7);
console.log(result2);

Example 2:

const canVote=(age)=>{
if(age>=18){
return "eligible to vote";
}
else{
return "You cant vote your age is "+age +" Only ";
}
}

24
Ameerpet technologies

console.log(canVote(21));

JavaScriptDay-4
 Primitive Types: Primitive types in JavaScript (such as numbers, strings, booleans, null,
undefined, and symbols) are stored as values directly in memory.
 Reference Types: Objects (including arrays, functions, and custom objects) are
considered reference types because they are stored as references or pointers to their
memory locations.

Plain objects in JavaScript are simple data structures that consist of key-value pairs.
They serve as basic containers for organizing and storing data, and they are typically created using object
literals or the Object() constructor.

Just to know what are objects and what are functions

Plain Objects:

1. Data Containers: Plain objects are primarily used as data containers. They organize and
store data using key-value pairs, where the keys are strings or symbols, and the values
can be of any data type.
2. No Execution Context: Plain objects do not have an execution context or behavior
associated with them. They do not contain executable code, methods, or functions by
default. They are mainly used for data storage and organization.
3. Creation: Plain objects are typically created using object literals or the Object()
constructor. They do not involve executing code when created.
4. Usage: Common use cases for plain objects include representing structured data,
configuration settings, dictionaries, and JSON data.

Functions:

1. Executable Code: Functions in JavaScript are blocks of executable code that can be
defined and invoked. They can contain a series of statements and can perform actions or
calculations.
2. Execution Context: Functions have their own execution context, which means they can
have local variables, parameters, and they can access variables from their surrounding
scope (closure).
3. Creation: Functions can be defined using function declarations, function expressions,
arrow functions, or as methods within objects. They are used to encapsulate behavior and
logic.
4. Usage: Functions are used for defining reusable code blocks, implementing algorithms,
performing operations, and responding to events. They are essential for defining the
behavior of objects and the application logic.

25
Ameerpet technologies

In summary, plain objects are primarily used for data storage and organization and do not contain
executable code. Functions, on the other hand, are blocks of executable code that can perform
actions, calculations, and encapsulate behavior.

Creating a object :Syntax


We can create plain object in two ways

Object Literal:

const person = {
name: "John",
age: 30
};

Accessing Object properties:

In JavaScript, you can access object properties using two primary methods: dot notation and bracket
notation.

Dot Notation: Dot notation is the most common way to access object properties when the property
name is a valid identifier (e.g., doesn't contain spaces or special characters and doesn't start with a
number):

const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
const firstname = person.firstName; // Using dot notation
console.log(firstname); // Output: "John"

Bracket Notation:

Bracket notation is used when the property name contains spaces, special characters, or when
you want to access a property dynamically using a variable:

const person = {
"first name": "John",
"last name": "Doe",
age: 30,
};

const lastName = person["last name"]; // Using bracket notation


console.log(lastName); // Output: "Doe"

26
Ameerpet technologies

Adding a new Property To an Object:

const person = {
firstName: "John",
lastName: "Doe"
};

// Adding a new property using dot notation

person.age = 30;

const person = {
firstName: "John",
lastName: "Doe"
};

// Adding a new property using bracket notation

person["age"] = 30;

Modifying an Existing property of an object:

const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

// Modifying the "age" property using dot notation

person.age = 31;
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

// Modifying the "age" property using bracket notation

person["age"] = 31;

Deleting a property from an Object:


//Dot notation

27
Ameerpet technologies

const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Deleting the "age" property
delete person.age;

// The "age" property is now removed from the object


console.log(person.age); // Output: undefined

//Bracket Notation

const person = {
firstName: "John",
lastName: "Doe",
age: 30
};

// Deleting the "age" property using bracket notation


delete person["age"];

// The "age" property is now removed from the object


console.log(person.age); // Output: undefined

Object inside another Object:

const person1 = {
name: "Raju",
age: 21,
gender: "male",
address: {
city: "Hyderabad",
area: "ameerpet",
pincode: 505412,
},
};
console.log(person1.address);
console.log(person1.address.area);
person1.address.city = "America";

28
Ameerpet technologies

JavaScriptDay-5
Creating object using the Constructor
// Create a car object
const car = new Object();

// Add elements
car.make = 'Toyota';
car.model = 'Camry';
car.year = 2022;
car.color = 'Blue';

// Access and print elements


console.log("Make: "+car.make);
console.log("Model:" +car.model);
console.log("Year:" +car.year);
console.log("Color:"+car.colors);

// Modify elements
car.year = 2023;
car.color = 'Red';

// Access and print modified elements


console.log("Modified Year:" +car.year);
console.log("Modified Color:"+car.color);

// Delete elements
delete car.color;

// Access and print elements after deletion


console.log("After deleting color property:");
console.log("Make: "+car.make);
console.log("Model:"+car.model);
console.log("Year:"+car.year);

// Try to access the deleted property (will be undefined)


console.log("Color:"+car.color);

29
Ameerpet technologies

Execution Context: Everything in js happens in Execution Context


In JavaScript, the term "execution context" refers to the environment in which a piece of code is
executed. It includes all the variables, functions, and other resources that a particular piece of code has
access to during its execution.

Memory Code

Data Stored in key:value pair Here the code Executes line by line
X:undefined,
Function:{……} Here code executes one line at a time

 Execution Context has two components. They are:-


1. Memory (also known as Variable Environment) :Here data stored in key : value pairs
2. Code:(also known as Thread of Execution): here code executes one line at a time
JavaScript is a Synchronous single -threaded language
Single-Threaded: Executes one command at a time
Synchronous: in particular order
Ex:
var x = 25;
function add(n1, n2) {
var sum = n1 + n2;
return sum;
}
var firstSum = add(x, 10);
var secondSum=add(10,x);
console.log(firstSum);

What happens in background ,when we run the code in js?


1)execution context will be created first : it executes in two phases:

30
Ameerpet technologies

 1) Memory Creation phase: here memory allocated to the code if it has variables its defined
as undefined , then if we have functions in code it wil store total function code.

Memory Code

X:undefined,
add: {
var sum = n1 + n2;
return sum;
}
firstSum:udefined,
secondSum:undefined

 2) code execution phase


Here code logics executes,here total calculation happens again js engine execute from
starting

Memory Code

Add
x:25 Memory creation
add: { Memory Code
var sum = n1 + n2; n1:undefined
return sum; n2:undefined
} sum:undefined
firstSum:udefined, Code Execution
secondSum:undefined Memory Code
------------------------------------ n1:25
After return n2:10 Then Here return
X:25 sum:35 will terminate
firstSum:35 function and moves
controller to
invocation line the
this value is
returned to
invocated variable
After completion of invocation the execution context of function(local execution context) will
be deleted

31
Ameerpet technologies

Main execution conext is called as Global execution context

Hoisting: the execution context is reason for hoisting


console.log(x);
const message=sayHello();
console.log(message);
var x=25
function sayHello(){
console.log("Hello");
return 10+20;
}

Window:

 In JavaScript, there is a global object called window, but typically, when you access
variables or functions, you don't explicitly use the window keyword unless you're working
with properties of the global object.
 For example, if you define a variable in the global scope, it becomes a property of the
window object:

var myVariable = "Hello, world!";


console.log(window.myVariable); // This would output "Hello, world!"

However, when working with local variables or functions, you typically don't need to reference
the window object. For example:

function myFunction() {
var localVar = "This is a local variable";
console.log(localVar);
}

myFunction(); // This would log "This is a local variable"

Using a function inside object and returning the value


// Define a plain object
const person = {
firstName: "John",
lastName: "Doe",

// Define a method inside the object


fullName: function () {
return this.firstName + " " + this.lastName;
},

32
Ameerpet technologies

//Using a function inside object and using the console.log to print value
greet: function () {
console.log("Hello, my name is " + this.fullName());
},
};

// Access properties and call methods of the object


console.log(person.firstName); // Output: "John"
console.log(person.lastName); // Output: "Doe"
console.log(person.fullName()); // Output: "John Doe"
person.greet(); // Output: "Hello, my name is John Doe"

JavaScriptDay-6
Classes were introduced in JavaScript with the release of ECMAScript 6 (ES6), which is also known as
ECMAScript 2015. Prior to ES6, JavaScript used prototype-based inheritance rather than class-based
inheritance.

Prototype-based inheritance: prototype-based inheritance is a way to create and manage object


relationships.

 Every object in JavaScript has an internal property called [[Prototype]] (often referred to as
"dunder proto") which can point to another object.
 When you try to access a property or method on an object, and that property or method doesn't
exist on the object itself, JavaScript will look up the prototype chain to find it.

Prototypes:-

 In JavaScript, objects can inherit properties and methods from other objects through their
prototypes.
 Each object can have a prototype object, which it inherits from. This is done using the
[[Prototype]] property.

Example1:

//here I am calling run() method from person object but here there is no run() in person object

const person={
name:"hero",
age:21,
gender:"male",
}

const prototype1={
run:()=>{

33
Ameerpet technologies

console.log("I am run method of prototype1");


}
}

person.__proto__=prototype1;
person.run() //output will be :-I am run method of prototype1

Example 2:

const person={
name:"hero",
age:21,
gender:"male",
run:function(){
console.log("I am run method");
}
}
const prototype1={
run:()=>{
console.log("hero");
}
}

person.__proto__=prototype1;
person.run(); //output: I am run method

Example 3:

 when objects are linked together through their prototype chains, this is often referred to as
"prototype inheritance" or "prototypal inheritance.
 " It's a mechanism by which objects can inherit properties and methods from other objects in a
hierarchical manner.

const person={
name:"Hero",
gender:"male",
age:25,
run:function(){
console.log("I am running method from main Object");
}
}
const prototype1={
run:function(){

34
Ameerpet technologies

console.log("I am running method from protype1");


}
}
const prototype2={
walk:function(){
console.log("I am walking method from protype2");
},
run:function(){
console.log("I am running method from protype1");
}
}

person.__proto__=prototype1;
prototype1.__proto__=prototype2;
person.walk(); //output:I am walking method from protype2
person.run(); //output:I am running method from main Object

Object Oriented Programming

Class-Based
Class:
 class is a collection of variables and methods
 variables-Store information
 Methods-Process information

Object:
 Realworld entity (Human,House,Car,Laptop,Mobile….)
 Object -memory allocation of class

1)Class (Blueprint): Think of a class as a blueprint for creating cars. It defines what a car should have,
such as wheels, color, engine type, and methods like "start" and "stop."

2) Instance (Object Instance): An instance is a specific car created based on the blueprint (class). Each
car has its unique characteristics, such as a specific color, number of wheels, and so on. These individual
cars are instances of the car class.

In JavaScript, the public keyword is not used when creating classes because JavaScript does not have
explicit access modifiers like some other programming languages (e.g., Java or C#). In JavaScript, all class
members are public by default.

35
Ameerpet technologies

When you define properties or methods within a class in JavaScript, they are automatically considered
public and can be accessed from outside the class instance.

class RailwayForm{
submit(){
console.log("Your form is submitted");
}
cancel(){
console.log("Your application is cancelled");
}
}
RailwayForm.submit();

let rohanForm=new RailwayForm();

//let gopalForm=new RailwayForm();

rohanForm.submit();

rohanForm.cancel();

Example 1:

class RailwayForm{
static submit(){
console.log("Your form is submitted");
}
static cancel(){
console.log("Your application is cancelled");
}
}
RailwayForm.submit();

Example 2:

class RailwayForm {
fill(gname) {
console.log(gname + "filled the form");
}
static submit() {
console.log("Your form is submitted");
}
static cancel() {
console.log("Your application is cancelled");
}

36
Ameerpet technologies

}
RailwayForm.submit();
let heroForm = new RailwayForm();
heroForm.fill("Hero");

//In js this “Hero ”will store in instance {whereas in java we explicitly use instance variable}

javaCode:

public class RailwayForm {

private String applicantName;

public void fill(String gname) {


this.applicantName = gname;
System.out.println(gname + " filled the form");
}

public static void submit() {


System.out.println("Your form is submitted");
}

public static void cancel() {


System.out.println("Your application is cancelled");
}

public static void main(String[] args) {


submit();
RailwayForm heroForm = new RailwayForm();
heroForm.fill("Hero");
}
}

Example 3:

class RailwayForm {
fill(name, trainno) {
this.fullname = name;
this.trainNo = trainno;
console.log(
"mr " + this.fullname + " your train number is " + this.trainNo
);
}

37
Ameerpet technologies

submit() {
console.log(this.fullname + " your form submited successfully");
}
cancel() {
console.log(this.fullname + "your form cancelled successfully");
}
}
const heroForm = new RailwayForm();
heroForm.fill("Hero", 12345);
heroForm.submit();
heroForm.cancel();

//if I forgot to fill the form –it will display undefined name, undefined trainno , just comment out calling
or invoking fill()

Same Code in Java:

public class RailwayForm {


private String fullname;
private int trainNo;

public void fill(String name, int trainno) {


this.fullname = name;
this.trainNo = trainno;
System.out.println("Mr " + this.fullname + ", your train number is " + this.trainNo);
}

public void submit() {


System.out.println(this.fullname + ", your form submitted successfully");
}

public void cancel() {


System.out.println(this.trainNo + ", your form cancelled successfully");
}

public static void main(String[] args) {


RailwayForm heroForm = new RailwayForm();
heroForm.fill("Hero", 12345);
heroForm.submit();
}
}

38
Ameerpet technologies

JavaScriptDay-7
Constructor():-

 we create object to class using “new ” operator


 ”new ” operator allocates memory to variables
 To provide initial values to variables we use constructor
 A constructor in JavaScript is a special function used to create and initialize objects.
 It's called with the new keyword to create instances of a particular object type, allowing you to
set initial properties and behaviors for those objects.
 Constructors are commonly used for defining and creating multiple objects of the same type,
ensuring consistent object structures and behavior.

Example1:-

class RailwayForm{
constructor(){
console.log("i am constructor");
}
}
new RailwayForm;
new RailwayForm;
//or
let heroform1=new RailwayForm;
let heroform2=new RailwayForm;

output:
i am constructor
i am constructor
i am constructor
i am constructor

Example2:-

class RailwayForm{
fill(gname,train_no){
this.name=gname;
this.trainNo=train_no;
console.log("mr "+this.name+" your ticket with id "+this.trainNo+" is successfully Filled");

}
submit(){
console.log("mr "+this.name+" your ticket with id "+this.trainNo+" is successfully booked");
}
cancel(){

39
Ameerpet technologies

console.log("mr "+this.name+" your ticket with id "+this.trainNo+" is successfully cancelled");


}
}

let heroform1=new RailwayForm;


heroform1.fill("hero",12345);
heroform1.submit();
heroform1.cancel();
output:
mr hero your ticket with id 12345 is successfully Filled
mr hero your ticket with id 12345 is successfully booked
mr hero your ticket with id 12345 is successfully cancelled
(or)
if I comment out fill method or I stopped to explicitly pass variables
let heroform1=new RailwayForm;
// heroform1.fill("hero",12345);
heroform1.submit();
heroform1.cancel();
output:
mr undefined your ticket with id undefined is successfully booked
mr undefined your ticket with id undefined is successfully cancelled

//removing fill method and adding constructor in place of fill method so that i need not to call or
initialise values explicitily

class RailwayForm{
constructor(gname,train_no){
this.name=gname;
this.trainNo=train_no;
}
submit(){
console.log("mr "+this.name+" your ticket with id "+this.trainNo+" is successfully booked");
}
cancel(){
console.log("mr "+this.name+" your ticket with id "+this.trainNo+" is successfully cancelled");
}
}

let heroform1=new RailwayForm("hero",12345);


// heroform1.fill("hero",12345);
heroform1.submit();
heroform1.cancel();

output:

40
Ameerpet technologies

mr Hero your ticket with id 12345 is successfully booked

mr Hero your ticket with id 12345 is successfully cancelled

Define class,create object and access data:

class Person{
constructor(goodname,graduation,vill){
this.name=goodname;
this.qualification=graduation;
this.myvill=vill;
}
greet(){
console.log("good morning mr "+this.name);
}
mydetails(){
console.log("my name is "+this.name+" i have completed "+this.qualification+" and i am from "+this.myvill)
}
}
let hero=new person("Hero","btech","ameerpet");
hero.greet();
hero.mydetails();

output:
good morning mr Hero
my name is Hero i have completed btech and i am from Ameerpet

Class field declarations(or ) Class properties:

 This syntax allows you to define class properties directly within the class body without the need
for a constructor function to initialize them.
 This is commonly referred to as "class field declarations" or "class properties."

 The newer class field declaration syntax is considered more readable and less error-
prone because you don't need to repeat the property names within the constructor.
 The properties are automatically initialized with undefined, and you can then assign
values to them in the constructor, making your code shorter and more concise.

Java code:

public class Person {


private String name;
private int age;

41
Ameerpet technologies

public Person(String nm, int ag) {


this.name = nm;
this.age = ag;
}

public void greet() {


System.out.println("Hello, my name is " + this.name);
System.out.println("I am " + this.age + " years old");
}

public static void main(String[] args) {


Person p = new Person("Raju", 21);
p.greet();
}
}

C# code:

using System;

public class Person


{
private string name;
private int age;

public Person(string nm, int ag)


{
this.name = nm;
this.age = ag;
}

public void Greet()


{
Console.WriteLine("Hello, my name is " + this.name);
Console.WriteLine("I am " + this.age + " years old");
}

public static void Main()


{
Person p = new Person("Raju", 21);
p.Greet();
}
}

42
Ameerpet technologies

Javascript code

class Person {
name; //var ,let and const variable before name is not supported
age; // v ar ,let and const variable before age is not supported
constructor(gname, age) {
this.name = gname;
this.myage = age;
}
introduction() {
console.log(
"my name is " + this.name + " and i am " + this.myage + " years old"
);
}
}
const person = new Person("Hero", 21);
person.introduction();

 The var keyword is typically used for declaring variables in a function scope and is not used
within class declarations for defining instance variables.
 In this code, name and age are declared as instance variables directly within the class, and they
are initialized within the constructor. Using var to declare them is unnecessary and not a
standard practice in modern JavaScript class definitions.

Template literals:-

 Template literals, often referred to as template strings, are a feature introduced in


ECMAScript 6 (ES6), which is a version of JavaScript released in 2015.
 Template literals allow you to create strings that can span multiple lines and include
expressions inside them, making string interpolation and formatting more convenient
and readable.

Here's the basic syntax of a template literal:

const greeting = `Hello, World!`;

Key features of template literals:

1. Multiline Strings: You can create multiline strings without the need for explicit line
breaks.

43
Ameerpet technologies

const multilineText = `
This is a
multiline
string.`;

· String Interpolation: You can embed expressions or variables directly inside a template literal
using ${}.

const name = "Alice";


const greeting = `Hello, ${name}!`;

· Expression Evaluation: Expressions within ${} are evaluated, and their results are
concatenated into the string.

const x = 10;
const y = 20;
const result = `The sum of ${x} and ${y} is ${x + y}.`;

· Nested Template Literals: You can nest template literals within each other.

const greeting = `Hello, ${`World`}!`;


class Person {
name;
age;
constructor(nm, ag) {
this.name = nm;
this.age = ag;
}
greet() {
console.log(
"my name is " + this.name + "and i am " + this.age + " years old "
);
console.log(`my name is ${this.name} and i am ${this.age} years old`);
}
}
const p = new Person("Raju", 21);
p.greet();

JavaScriptDay-8
this keyword:

 this in JavaScript refers to the current object or context.


 It's used to access or modify properties and methods within that context.

44
Ameerpet technologies

 Typically employed in methods of objects or constructors to reference instance


members.
 Enables dynamic handling of object data and context-specific operations.
 Its value may change depending on how a function is invoked.

super keyword:

 super in JavaScript is used in classes to access parent class properties and methods.
 It's particularly useful when overriding methods in a subclass while maintaining access
to the parent's functionality.
 In constructors, super calls the constructor of the parent class.
 Supports hierarchical class structures and code organization in object-oriented
programming.
 Enhances code reusability and maintains a clear separation of concerns.

Prototype-based -Inheritence(Es5)

// Parent constructor function


function Animal(name) {
this.name = name;
}

// Adding a method to the prototype of Animal


Animal.prototype.sayHello = function() {
console.log("Hello, I'm " + this.name);
};

// Child constructor function inheriting from Animal


function Dog(name, breed) {
// Call the parent constructor
Animal.call(this, name);

// Additional property specific to Dog


this.breed = breed;
}

// Set up prototype chain (inheritance)


Dog.prototype = Object.create(Animal.prototype);

// Adding a method specific to Dog


Dog.prototype.bark = function() {
console.log("Woof! Woof!");
};

// Create instances

45
Ameerpet technologies

var myAnimal = new Animal("Generic Animal");


var myDog = new Dog("Buddy", "Labrador");

// Test the inheritance


myAnimal.sayHello(); // Output: Hello, I'm Generic Animal
myDog.sayHello(); // Output: Hello, I'm Buddy
myDog.bark(); // Output: Woof! Woof!

Class based inheritance:-

 Inheritance in JavaScirpt is a mechanism in which one object acquires all the properties
and behaviors of a parent object.
 The idea behind inheritance is that you can create new classes that are built upon
existing classes.
 When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.

Example1:

class Animal {
fname;
constructor(name) {
this.fname = name;
}
sayHello() {
console.log(`i m ${this.fname}`);
}
}

class Dog extends Animal{


name;
breed;
constructor(name,breed){
super(name);
this.name=name;
this.breed=breed;
}s
barking(){
console.log(`i m a ${this.name} and im a ${this.breed} i'll bark whof whof`);
}
}

46
Ameerpet technologies

let dog=new Dog("Chintu","StreetDog");


let animal=new Animal("Puppy");
animal.sayHello();
dog.sayHello();
dog.barking();

Example2:-

class Vehicle{
model;
made;
year;
constructor(model,made,year){
this.model=model;
this.made=made;
this.year=year;

}
launching(){
console.log(`${this.model} is made in ${this.made } is going to launch in the
year of ${this.year}`)
}
stopping(){
console.log(`due to some reasons ${this.model} is going to shutdown in
${this.year}`);
}
}
class Car extends Vehicle{
modifying(){
console.log("Modification of the car is completed");

}
stopping(){
console.log(`${this.model} is NOT going to stop its Production`);
}
}
let c=new Car("Toyota","india",2032);
let v=new Vehicle("Nano","india",2013);
c.launching();
c.stopping();
v.launching();
v.stopping();

Example2

47
Ameerpet technologies

class Vehicle{
model;
made;
year;
constructor(model,made,year){
this.model=model;
this.made=made;
this.year=year;

}
launching(){
console.log(`${this.model} is made in ${this.made } is going to launch in the
year of ${this.year}`)
}
stopping(){
console.log(`due to some reasons ${this.model} is going to shutdown in
${this.year}`);
}
}
class Car extends Vehicle{
constructor(model,made,year){
super(model,made,year)
}
modifying(){
console.log("Modification of the car is completed");

}
stopping(){
super.launching();
console.log(`${this.model} is NOT going to stop its Production`);
}

}
let c=new Car("Toyota","india",2032);
let v=new Vehicle("Nano","india",2013);
// c.launching();
c.stopping();
// v.launching();
// v.stopping();

Encapsulation: Encapsulation is a fundamental concept in object-oriented programming where the


internal state of an object is hidden from external access, and access to that state is controlled through
well-defined methods.

48
Ameerpet technologies

 It helps ensure data integrity, improves code maintainability, and allows for better control over
an object's behavior.

class Person {
#name; // Private field for storing name
#age; // Private field for storing age

constructor(name, age) {
this.#name = name;
this.#age = age;
}

// Getter method for name


getName() {
return this.#name;
}

// Setter method for name


setName(newName) {
this.#name = newName;
}

// Getter method for age


getAge() {
return this.#age;
}

// Setter method for age


setAge(newAge) {
this.#age = newAge;
}
}

const person = new Person('Alice', 30);

console.log(person.getName()); // Get name: Alice


console.log(person.getAge()); // Get age: 30

person.setName('Bob'); // Set name to 'Bob'


person.setAge(25); // Set age to 25

console.log(person.getName()); // Get name: Bob


console.log(person.getAge()); // Get age: 25

49
Ameerpet technologies

JavaScriptDay-9
Encapsulation continuation:
Example 2:

class Bankaccount{
#accountnumber;
#balance;
constructor(accountnumber,balance){
this.#accountnumber=accountnumber;
this.#balance=balance;
}
getAccountNumber(){
return this.#accountnumber;
}
setAccountNumber(accountnumber){
this.#accountnumber=accountnumber;
}
getBalance(){
return this.#balance;
}
setBalance(balance){
this.#balance=balance;
}

}
let ac=new Bankaccount(12345,"5000");
console.log(ac.getAccountNumber(),ac.getBalance() );
ac.setAccountNumber(998776);
ac.setBalance(25000);
console.log(ac.getAccountNumber(),ac.getBalance() );

Example 3:

class Bankaccount{
#accountnumber;
#balance;
constructor(accountnumber,balance){
this.#accountnumber=accountnumber;
this.#balance=balance;
}
getAccountNumber(){
return this.#accountnumber;

50
Ameerpet technologies

getBalance(){
return this.#balance;
}
deposit(amount){
if(amount>0){
this.#balance=this.#balance+amount;
console.log(`deposited amount: ${amount}, new Balance: ${this.#balance}`);

}
else{
console.log("Enter correct amount ,values cannot be in negative");
}
}
withdraw(amount){
if(amount>0){
this.#balance=this.#balance-amount;
console.log(`debited amount :${amount}, new Balance: ${this.#balance}`);
}
}

}
let ac=new Bankaccount(12345,5000);
console.log(ac.getAccountNumber(),ac.getBalance() );
ac.withdraw(500);
ac.deposit(4000);

Abstraction:-
An abstraction is a way of hiding the implementation details and showing only the functionality to the
users. In other words, it ignores the irrelevant details and shows only the required one.

Example1:-

class Shape {
// Abstract method for calculating area (must be implemented by subclasses)
calculateArea() {
throw new Error("Abstract method 'calculateArea' must be implemented.");
}
}

class Circle extends Shape {

51
Ameerpet technologies

constructor(radius) {
super();
this.Radius = radius;
}

// Implementing the abstract method to calculate the area of a circle


calculateArea() {
const approximatePi = 3.14159265359;
const area = approximatePi * this.Radius * this.Radius;
console.log(`The area of the circle is: ${area}`);
}
}

// Usage
const circle = new Circle(5);
circle.calculateArea(); // Outputs the area of the circle

Example2:-

class Shape {
constructor(name) {
this.name = name;
}

// Abstract method to calculate area


calculateArea() {
throw new Error("This method must be implemented by subclasses");
}
}

class Circle extends Shape {


constructor(radius) {
super("Circle");
this.radius = radius;
}

// Implementing the abstract method for Circle


calculateArea() {
return Math.PI * this.radius * this.radius;
}
}

class Square extends Shape {


constructor(sideLength) {
super("Square");

52
Ameerpet technologies

this.sideLength = sideLength;
}

// Implementing the abstract method for Square


calculateArea() {
return this.sideLength * this.sideLength;
}
}

const circle = new Circle(5);


const square = new Square(4);

console.log(`Area of ${circle.name}: ${circle.calculateArea()}`);


console.log(`Area of ${square.name}: ${square.calculateArea()}`);

Polymorphism:

 In JavaScript, polymorphism allows objects to be used interchangeably based on a


shared interface.
 Runtime polymorphism is achieved through method overriding, where different objects
share the same method name and signature but provide their own implementation.
 Compile-time polymorphism, such as method overloading, is less explicit in JavaScript
and can be simulated through conditional statements inside functions.

// Compile-time polymorphism (Method Overloading)


class MathOperations {
static add(x, y) {
return x + y;
}

static add(x, y, z) {
return x + y + z;
}
}

console.log(MathOperations.add(2, 3)); // Output: NaN (due to method


overloading not being supported)

// Runtime polymorphism (Method Overriding)


class Animal {
makeSound() {
console.log("Generic animal sound");
}
}

53
Ameerpet technologies

class Dog extends Animal {


makeSound() {
console.log("Woof! Woof!");
}
}

class Cat extends Animal {


makeSound() {
console.log("Meow!");
}
}

// Example of runtime polymorphism


const dog = new Dog();
const cat = new Cat();

dog.makeSound(); // Output: Woof! Woof!


cat.makeSound(); // Output: Meow!

JavaScriptDay-10
“Here I'm explaining arrays in Java because I want to compare them with JavaScript. This will be
useful for teaching arrays in our future JavaScript class”.

Arrays:
 An array in Java is a fixed-size, ordered collection of elements of the same data type.
 It provides indexed access to its elements, making it easy to store and manipulate
multiple values of the same kind in a single variable.
 Arrays are efficient for sequential and random access, but their size is predetermined
and cannot change dynamically.
 They are a fundamental data structure used to organize and work with data efficiently in
Java

import java.util.Arrays;

Difference between primitive data type and Array :

 Arrays in Java are data structures used to store multiple elements of the same data
type.

54
Ameerpet technologies

 They have a fixed size determined upon creation and allocate memory for all elements
in a contiguous block.
 Arrays of reference types have elements initialized to null by default.
 Primitive data types, on the other hand, store individual values such as integers or
booleans. They do not require explicit initialization and have default values if not
assigned.
 Primitive data types are used for basic data storage and calculations, while arrays are
used for managing collections of elements efficiently.

Program to display Default values of each type of Array:

public class NewArrays{


public static void main(String[] args) {
int[] intArr= new int[5];
String[] strArr= new String[5];
char[] charArr=new char[5];
boolean[] boolArr=new boolean[5];

System.out.println("default values of integer


Array:"+Arrays.toString(intArr));
System.out.println("default values of String
Array:"+Arrays.toString(strArr));
System.out.println("default values of Character
Array:"+Arrays.toString(charArr));
System.out.println("default values of Boolean
Array:"+Arrays.toString(boolArr));

}
}

Creation of array with values:


To create integer,char,boolean,string arrays And their length:

public class NewArrays{


public static void main(String[] args) {
int[] intArr= {1,2,3,4};
String[] strArr= {"Hero1","Hero2","Hero3","Hero4","Hero5","Hero6"};
char[] charArr= {'a','b','c','1','$'};
boolean[] boolArr= {true,false,false};

System.out.println("Length of integer Array:"+intArr.length);


System.out.println("Length of String Array:"+strArr.length);
System.out.println("Length of Character Array:"+charArr.length);

55
Ameerpet technologies

System.out.println("Length of Boolean Array:"+boolArr.length);

}
}

Program to print first element of array:

public class NewArrays{


public static void main(String[] args) {
int[] intArr= {1,2,3,4};
String[] strArr= {"Hero1","Hero2","Hero3","Hero4","Hero5","Hero6"};
char[] charArr= {'a','b','c','1','$'};
boolean[] boolArr= {true,false,false};

System.out.println("First Element of integer Array : "+intArr[0]);


System.out.println("First Element of String Array : "+strArr[0]);
System.out.println("First Element of Character Array : "+charArr[0]);
System.out.println("First Element of Boolean Array : "+boolArr[0]);

}
}

Program to print last element of array:

public class NewArrays{


public static void main(String[] args) {
int[] intArr= {1,2,3,4};
String[] strArr= {"Hero1","Hero2","Hero3","Hero4","Hero5","Hero6"};
char[] charArr= {'a','b','c','1','$'};
boolean[] boolArr= {true,false,false};

int lastInt=intArr[intArr.length-1];
String lastStr=strArr[strArr.length-1];
char lastChar=charArr[charArr.length-1];
boolean lastBool=boolArr[boolArr.length-1];
System.out.println("First Element of integer Array : "+lastInt);
System.out.println("First Element of String Array : "+lastStr);
System.out.println("First Element of Character Array : "+lastChar);
System.out.println("First Element of Boolean Array : "+lastBool);

}
}

56
Ameerpet technologies

Program to check whether the first element of array is even or not

public class NewArrays {


public static void main(String[] args) {
int[] intArr = { 24, 2, 3, 4 };
int n = intArr[0];
if(n%2==0)
{
System.out.println("First number ("+n+") of Array is Even");
}
else {
System.out.println("Fisrt number("+n+") of Array is not Even");
}
}
}

Last number of Array is prime or not

public class NewArrays {


public static void main(String[] args) {
int[] intArr = { 24, 2, 3, 4 ,7};
int n = intArr[intArr.length - 1];

int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
}
if (count == 2) {
System.out.println("The last number of array is Prime");
} else {
System.out.println("The last number of array is not Prime");
}
}
}

Program for Printing the Array Elements:

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };
int[] arr2 = { 3, 5, 1, 4 };
System.out.println(arr1); // [I@5a07e868

57
Ameerpet technologies

System.out.println(arr2);// [I@76ed5528

System.out.println("First Array");
for (int i = 0; i <= arr1.length - 1; i++) {
System.out.print(arr1[i] + " "+"\n");
}
System.out.println("Second Array");
for(int i=0;i<=arr2.length-1;i++) {
System.out.println(arr2[i]);
}

}
}

Printing array values in Reverse order:

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };

System.out.println("Printing the Array in Reverse Order");


for (int i = arr1.length - 1; i >= 0; i--) {
System.out.print(arr1[i] + " " + "\n");
}

}
}

Program to find the Sum of Total values of array

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };

int sum=0;
for(int i=0;i<=arr1.length-1;i++) {
sum=sum+arr1[i];
}

System.out.println("the Sum of total values of array is :"+sum);

}
}

Program to print Only even numbers of array:-

58
Ameerpet technologies

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };

System.out.println("Even Numbers of The Array");


for (int i = 0; i <= arr1.length - 1; i++) {

if (arr1[i] % 2 == 0) {
System.out.println(arr1[i]);
}
}

}
}

Foreach loop:-

 Foreach (enhanced for) loops simplify array and collection iteration.


 They enhance code readability and reduce off-by-one errors.
 You can't modify elements during iteration.
 Best suited for straightforward read-only iterations.
 Commonly used for arrays and collections.

Program to Print Array Elements using ForEachLoop;

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };

for(int currentElement:arr1) {
System.out.println(currentElement);
}
}
}

Sum of the values of the array

public class NewArrays {


public static void main(String[] args) {
int[] arr1 = { 24, 2, 3, 4, 7 };
int sum = 0;
for (int currentElement : arr1) {

sum = sum + currentElement;

59
Ameerpet technologies

System.out.println("Sum of total Element in the array "+sum);


}
}

Again Creating Empty Array and checking their default values By using For Each Loop

public class NewArrays {


public static void main(String[] args) {

int[] arr = new int[5];


String[] strArray = new String[6];
boolean[] booleanArray = new boolean[3];
char[] chArray = new char[4];
System.out.println("Integer Array Default values");
for (int i = 0; i <= arr.length - 1; i++) {
System.out.println(arr[i]);

}
System.out.println("String Array Default values");
for (String x : strArray) {
System.out.println(x);

}
System.out.println("Boolean Array Default values");
for (boolean b : booleanArray) {
System.out.println(b);

}
System.out.println("char Array default values");
for (char c : chArray) {
// System.out.print(c+","); //char returns empty values to check try this
System.out.println(c);
}

}
}

Coping one Array Elements into another array

public class NewArrays {


public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int[] newArray = new int[arr.length];

60
Ameerpet technologies

// to copy old array elements to new array elements


for (int i = 0; i <= newArray.length - 1; i++) {
newArray[i] = arr[i];
}

System.out.println("New Array Elements Are");


// printing new Array Elements
for (int x : newArray) {
System.out.println(x);
}

}
}

We cannot add or delete anything from the existing array because it is fixed in size(length) if you want
to modify anything of the existing array then you have to take a new array and copy this elements to
that array and you can do your operations

JavaScriptDay-11
Arrays: In JavaScript, an array is a data structure that stores an ordered collection of values, each
associated with a numeric index.

 Arrays can contain elements of varying data types and are dynamically resizable, allowing for the
addition and removal of elements.
 They provide built-in methods and properties for easy manipulation, iteration, and retrieval of
data.
 Arrays are commonly used for organizing and managing data, making them a fundamental data
structure in JavaScript and many other programming languages.

Syntax of Array normal Array


let fruits=["apple","banana","orange","grapes","watermelon","pineapple"];

Accessing first element of Array:


console.log(fruits[0]);

Last Element of the Array


console.log(fruits[fruits.length-1]);

Numbers Array
let myArray = [1, 2, 3, 4, 5];
let lastIndex = myArray.length - 1;
let lastElement = myArray[lastIndex];

61
Ameerpet technologies

console.log(lastElement); // Outputs: 5 (the last element)

Syntax of Mixed Array

let mixedArray=[1,"hero",2.5,true];
console.log(mixedArray[0]);
console.log(mixedArray[mixedArray.length-1]);

For Loop: The traditional for loop is a versatile loop that allows you to iterate over elements in an array
using an index variable. It is often used when you need to control the loop's behavior manually.

let fruits=["apple","banana","orange","grapes","watermelon","pineapple"];

for(var i=0;i<=fruits.length-1;i++){
console.log(fruits[i]);
}

For...of Loop: The for...of loop is a more modern and concise way to iterate over the values of an array
without needing an explicit index variable. It simplifies the code and makes it more readable .

let fruits = ['apple', 'banana', 'cherry'];

for(let x of fruits){
console.log(x);
}

This loop directly iterates over the elements (values) in the fruits array, and you don't need to manage
an index variable. It's especially useful when you want to focus on the values themselves.

For...in Loop: The for...in loop is not recommended for iterating over arrays. It is primarily used
for iterating over the properties of objects. When used with arrays, it iterates over the
enumerable properties, including array elements, but it's not as suitable or predictable as for or
for...of loops for this purpose.

let fruits = ['apple', 'banana', 'cherry'];

for (let index in fruits) {


console.log(fruits[index]);

62
Ameerpet technologies

Array Methods:

1. push(): Adds one or more elements to the end of an array.

let numbers = [1, 2, 3];

numbers.push(4);

console.log(numbers); // Output: [1, 2, 3, 4]

2. pop(): Removes and returns the last element from an array.


let colors = ["red", "green", "blue"];

let lastColor = colors.pop();


console.log(lastColor); // Output: 'blue'
console.log(colors); // Output: ['red', 'green']

3. shift(): Removes and returns the first element from an array, shifting all other elements
to a lower index.

let daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'];

let firstDay = daysOfWeek.shift();


console.log(firstDay); // Output: 'Monday'
console.log(daysOfWeek); // Output: ['Tuesday', 'Wednesday', 'Thursday']

4. unshift(): Adds one or more elements to the beginning of an array, shifting existing
elements to higher indices.

let animals = ["lion", "tiger", "leopard"];

animals.unshift("cheetah", "panther");

console.log(animals); // Output: ['cheetah', 'panther', 'lion', 'tiger',


'leopard']

5. splice(): Adds or removes elements from a specific position in an array.

63
Ameerpet technologies

array.splice(start, deleteCount, item1, item2, ...);

let cars = ['Toyota', 'Honda', 'Ford', 'Chevrolet'];


// Remove 'Ford' and 'Chevrolet' and add 'Nissan', 'BMW' at index 2
let removedCars = cars.splice(2, 2, 'Nissan', 'BMW');

console.log(removedCars); // Output: ['Ford', 'Chevrolet']


console.log(cars); // Output: ['Toyota', 'Honda', 'Nissan', 'BMW']

6.indexOf(): Returns the index of the first occurrence of a specified element in an array.

let fruits = ['apple', 'banana', 'cherry', 'banana'];

let bananaIndex = fruits.indexOf('banana');

console.log(bananaIndex); // Output: 1

7.lastIndexOf(): Returns the index of the last occurrence of a specified element in an array.

let fruits = ['apple', 'banana', 'cherry', 'banana'];

let lastBananaIndex = fruits.lastIndexOf('banana');

console.log(lastBananaIndex); // Output: 3

8 .reverse(): Reverses the order of elements in an array.

let numbers = [1, 2, 3, 4, 5];

numbers.reverse();

console.log(numbers); // Output: [5, 4, 3, 2, 1]

9.sort(): Sorts the elements of an array in place, based on a provided sorting function.

let fruits = ['banana', 'apple', 'cherry'];

fruits.sort();

console.log(fruits); // Output: ['apple', 'banana', 'cherry']

64
Ameerpet technologies

10.isArray(): Checks if a given value is an array.

let array1 = [1, 2, 3];


let string1 = 'Hello, world!';

console.log(Array.isArray(array1)); // Output: true


console.log(Array.isArray(string1)); // Output: false

11 concat(): Combines two or more arrays to create a new array.

let arr1 = [1, 2, 3];


let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];

let combinedArray = arr1.concat(arr2, arr3);

console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

12 join(): Converts all elements of an array into a string and concatenates them, separated by a
specified delimiter.

let fruits = ['apple', 'banana', 'cherry'];

let joinedString = fruits.join(', ');

console.log(joinedString); // Output: 'apple, banana, cherry'

13.slice(): Creates a new array by extracting a portion of an existing array.

let numbers = [1, 2, 3, 4, 5];

let slicedArray = numbers.slice(1, 4);

console.log(slicedArray); // Output: [2, 3, 4]

65
Ameerpet technologies

The slice method is used to extract elements from the numbers array starting from index 1
(inclusive) up to, but not including, index 4 (exclusive), creating a new array slicedArray.

JavaScriptDay-12

In JavaScript, Date and Math are built-in objects that provide functionalities related to date and
mathematical operations, respectively.

Create a new date:


const currentdate=new Date();

Get specific date components (year, month, day, etc.):


1. getDate(): it will print todays date (ex:25)
const currentdate=new Date();
const date=currentdate.getDate();
console.log(date); //output:25

2. getFullYear(): it returns present year (ex:2024)


const currentdate=new Date();
const year=currentdate.getFullYear();
console.log(year); //output:2024

3. getMonth(): it will return current month but its index starts with 0(zero) so we have to add 1
to this method so that it will return current month
const currentdate = new Date();
const month = currentdate.getMonth();
const currentMonth = currentdate.getMonth() + 1;
console.log(month); //output:0
console.log(currentMonth); //output:1

4. After above operations or tasks tr y the following:


Print Today’s Full Date(date/month/year):
const currentdate = new Date();
const date = currentdate.getDate();
const year = currentdate.getFullYear();
const currentMonth = currentdate.getMonth() + 1;
console.log(`year:${year} month:${currentMonth} date:${date}`); //output:
year:2024 month:1 date:25
5. getHours():it return in 24 hrs format

const currentdate = new Date();

66
Ameerpet technologies

let hours=currentdate.getHours();
console.log(hours); //output: 1

6. getMinutes(): it return current Minutes


const currentdate = new Date();
let minutes=currentdate.getMinutes();
console.log(minutes);//output:45

7. getSeconds(): it returns current Seconds


const currentdate = new Date();
let seconds=currentdate.getSeconds();
console.log(seconds); //output:50
8. getMilliSeconds(): it returns current MilliSeconds
const currentdate = new Date();
let milliseconds=currentdate.getMilliseconds();
console.log(milliseconds);//output:941

9. toDateString();
const currentdate = new Date();
console.log(currentdate.toDateString()); //output:Thu Jan 25 2024
10. toLocaleDateString():
const currentdate = new Date();
console.log(currentdate.toLocaleDateString()); //output:1/25/2024
11. The Date Object values
const currentdate = new Date();
console.log(currentdate); //Thu Jan 25 2024 01:12:47 GMT+0530 (India
Standard Time)

Extra INFO:

No arguments: new Date() creates a Date object representing the current date and time.
String argument: new Date('YYYY-MM-DDTHH:mm:ss') creates a Date object for the specified
date and time.
Separate arguments: new Date(year, month, day, hours, minutes, seconds, milliseconds) creates a
Date object with the specified components.
const currentdate = new Date(2028, 4, 21, 24, 12, 47); // (year, month, day,
hour, min, second)
console.log(currentdate); // Mon May 22 2028 00:12:47 GMT+0530 (India Standard
Time)
console.log(currentdate.getMonth()); // 4
console.log(currentdate.getFullYear()); //2028
console.log(currentdate.getDate());// 1

67
Ameerpet technologies

Math:
sqrt(number):Calculates the square root of a number:

const number = 16;


const squareRoot = Math.sqrt(number);
console.log(squareRoot);//output :4

random():Generate a random number between 0 and 1:

const randomNumber = Math.random();


console.log(randomNumber);//Output (varies each time you run the code):
// 0.12345678901234567 (for example)

round(decimalNumber):Round a number to the nearest integer:

const decimalNumber1 = 3.75;


const decimalNumber2 =3.27;
const roundedNumber1 = Math.round(decimalNumber1);
const roundedNumber2 =Math.round(decimalNumber2);

console.log(roundedNumber1);// Output: 4
console.log(roundedNumber2);// output: 3

floor(decimalNumber): gives the base number of the decimal value;

const decimalNumber1 = 3.75;


const decimalNumber2 =3.27;
const flooredNumber1 = Math.floor(decimalNumber1);
const flooredNumber2 =Math.floor(decimalNumber2);

console.log(flooredNumber1);// Output: 3
console.log(flooredNumber2);// output: 3

ceil(decimalNumber): gives the base ceil(top most) number of the decimal value;

const decimalNumber1 = 3.75;


const decimalNumber2 =3.27;

68
Ameerpet technologies

const ceilNumber1 = Math.ceil(decimalNumber1);


const ceilNumber2 =Math.ceil(decimalNumber2);

console.log(ceilNumber1);// Output: 3
console.log(ceilNumber2);// output: 3

Math.min(): gives the smallest element from the given numbers:

const minValue = Math.min(10, 5, 20, 3, 8); //returns smallest of the given


params
console.log(minValue); // Output: 3

Math.max():

const maxNumber = Math.max(10, 30, 50, 80, 60); //returns the maximum valoe of
the given numbers
console.log(maxNumber); // Output: 80

Math.pow():

const base = 2;
const exponent = 3;
// Calculate 2^3 (2 raised to the power of 3)
const result = Math.pow(base, exponent);
console.log(result); // Output: 8

Date Example:

// Create a new Date object

const currentDate = new Date();

// Get various components of the date

const year = currentDate.getFullYear();

const month = currentDate.getMonth(); // 0-based (0 = January, 1 = February, etc.)

const day = currentDate.getDate();

const hours = currentDate.getHours();

const minutes = currentDate.getMinutes();

69
Ameerpet technologies

const seconds = currentDate.getSeconds();

const milliseconds = currentDate.getMilliseconds();

const dayOfWeek = currentDate.getDay(); // 0-based (0 = Sunday, 1 = Monday, etc.)

// Display the current date and time

console.log("Current Date:", currentDate);

// Display individual date components

console.log("Year:", year);

console.log("Month:", month + 1); // Adding 1 to the month since it's 0-based

console.log("Day:", day);

console.log("Hours:", hours);

console.log("Minutes:", minutes);

console.log("Seconds:", seconds);

console.log("Milliseconds:", milliseconds);

console.log("Day of the Week:", getDayName(dayOfWeek));

// Helper function to get the day name based on the day of the week

function getDayName(dayOfWeek) {

const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

return daysOfWeek[dayOfWeek];

Math Example:

// Math.min() and Math.max()

const num1 = 10;

const num2 = 30;

const num3 = 50;

const num4 = 80;

const num5 = 60;

70
Ameerpet technologies

const minNumber = Math.min(num1, num2, num3, num4, num5);

const maxNumber = Math.max(num1, num2, num3, num4, num5);

console.log("Minimum Number:", minNumber); // Output: 10

console.log("Maximum Number:", maxNumber); // Output: 80

// Math.sqrt()

const numberToSquareRoot = 25;

const squareRoot = Math.sqrt(numberToSquareRoot);

console.log("Square Root of", numberToSquareRoot, "is", squareRoot); // Output: 5

// Math.random()

const randomValue = Math.random();

console.log("Random Value between 0 and 1:", randomValue); // Output: A random number between 0
and 1

// Rounding methods

const decimalNumber = 3.75;

const roundedNumber = Math.round(decimalNumber);

const floorNumber = Math.floor(decimalNumber);

const ceilNumber = Math.ceil(decimalNumber);

console.log("Rounded Number:", roundedNumber); // Output: 4 but in this case if value is 3.2 it will
return 3 and if value is 3.8 it return 4

console.log("Floor Number:", floorNumber); // Output: 3

console.log("Ceil Number:", ceilNumber); // Output: 4 suppose if value 3.2 or 3.8 it will return 4 only

JavaScriptDay-13
71
Ameerpet technologies

Call By Value:- Calling a Function by passing a primitive value is called as Call By Value.
 “Call by value" is a method of passing arguments to functions in programming languages.
 In a "call by value" approach, the value of the argument, typically a variable or a constant, is
passed to the function as a parameter.
 This means that the function receives a copy of the argument's value, and any modifications
made to the parameter inside the funct ion do not affect the original argument outside the
function.
 It is commonly used for primitive data types, such as numbers, strings, and booleans.

Following ex is to understand the concept in easy way

let a=10;
let b=a;
b=b+10;
console.log(b); //20
console.log(a); //10
Example1:
function test(x) {
x = x + 200;
console.log(` x value inside function after modification x = ${x}`);
}
let x = 100;
test(x);
console.log(` x value outside function after callByValue x = ${x}`); //here the value is unchanged

Example2:

function stringCallby(message){
message=" i am not Zero,i am a hero";
console.log(`here the message is ${message}`) //value modified here
}
let message="zero";
stringCallby(message);
console.log(`here the message is ${message}`); //value is unchanged

Call By Reference:- Calling a function by passing a reference value is called Call By Reference.

 In a "call by reference" approach, instead of passing a copy of the argument's value, a reference
to the original data is passed to the function as a parameter.
 This means the function can directly access and modify the original data, and any changes made
to the parameter inside the function are reflected in the original argument outside the function.

72
Ameerpet technologies

let a = [10, 20, 30, 40];


let b = a;

a.push(25);
a.unshift(121);
console.log(a); // this is very common //output :[ 121, 10, 20, 30, 40, 25 ]
console.log(b); // but for the change //output: [ 121, 10, 20, 30, 40, 25 ]

Example1:

function test(arr){
arr.push(21);
arr.unshift(32);
console.log(arr);
}
let arr=[10,20,30,40];
test(arr); // [ 32, 10, 20, 30, 40, 21 ]
console.log(arr);// [ 32, 10, 20, 30, 40, 21 ]

Example2:

function Test(Person1) {
Person1.name = "Zero";
console.log(Person1);
}
const Person = {
name: "Hero",
age: 21,
gender: "male",
};
Test(Person); //output :{name: 'Zero', age: 21, gender: 'male'}
console.log(Person); //output:{name: 'Zero', age: 21, gender: 'male'}

Difference Between callByValue and callByReference

callByValue callByReference

A copy of actual arguments is Address of actual arguments is


passed to formal arguments passed to formal arguments
Actual arguments remain safe; not modified Changes to actual arguments are possible,
accidentally handle with care
Address of actual and formal arguments are Address of actual and formal arguments are
different the same

73
Ameerpet technologies

Changes inside the function do not reflect Changes inside the function are reflected
outside outside as well

Spread Operator(...):-

 The spread operator (...) in JavaScript is a relatively recent addition to the language,
introduced in ECMAScript 2015 (ES6).
 It is a versatile feature that is used to "spread" or unpack elements from arrays, objects,
or iterable objects (like strings) into other arrays, objects, or function arguments.

Why it was introduced ?

 The spread operator was introduced to enhance the flexibility and expressiveness of
JavaScript when working with arrays, objects, and function arguments.

Now, if we store it in another variable and modify that variable, it won't affect the original
variable which contains the array elements or object properties.

Array Example1:

let a = [10, 20, 30, 40, 50];


let b = [...a];
b.push(70);
console.log(b); //output: [ 10, 20, 30, 40, 50, 70 ]
console.log(a); //output: [ 10, 20, 30, 40, 50 ]

Object Example 2:

let person={
name:"zero",
age:21,
gender:"male"
}

let b={...person};
b.name="hero";

console.log(person);
console.log(b);

Copying Arrays:

 You can use the spread operator to create a shallow copy of an array:

74
Ameerpet technologies

//copying array without spread operator

let orgnlarr = [1, 2, 3, 4, 5, 6];


let copyarr = orgnlarr;
console.log(copyarr) // output: [1, 2, 3, 4, 5, 6]
console.log(orgnlarr === copyarr) // output :true (because they store at same location);

 In JavaScript, when you assign an array to another variable using the assignment
operator (=), you are creating a reference to the original array rather than
creating a new copy of the array.
 This means that both variables (orgnlarr and copyarr) point to the same location in
memory, and any changes made to one array will affect the other.

Copying array with Spread Operator:

let orgnlarr = [1, 2, 3, 4, 5, 6];


let copyarr =[ ...orgnlarr];
console.log(copyarr)
console.log(orgnlarr === copyarr) // false , because their address is different or reference is different

 The spread operator (...) creates a new array and copies the elements of orgnlarr into the
new array. As a result, orgnlarr and copyarr are now two separate arrays with different
references in memory.
 The statement console.log(orgnlarr === copyarr); evaluates to false because they are distinct
arrays, and their references in memory are not the same. Any modifications made to
one array will not affect the other.
 This is a common way to create a shallow copy of an array in JavaScript.

Merging Arrays:

//You can merge two or more arrays using the spread operator:
const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6, 7];
const arr3 = [8, 9, 10];
const mergedArray = [...arr1, ...arr2, ...arr3];
console.log(mergedArray);

Adding Elements to an Array:


You can add elements to an existing array using the spread operator:

75
Ameerpet technologies

const originalArray = [1, 2, 3];


const newArray = [...originalArray, 4, 5];

console.log(newArray); // [1, 2, 3, 4, 5]

Copying Objects:

You can use the spread operator to create a shallow copy of an object:

const originalObject = { name: 'John', age: 30 };

const copyObject = {...originalObject} ;

console.log(copyObject); // { name: 'John', age: 30 }


console.log(originalObject === copyObject); // false(not the same reference or location)

Merging Objects:

 You can merge two or more objects using the spread operator.
 Note :that if there are overlapping keys, the rightmost object's value
takes precedence:
 const object1 = { name: 'John', age: 30 };
 const object2 = { job: 'Full stack Developer', age: 25 };
 const mergedObject = { ...object1, ...object2 };
 const mergedObject2={...object2,...object1};

 console.log(mergedObject);// { name: 'John', age: 25, job: 'Full stack Developer' } //here we can see
that both objects has age as key but in second objects’s age is taken.
 console.log(mergedObject2);//{job: 'Full stack Developer', age: 30, name: 'John'} // here also second
object age is taken age=30;

Adding Properties to an Object:

You can add properties to an existing object using the spread operator:

const originalObject = { name: 'John' ,gender:"male"};

const updatedObject = { ...originalObject, age: 30 };

76
Ameerpet technologies

console.log(updatedObject); //output: { name: 'John', gender: 'male', age: 30 }

REST PARAMETERS:- Rest parameters are a form of parameter tied to an array, which allows for the
concise introduction of a variable number of terms in a function call. This is also called a variadic
function.

 Rest parameters in JavaScript are a feature that allows you to represent an indefinite number of
function arguments as an array.

 They are denoted by the use of the rest operator (...) followed by a parameter name in a
function declaration.

 When a function is called with more arguments than there are named parameters, the excess
arguments are gathered into an array.

Without Rest Parameter:


function sumOfValues(a,b,c,d,e,f,g){
// let sum=0;
let sum=a+b+c+d+e+f+g;
console.log(sum);
}
sumOfValues(10,20,30,40,50,60,70)

Example 1:

function sumOfValues(...arr) {
let sum = 0;
for (var i = 0; i <= arr.length - 1; i++) {
sum = sum + arr[i];
}
console.log(sum);
let sum1 = 0;
for (let ind in arr) {
sum1 = sum1 + arr[ind];
}
console.log(sum1);
let sum2 = 0;
for (let x of arr) {
sum2 = sum2 + x;
}
console.log(sum2);
}

77
Ameerpet technologies

sumOfValues(10, 20, 30, 40, 50, 60, 70);

Example2:
For loop
function perfectValues(...arr) {
for(var j=0;j<=arr.length-1;j++){
let n = arr[j];
let sum = 0;
for (var i = 0; i < n; i++) {
if (n % i === 0) {
sum = sum + i;
}
}
if (n === sum) {
console.log(n);
}
}
}
perfectValues(5,6,7,28,3);

For of loop
function arrperfect(...arr) {
for (let n of arr) {
let sum = 0;
for (let i = 1; i <= n - 1; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum === n) {
console.log(n);
}
}
}
arrperfect(5, 6, 30, 28, 50); // output: 6,28

Example 3:-
function primeNumb(...arr) {
for (var j = 0; j <= arr.length - 1; j++) {
let n = arr[j];
let count = 0;
for (var i = 0; i <= n; i++) {

78
Ameerpet technologies

if (n % i === 0) {
count = count + 1;
}
}
if (count === 2) {
console.log(n);
}
}
}
primeNumb(7, 6, 3, 9, 4, 12,11);

Difference between Spread operator and Rest operator:

 The spread operator (...) is used to expand elements of an array or properties of an


object.
 The rest operator (...) is used to collect the remaining elements of an array or properties
of an object into a single variable.
 The spread operator can be used with arrays and objects, while the rest operator is
commonly used with function parameters to handle variable numbers of arguments.

JavaScriptDay-14

Call Back Function: A function passed as an argument to another function is called as Call Back
Function

 A callback function, in programming, is a function that is passed as an argument to another


function and is intended to be called when a specific event occurs or when a particular task is
completed.
 Callback functions are commonly used in asynchronous programming, event handling, and
various other scenarios where you want to define custom behavior that should execute at a
certain point in the program's execution.

callback functions uses:

1. Asynchronous Operations
2. Event Handling
3. Custom Behavior
4. Modular and Reusable Code
5. Error Handling
6. Higher-Order Functions
7. Chaining and Composition

79
Ameerpet technologies

8. Dynamic Behavior

Example 1:
function test(callback) {
callback();
}
function b() {
console.log("i am a callback function");
}
test(b); // output: i am a callback function

Example 2:

function wish(callback) {
callback("Hero");
}
function greeting(name) {
console.log(`Good Morning ${name}`);
}
wish(greeting); // Good Morning Hero
Example 3:
function check(callback){
callback(6);
}
function even(n){
if(n%2===0){
console.log(`${n} is even`);
}
else{
console.log(`${n} is not even`);
}
}
check(even); //output: 6 is even

Example 4:
function check(x,callback) {
callback(x);
}
function isPrime(n) {
let count = 0;
for (var i = 0; i <= n; i++) {

80
Ameerpet technologies

if (n % i === 0) {
count = count + 1;
}
}
if (count === 2) {
console.log(`${n} is Prime`);
} else {
console.log(` ${n} is Not Prime`);
}
}
check(6,isPrime); //output: 6 is Not Prime

Example 5:

function test(a,b,c,callback){
callback(a,b,c);
}
function add(x,y,z){
let sum=x+y+z;
console.log(sum);
}

test(3,4,5,add);

Example 6: Call Back Function with Rest Parameter


function test(callback, ...arr) {
callback(arr);
}
function add(arr) {
let sum = 0;
for (var i = 0; i <= arr.length - 1; i++) {
sum = sum + arr[i];
}
console.log(sum);
}

test(add,1,2,3,4,5,6); //output : 21

Example 7:
 setTimeout is a JavaScript function that schedules the execution of a specified function or
code block after a specified time delay, measured in milliseconds.

81
Ameerpet technologies

 It is commonly used for introducing delays in code execution, animations, or asynchronous


operations.

function a(callback){
console.log("hello");
setTimeout(callback,5000);
}
function b(){
console.log("hero");
}
a(b);

Higher Order Funtion:


A function which takes one or more functions or callback functions as arguments or returns a
function as result is called as Higher order functions

Example 1:-

function test(callback1,callback2, arr) {


callback1(arr);
callback2(arr);
}
function displayArr(arr) {
for (let x of arr) {
console.log(x);
}
}
function bigArr(arr1) {
let big = arr1[0];
for (let a of arr1) {
if (a > big) {
big = a;
}
}
console.log(`biggest element of arr is ${big}`);
}
let arr = [1, 2, 3, 4, 5];
test(displayArr,bigArr, arr);

Example 2:
function test(callback1,callback2, arr) {
callback1(arr);

82
Ameerpet technologies

return callback2(arr);
}
function displayArr(arr) {
for (let x of arr) {
console.log(x);
}
}
function bigArr(arr1) {
let big = arr1[0];
for (let a of arr1) {
if (a > big) {
big = a;
}
}
return "biggest element is "+big;
}
let arr = [1, 2, 3, 4, 5];
console.log(test(displayArr,bigArr, arr));

Example 3: A function which returns another function as Result


function multiplier(factor) {
return function (number) {
return factor * number;
};
}

const multiplyByTwo = multiplier(2);


console.log(multiplyByTwo(5)); // Output: 10
console.log(multiplyByTwo(8)); // Output: 16

const multiplyByThree = multiplier(3);


console.log(multiplyByThree(4)); // Output: 12
console.log(multiplyByThree(7)); // Output: 21

JavaScriptDay-15
Array Methods:
forEach():used to print ARRAY elements directly without using index values or for loop

 it is a Higer Order function

83
Ameerpet technologies

 The forEach method is a built-in JavaScript method that allows you to iterate over the elements
of an array and apply a function to each element.
 It's a convenient way to perform an action on each item in an array without the need for explicit
loops like for or while.
 forEach returns undefined, (i.e forEach doesn’t return anything)
 Use forEach to simplify array iteration, performing actions like printing, modifying, or
interacting with the DOM for each element.
 Unlike for loops, forEach lacks break capabilities; prefer for or alternative loops for premature
exits.

Syntax:

array.forEach(function(currentValue, index, array) {


// code to be executed for each element
}, thisArg);

 currentValue: The current element being processed in the array.


 index (optional): The index of the current element being processed.
 array (optional): The array that forEach is being called on.
 thisArg (optional): An optional value to be used as this when executing the callback function.

let arr = [10, 20, 30, 40, 50];

function iterateArray(currentValue, index, array) {


console.log(`cv: ${currentValue} index: ${index} array:${array}`);
}
arr.forEach(iterateArray);
//output:
/*cv: 10 index: 0 array:10,20,30,40,50
cv: 20 index: 1 array:10,20,30,40,50
cv: 30 index: 2 array:10,20,30,40,50
cv: 40 index: 3 array:10,20,30,40,50
cv: 50 index: 4 array:10,20,30,40,50*/

for Each with Anonymous function :

let arr1 = [10, 20, 30, 40, 50];

arr1.forEach(function (cv, i, arr) {


console.log(`currentValue: ${cv} index:${i} array:${arr}`);
});
//output:
/*currentValue: 10 index:0 array:10,20,30,40,50
currentValue: 20 index:1 array:10,20,30,40,50

84
Ameerpet technologies

currentValue: 30 index:2 array:10,20,30,40,50


currentValue: 40 index:3 array:10,20,30,40,50
currentValue: 50 index:4 array:10,20,30,40,50*/

forEach with Arrow Function:

let arr1 = [10, 20, 30, 40, 50];

arr1.forEach((cv, i, arr) => {


console.log(`currentValue: ${cv} index:${i} array:${arr}`);
});
//output:
/*currentValue: 10 index:0 array:10,20,30,40,50
currentValue: 20 index:1 array:10,20,30,40,50
currentValue: 30 index:2 array:10,20,30,40,50
currentValue: 40 index:3 array:10,20,30,40,50
currentValue: 50 index:4 array:10,20,30,40,50*/

Biggest Element in the array

let arr1 = [10, 20, 30, 40, 50];

let big1=arr1[0];
arr1.forEach((cv,i,arr)=>{
if(cv>big1){
big1=cv;
}
});
console.log(`the largest value of the array is ${big1}`);
//output:the largest value of the array is 50

 Find Smallest Element in the Array using anonymous function and forEach

Sum of EvenNumbers in array

let arr1 = [1, 2, 3, 4, 5, 6];

let sum = 0;

85
Ameerpet technologies

arr1.forEach((cv, i, arr) => {


if (cv % 2 === 0) {
sum = sum + cv;
}
});
console.log(`the sum of even values of the array is ${sum}`);
//output:the sum of even values of the array is 12

Odd Indexed elements

let arr1 = [1, 2, 3, 4, 5, 6];

arr1.forEach((cv, i, arr) => {


if (i%2 !== 0) {
console.log(cv);
}
});

Prime number with forEach

let arr1 = [1, 2, 3, 4, 5, 6, 7];


let count = 0;
console.log(`the prime numbers of the array are:`);
arr1.forEach((cv) => {
let count = 0;
for (var i = 1; i <= cv; i++) {
if (cv % i === 0) {
count++;
}
}
if (count === 2) {
console.log(cv);
}
});

Try Perfect number logic using forEach

Objects Related Topic:

Iterating the objects using For in loop

Dot Notation used:

86
Ameerpet technologies

const Person={
name:"hero",
age:21,
gender:"male"
}

for(let key in Person){


console.log(`${key}: ${Person.key}`)
}
// output: name: undefined
// age: undefined
// gender: undefined

Bracket notation Used:

const Person={
name:"hero",
age:21,
gender:"male"
}

for(let key in Person){


console.log(`${key}: ${Person[key]}`)
}

//output:
/*name: hero
age: 21
gender: male*/S

 The first code (Person.key) is incorrect because dot notation (.) is used with the literal string
"key" instead of the variable key. JavaScript interprets it as an attempt to access a property
named "key" within the Person object, which doesn't exist, leading to undefined.
 The corrected code (Person[key]) uses square bracket notation to dynamically access the
property corresponding to the current key in the loop. This allows the variable key to be
properly evaluated, providing the correct values for each property during the iteration.

JavaScriptDay-16
forEach(): Iterate Over Each Element
modification Example:

87
Ameerpet technologies

let arrayEx = [1, 4, 2, 35, 9, 21];


arrayEx.forEach(function (cv) {
cv = cv * 2;
console.log(cv); //modified values 2,8,4,70,18,42
});

console.log(arrayEx); //[1,4,2,35,9,21];

 By the above example we can conclude that :the operations inside the forEach method
doesn’t effect the original array.

 The forEach operates on a copy of each element, not on the original array. Therefore,
when you print the arrayEx after the method, it remains unchanged, and the output will
be [1, 4, 2, 35, 9, 21].

Example 2: forEach returns Nothing


let arr=[1,2,3,4,5,6,7,8,9];
const evenNum=arr.forEach((cv)=>{
if(cv%2===0){
return cv;
}
})
console.log(arr);
console.log(evenNum); //it will show undefined because forEach doesn’t return anything

If you want a newArray with evenNumbers then you can modify the code as following

Example2:

let arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9];


let newArr = [];
console.log(newArr); //[]
arr.forEach((cv) => {
if (cv % 2 == 0) {
newArr.push(cv);
}
});

console.log("After "+ newArr);// After 10,2,4,6,8

map(): Transform Each Element's Value

88
Ameerpet technologies

 The map method is also a higher order function


 It is primarily used to transform elements in an array by applying a specified function to each
element and creating a new array with the results of those function calls.
 Here's the general syntax and common uses of the map method:
 arrayName.map(callback(currentValue, index, array), thisArg)
 It won’t modify existing array ,but modified values will be added to new array;

Example1: we can perform same operation as forEach() but never recommended to use this
let arrEx=[1,2,3,4,5,6,7,8,9];
arrEx.map((currentValue,index,arr)=>{
console.log(`currentvalue:${currentValue} index:${index} array:${arr}`);
})

Example 2: It won’t modify existing array ,but modified values will be added to new array;
let arrEx=[50,30,120,180,34,24,54];

const thirdPartValues=arrEx.map((cv,i,arr)=>{
return cv/3;
})
console.log(thirdPartValues); //[16.666666666666668, 10, 40, 60,
11.333333333333334, 8, 18] the values added into new array
console.log(arrEx);//[50, 30, 120, 180, 34, 24, 54] the original array is not
modified

Example 3: Double values:


const numbers=[1,2,3,4,5];
let doubledNum=numbers.map(doubleElem)

function doubleElem(item,index,arr){
return item*2;
}
console.log(numbers);
console.log(doubledNum);

Example 4:

let numb = [1, 2, 3, 4, 5];

function multiply(value, index) {


return value * index;
}

89
Ameerpet technologies

let values = numb.map(multiply);


console.log(values); // [0, 2, 6, 12, 20]

Example 5:

let fruits = [
"Apple",
"Banana",
"Grapes",
"Mango",
"custardApple",
"WaterMelon",
"Orange",
];

const fruitLengths = fruits.map(function (cv) {


return `${cv} : ${cv.length}`;
});

console.log(fruitLengths);

filter():- chooses Elements Meeting the given Condition


 it is also a higher order function
 The filter method in JavaScript is a built-in array method that creates a new array with all
elements that pass a certain test implemented by the provided function.It takes a callback
function as an argument and applies this function to each element in the array.
 The callback function should return true to include the element in the new array, or false to
exclude it.
 The filter() method is used to filter from the given list of elements with specified conditions.
 it returns a new array with filtered elements
 the filter method does not modify the original array

Example1:

let arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const newArr = arr.filter((cv) => {


if (cv % 2 == 0) {
return cv;
}
});

90
Ameerpet technologies

console.log(newArr); //[ 10, 2, 4, 6, 8 ]


console.log(arr); //[10, 1, 2, 3, 4, 5, 6, 7, 8, 9] it won’t modify the orignal
array

Above Example tried with map()

let arr = [1, 2, 3, 4, 5, 6];

const newArr=arr.map((cv) => {


if (cv % 2 == 0) {
return cv;
}
});

console.log( newArr); //[ undefined, 2, undefined, 4, undefined, 6 ]

Example2:
If we use Scope (curlybraces then we should use return keyword)

const nums=[10,18,25,36,33]

const evenArr=nums.filter(item=>{ return item%2===0});


console.log(evenArr);

console.log(nums)// filter() doesn’t modify the original array

Example3: Normal way without using filter()

const users = [
{ id: 1, name: "Hero1", age: 24, gender: "male" },
{ id: 2, name: "Heroine1", age: 18, gender: "female" },
{ id: 3, name: "Hero2", age: 28, gender: "male" },
{ id: 4, name: "Heroine2", age: 26, gender: "female" },
];

for (var i = 0; i <= users.length - 1; i++) {


//console.log(users[i].name);
if (users[i].age > 25) {
console.log(users[i]);
}
}

91
Ameerpet technologies

//using for of loop


for (let user of users) {
//console.log(user.name);
if (user.age > 25) {
console.log(user);
}
}

//output
// { id: 3, name: 'Hero2', age: 28, gender: 'male' }
//{ id: 4, name: 'Heroine2', age: 26, gender: 'female' }

Example4: By using filter method

const users = [
{ id: 1, name: "Hero1", age: 24, gender: "male" },
{ id: 2, name: "Heroine1", age: 18, gender: "female" },
{ id: 3, name: "Hero2", age: 28, gender: "male" },
{ id: 4, name: "Heroine2", age: 26, gender: "female" },
];
const eligibleCrew=users.filter((cv)=>{
if(cv.age>25){
return cv;
}
})
console.log(eligibleCrew)

Example 5: remove duplicates from array using filter method

const orgNumbers = [1, 2, 3, 4, 1, 4, 2, 3, 6, 1];


const nums = orgNumbers.filter((value, index, arr) => {
if( arr.indexOf(value) === index){
// indexOf this will check in the parameter array
return value;
}})
console.log(nums); // [ 1, 2, 3, 4, 6 ]

 forEach: Iterate Over Each Element


 map: Transform Each Element's Value
 filter: Select Elements Meeting Condition

92
Ameerpet technologies

JavaScriptDay-17
map():

Example 1:
Add 20 to each element of Array:

let arr= [1,2,3,4,5,6];


const addedValue=arr.map((cv)=>cv+20);
console.log(arr);//[ 1, 2, 3, 4, 5, 6 ]
console.log(addedValue);//[ 21, 22, 23, 24, 25, 26 ]

Example 2:

let arr = ["apple", "mango", "Banana", "orange"];


const addedValue = arr.map((cv) => cv.toUpperCase()); //[ 'APPLE', 'MANGO',
'BANANA', 'ORANGE' ]
const capitalFruits = arr.filter((cv1) => cv1.toUpperCase()); //[ 'apple',
'mango', 'Banana', 'orange' ]
const forEachFruits = arr.forEach((cv2) => cv2.toLowerCase()); //undefined
console.log(addedValue, capitalFruits, forEachFruits);

Example 3: Here we used Number constructor which converts values to number

let stringNum = ["1", "2", "3", "4", "5", "6"];

const intNum = stringNum.map((cv) => Number(cv));


console.log(intNum);
console.log(stringNum);
console.log("Type of StringNum array elements");
stringNum.forEach((cv) => {
console.log(typeof cv);
});
console.log("Type of intNum array Elements");
intNum.forEach((cv) => {
console.log(typeof cv);
});

93
Ameerpet technologies

Example 4: here used forEach,map,filter


let numbers=[1,2,3,4,5,6,7];
const EvenNumber3=numbers.forEach((num)=> num%2===0);
let EvenNumbers2=numbers.map((item)=> item%2===0);
let EvenNumbers1=numbers.filter((item)=> item%2===0);

console.log("forEach :"+EvenNumber3) //undefined


console.log("map :"+EvenNumbers2); //map false,true,false,true,false,true,false
console.log("filter :"+EvenNumbers1); //filter 2,4,6

Example 5: methods chaining concept


forEach method chaining: it wont work because the forEach returns nothing(undefined)

let arr = [1, 2, 3, 4, 5];

arr
.forEach((cv) => {
console.log(cv * 2);
})
.forEach((cv1) => {
console.log(cv1 * 3);
}); // Cannot read properties of undefined (reading 'forEach')

map method chaining: the method chaining works with map

let arr = [1, 2, 3, 4, 5];

const newArr = arr


.map((cv) => {
return cv * 10;
})
.map((cv1) => {
return cv1 + 5;
});
console.log(newArr);

filter method chaining:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

94
Ameerpet technologies

const dividedElems = arr


.filter((cv) => {
return cv % 2 === 0;
})
.filter((cv1) => {
return cv1 % 4 === 0;
});
console.log(dividedElems); //[4,8]

Truthy and Falsy:

 in JavaScript, a value is considered "falsy" if it converts to false when evaluated in a Boolean


context. Here are some examples of falsy values in JavaScript:

1. false: The Boolean value false.


2. 0: The number zero.
3. NaN: Not a Number.
4. '' or "": Empty string.
5. null: A special keyword denoting a null value.

Additionally, the following values are also falsy, but they are often considered edge cases:

6. undefined: A declared variable that hasn't been assigned a value.


7. document.all: A non-standard property that is true for certain browser objects.

 It's important to note that all other values in JavaScript are considered "truthy" when used in
a Boolean context, including non-empty st rings, non-zero numbers, and objects.

Example to demonstrate:

if (false) {
console.log('This will not be executed.');
}

if (0) {
console.log('This will not be executed.');
}

if ('') {
console.log('This will not be executed.');
}

if (null) {
console.log('This will not be executed.');

95
Ameerpet technologies

if (undefined) {
console.log('This will not be executed.');
}

if (NaN) {
console.log('This will not be executed.');
}

if (true) {
console.log('This will be executed.'); // true is truthy
}

if (1) {
console.log('This will be executed.'); // 1 is truthy
}

if ('Hello') {
console.log('This will be executed.'); // Non-empty string is truthy
}

if ([-1, 0, 1]) {
console.log('This will be executed.'); // Non-empty array is truthy
}

if ({}) {
console.log('This will be executed.'); // Non-empty object is truthy
}

Example with filter :

let arr=[1,2,3,4,5,6,7,8,9];
const divideValue=arr.filter((cv)=>{
if(cv%2){ //here it is 1 % 2 ans =1 so truthy so returning value next
// here 2%2 ans = 0 so falsy so no returning the value;
return cv;
}
})
console.log(divideValue //[ 1, 3, 5, 7, 9 ]

map and forEach method chaining:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

96
Ameerpet technologies

arr
.map((cv) => cv + 10)
.map((cv) => cv * 5)
.forEach((cv) => {
console.log(cv);
});// output [50,55,60,65,70,75,80,85,90,95]

Map ,filter and forEach method chaining:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];


arr
.map((cv) => cv + 10)
.map((cv) => cv * 5)
.filter((cv) => cv % 2 !== 0)
.forEach((cv) => {
console.log(cv);
}); //output:[55,65,75,85,95]

reduce():-
In JavaScript, the reduce() method is a built-in function for arrays that is used to reduce an array into a
single value by applying a specified function to each element of the array, from left to right.

 It's a powerful tool for performing operations like summing, averaging, or aggregating values in
an array.
 The reduce() method is commonly used in functional programming and for tasks that require
iteratively processing an array and accumulating a result.

Syntax:
array.reduce(callback(accumulator, currentValue, currentIndex, array),
initialValue)

Example 1:
let myNums = [1, 2, 3, 4, 5, 6];
myNums.reduce((ac, cv, i, arr) => {
console.log(ac, cv, i, arr);
}, 5);
// 5 1 0 [ 1, 2, 3, 4, 5, 6 ]
// undefined 2 1 [ 1, 2, 3, 4, 5, 6 ]
// undefined 3 2 [ 1, 2, 3, 4, 5, 6 ]
// undefined 4 3 [ 1, 2, 3, 4, 5, 6 ]
// undefined 5 4 [ 1, 2, 3, 4, 5, 6 ]
// undefined 6 5 [ 1, 2, 3, 4, 5, 6 ]

97
Ameerpet technologies

Example 2:
let myNums = [1, 2, 3, 4, 5, 6];
let initialvalue = 0;
const sumofArr = myNums.reduce((ac, cv) => {
return ac + cv;
}, initialvalue);
console.log(sumofArr); //21

Example 3:

let myNums = [1, 2, 3, 4, 5, 6];


let iv = 1;
const multyofArr = myNums.reduce((ac, cv) => ac*cv, iv);
console.log(multyofArr); //720

Example 4: largest element of the array

const numbers = [12, 6,48, 30, 8, 17];


let iv=-Infinity;
const max = numbers.reduce(((accumulator, currentValue) => Math.max(accumulator,
currentValue)), iv); //in accumulator each time the last largest element will
be stored
console.log(max); // Output: 48

JavascriptDay-18
Collections:

In JavaScript, there is no built-in "Collections" type as you might find in some other programming
languages.

 Instead, JavaScript provides various data structures and objects that can be used to store and
manipulate collections of data.
 These collections can be implemented using arrays, objects, Set and Map . Here are some
common data structures used to represent collections in JavaScript:

Arrays:

 They are ordered lists of elements, and each element can be of any data type, including
other arrays or objects.
 You can use methods like push(), pop(), shift(), unshift(), and various iteration methods to
manipulate and access array elements.

98
Ameerpet technologies

Example:

const numbers = [1, 2, 3, 4, 5];


const fruits = ["apple", "banana", "cherry"];

Objects: Objects in JavaScript are collections of key-value pairs.

 They are often used to store related data and can be thought of as associative arrays.
 You can use dot notation or bracket notation to access and manipulate object properties.

Example:

const person = {

firstName: "John",

lastName: "Doe",

age: 30
};

Sets: Sets are a built-in data structure introduced in ES6 (ECMAScript 2015) for storing unique values.

 They can be used to eliminate duplicates from an array or to manage a collection of distinct
values.

Example:

let arr=[1,2,3,4,1,24,21,2,1,3,4];
let unqvalue=new Set(arr);
console.log(unqvalue);

Maps: Maps are another ES6 feature that allow you to store key-value pairs.

 Unlike objects, maps can use any data type as keys and maintain the order of elements, making
them suitable for a wide range of use cases.

Example:

let m=new Map();


m.set("name","Hero");
m.set("age",21);
m.set("gender","male");
console.log(m);

99
Ameerpet technologies

Set:
Create a new Set:

const set=new Set();


A set is an unordered collection of unique values

let set= new Set([1,2,3,1,2,4]);


console.log(set); //{1,2,3,4}

Add an Elemenet to a Set

let set = new Set([1, 2, 3, 1, 2]);


console.log(set); //{1,2,3}

set.add(4);
set.add(5);
set.add(6);
console.log(set); //{ 1, 2, 3, 4, 5, 6 }

Check if a set contains an element


Clg(set.has(‘element’)); //output true or false

let set = new Set([1, 2, 3, 4, 5, 6]);


console.log(set); //{1,2,3,4,5,6}

console.log(set.has(3)); //true

Includes():-
Array also has a method which checks whether this element is present in the array or not.

let arr=[1,2,3,4,5,6];
console.log(arr.includes(2)); //true
console.log(arr.includes(9)); //false

Remove an Element from a Set:


set.delete(‘elem’);

let set = new Set([1, 2, 3, 4, 5, 6]);


console.log(set); //{1,2,3,4,5,6}

set.delete(4);

100
Ameerpet technologies

console.log(set); // { 1, 2, 3, 5, 6 } 4 is removed from the set

Get the size of a Set:


Clg(set.size);

let set = new Set([1, 2, 3, 4, 5, 6]);


console.log(set); //{1,2,3,4,5,6}

console.log(set.size); //6

clear a Set:
set.clear()

let set = new Set([1, 2, 3, 4, 5, 6]);


console.log(set); //{1,2,3,4,5,6}
set.clear();
console.log(set); //{}

convert a set to an Array:


const arr=[…set];

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


console.log(typeof set);//object
let arr=[...set];
console.log(typeof arr); //object

Map
A map is a collection of key-value pairs ,where each key can only appear once

Creating a New Map:

const map=new Map();


console.log(map);

Adding elements to a Map:

const map=new Map();

101
Ameerpet technologies

console.log(map);
map.set("name","hero");
map.set("age",0);
map.set("gender","male");

console.log(map); //{ 'name' => 'hero', 'age' => 0, 'gender' => 'male' }
Getting the size of a Map:
console.log(map.Size);

onst map = new Map();


console.log(map.size); //0
map.set("name", "hero");
map.set("age", 0);
map.set("gender", "male");

console.log(map.size); //3

checking if a map contains a key:


console.log(map.has(‘key1’);

const map = new Map();

map.set("name", "hero");
map.set("age", 0);
map.set("gender", "male");

console.log(map.has("name")); //true
console.log(map.has("job")); //false

Removing an element from a Map:


map.delete(‘key1’);

const map = new Map();

map.set("name", "hero");
map.set("age", 0);
map.set("gender", "male");
console.log(map); //{ 'name' => 'hero', 'age' => 0, 'gender' => 'male' }
map.delete("gender");
console.log(map); //{ 'name' => 'hero', 'age' => 0 }

102
Ameerpet technologies

Clearing all elements from a Map:


map.clear();

const map = new Map();

map.set("name", "hero");
map.set("age", 0);
map.set("gender", "male");
console.log(map); //{ 'name' => 'hero', 'age' => 0, 'gender' => 'male' }
map.clear();
console.log(map); //{}

Destructuring:
 Destructuring is a feature in JavaScript that allows you to extract values from objects and arrays
into variables.
 It provides a concise and convenient way to access and work with the properties or elements
contained within objects and arrays.

Destructuring Objects:

You can destructure objects by specifying the variable names inside curly braces {} that match the
property names in the object.

const person = { firstName: "John", lastName: "Doe" };


//before destructuring
console.log(person.firstName); //John
console.log(person.lastName); //Doe
//After destructuring

const { firstName, lastName } = person;

console.log(firstName); // Output: John


console.log(lastName); // Output: Doe

Example1:

const person={
name:"Hero",
age:21,
gender:"male"
}

const{name,age,gender}=person;

103
Ameerpet technologies

console.log(name,age,gender); //Hero 21 male

Example2: Rename the keys of objects

const person = {
name: "Hero",
gender: "male",
age: 21,
};

const { name: fname, gender, age: Age } = person;

console.log(fname, gender, Age); //hero male 21


Example3:

When we are Trying to destructure the property that doesn’t exist

const person={
name:"Hero",
gender:"male",
age:21
}

const {name,gender,age,address}=person;

console.log(name,gender,age,address);

Example4:

Assigning a default value to the value which doesn’t exist in the Object

const person={
name:"Hero",
gender:"male",
age:21
}

const {name,gender,age,address='Ameerpet'}=person;

console.log(name,gender,age,address); //Hero male 21 Ameerpet

Destructuring Arrays:

 Destructuring also works with arrays.

104
Ameerpet technologies

 You can extract elements from an array and assign them to variables using square brackets [].

const colors = ["red", "green", "blue"];


//Before destructuring
console.log(colors[0]); //red
console.log(colors[1]); //green
console.log(colors[colors.length - 1]); //blue
//After Destructuring
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // Output: red
console.log(secondColor); // Output: green
console.log(thirdColor); // Output: blue

Skipping an element in destructuring array

let arr=[1,2,3,4,5];
const[a,b,,d,e]=arr;
console.log(a,b,d,e); //[1,2,4,5]

using spread operator and storing values and printing

let arr=[1,2,3,4,5];
const[a,...b]=arr;
console.log(a,b); //1 [ 2, 3, 4, 5 ]

☺thAnk You😇
for Your pAtience AnD co -operAtion throughout the clAsses

-vineeth goDishelA

105

You might also like