Java script matrial
Java script matrial
vineeth goDishelA
Note:The Remaining Js topics will be covered along with React js
Ameerpet technologies
JavaScriptDay-1
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
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
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)
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:
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
var a;
let b;
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>
<!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.
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>
<!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>
<!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(){
practice.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to JavaScript Class</title>
6
Ameerpet technologies
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>
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>
<!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:
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
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
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
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.
var a = 5;
console.log(a); // 5
let b = 5;
console.log(b); // 5
// let b = 10; // Error: Identifier 'b' has already been declared (Redeclaration
not allowed)
12
Ameerpet technologies
let x="hello";
if(true){
let x="I said Hello";
console.log(x) // output: I said Hello
}
console.log(x);//output: hello
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)
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
console.log(x); // undefined
var x = 5;
console.log(x); // 5
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:
sayHello(); // This will call the sayHello function, and "Hello, world!" will be printed to the console
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.
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: 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
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
function getGreeting() {
return "Hello, world!";
}
const greeting = getGreeting();
console.log(greeting);
Example:2
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."
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
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.
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.
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");
}
};
const mul=function(num)
{
for(var i=1;i<=num;i++){
console.log(num+"X"+i+"="+(num*i));
}
}
mul(10)
const check=function(num){
if(num%2===0){
return "even";
}
else {
return "odd";
}
}
console.log(check(15));
20
Ameerpet technologies
//prime number
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
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.
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.
22
Ameerpet technologies
}
}
};
evenNumbers();
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:
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.
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.
Object Literal:
const person = {
name: "John",
age: 30
};
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,
};
26
Ameerpet technologies
const person = {
firstName: "John",
lastName: "Doe"
};
person.age = 30;
const person = {
firstName: "John",
lastName: "Doe"
};
person["age"] = 30;
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
person.age = 31;
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
person["age"] = 31;
27
Ameerpet technologies
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Deleting the "age" property
delete person.age;
//Bracket Notation
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
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';
// Modify elements
car.year = 2023;
car.color = 'Red';
// Delete elements
delete car.color;
29
Ameerpet technologies
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
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
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
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:
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);
}
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());
},
};
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.
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
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
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
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();
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:
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()
38
Ameerpet technologies
JavaScriptDay-7
Constructor():-
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
//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");
}
}
output:
40
Ameerpet technologies
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
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:
41
Ameerpet technologies
C# code:
using System;
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:-
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 ${}.
· 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.
JavaScriptDay-8
this keyword:
44
Ameerpet technologies
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)
// Create instances
45
Ameerpet technologies
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}`);
}
}
46
Ameerpet technologies
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();
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;
}
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.");
}
}
51
Ameerpet technologies
constructor(radius) {
super();
this.Radius = radius;
}
// Usage
const circle = new Circle(5);
circle.calculateArea(); // Outputs the area of the circle
Example2:-
class Shape {
constructor(name) {
this.name = name;
}
52
Ameerpet technologies
this.sideLength = sideLength;
}
Polymorphism:
static add(x, y, z) {
return x + y + z;
}
}
53
Ameerpet technologies
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;
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.
}
}
55
Ameerpet technologies
}
}
}
}
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
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");
}
}
}
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]);
}
}
}
}
}
int sum=0;
for(int i=0;i<=arr1.length-1;i++) {
sum=sum+arr1[i];
}
}
}
58
Ameerpet technologies
if (arr1[i] % 2 == 0) {
System.out.println(arr1[i]);
}
}
}
}
Foreach loop:-
for(int currentElement:arr1) {
System.out.println(currentElement);
}
}
}
59
Ameerpet technologies
Again Creating Empty Array and checking their default values By using For Each Loop
}
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);
}
}
}
60
Ameerpet technologies
}
}
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.
Numbers Array
let myArray = [1, 2, 3, 4, 5];
let lastIndex = myArray.length - 1;
let lastElement = myArray[lastIndex];
61
Ameerpet technologies
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 .
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.
62
Ameerpet technologies
Array Methods:
numbers.push(4);
3. shift(): Removes and returns the first element from an array, shifting all other elements
to a lower index.
4. unshift(): Adds one or more elements to the beginning of an array, shifting existing
elements to higher indices.
animals.unshift("cheetah", "panther");
63
Ameerpet technologies
6.indexOf(): Returns the index of the first occurrence of a specified element in an array.
console.log(bananaIndex); // Output: 1
7.lastIndexOf(): Returns the index of the last occurrence of a specified element in an array.
console.log(lastBananaIndex); // Output: 3
numbers.reverse();
9.sort(): Sorts the elements of an array in place, based on a provided sorting function.
fruits.sort();
64
Ameerpet technologies
12 join(): Converts all elements of an array into a string and concatenates them, separated by a
specified delimiter.
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.
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
66
Ameerpet technologies
let hours=currentdate.getHours();
console.log(hours); //output: 1
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:
console.log(roundedNumber1);// Output: 4
console.log(roundedNumber2);// output: 3
console.log(flooredNumber1);// Output: 3
console.log(flooredNumber2);// output: 3
ceil(decimalNumber): gives the base ceil(top most) number of the decimal value;
68
Ameerpet technologies
console.log(ceilNumber1);// Output: 3
console.log(ceilNumber2);// 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:
69
Ameerpet technologies
console.log("Year:", year);
console.log("Day:", day);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);
console.log("Milliseconds:", milliseconds);
// Helper function to get the day name based on the day of the week
function getDayName(dayOfWeek) {
return daysOfWeek[dayOfWeek];
Math Example:
70
Ameerpet technologies
// Math.sqrt()
// Math.random()
console.log("Random Value between 0 and 1:", randomValue); // Output: A random number between 0
and 1
// Rounding methods
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("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.
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
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'}
callByValue callByReference
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.
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:
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
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.
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);
75
Ameerpet technologies
console.log(newArray); // [1, 2, 3, 4, 5]
Copying Objects:
You can use the spread operator to create a shallow copy of an object:
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;
You can add properties to an existing object using the spread operator:
76
Ameerpet technologies
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.
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
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);
JavaScriptDay-14
Call Back Function: A function passed as an argument to another function is called as Call Back
Function
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);
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
function a(callback){
console.log("hello");
setTimeout(callback,5000);
}
function b(){
console.log("hero");
}
a(b);
Example 1:-
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));
JavaScriptDay-15
Array Methods:
forEach():used to print ARRAY elements directly without using index values or for loop
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:
84
Ameerpet technologies
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
let sum = 0;
85
Ameerpet technologies
86
Ameerpet technologies
const Person={
name:"hero",
age:21,
gender:"male"
}
const Person={
name:"hero",
age:21,
gender:"male"
}
//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
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].
If you want a newArray with evenNumbers then you can modify the code as following
Example2:
88
Ameerpet technologies
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
function doubleElem(item,index,arr){
return item*2;
}
console.log(numbers);
console.log(doubledNum);
Example 4:
89
Ameerpet technologies
Example 5:
let fruits = [
"Apple",
"Banana",
"Grapes",
"Mango",
"custardApple",
"WaterMelon",
"Orange",
];
console.log(fruitLengths);
Example1:
90
Ameerpet technologies
Example2:
If we use Scope (curlybraces then we should use return keyword)
const nums=[10,18,25,36,33]
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" },
];
91
Ameerpet technologies
//output
// { id: 3, name: 'Hero2', age: 28, gender: 'male' }
//{ id: 4, name: 'Heroine2', age: 26, gender: 'female' }
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)
92
Ameerpet technologies
JavaScriptDay-17
map():
Example 1:
Add 20 to each element of Array:
Example 2:
93
Ameerpet technologies
arr
.forEach((cv) => {
console.log(cv * 2);
})
.forEach((cv1) => {
console.log(cv1 * 3);
}); // Cannot read properties of undefined (reading 'forEach')
94
Ameerpet technologies
Additionally, the following values are also falsy, but they are often considered edge cases:
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
}
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 ]
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]
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:
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:
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:
99
Ameerpet technologies
Set:
Create a new Set:
set.add(4);
set.add(5);
set.add(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
set.delete(4);
100
Ameerpet technologies
console.log(set.size); //6
clear a Set:
set.clear()
Map
A map is a collection of key-value pairs ,where each key can only appear once
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);
console.log(map.size); //3
map.set("name", "hero");
map.set("age", 0);
map.set("gender", "male");
console.log(map.has("name")); //true
console.log(map.has("job")); //false
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
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.
Example1:
const person={
name:"Hero",
age:21,
gender:"male"
}
const{name,age,gender}=person;
103
Ameerpet technologies
const person = {
name: "Hero",
gender: "male",
age: 21,
};
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;
Destructuring Arrays:
104
Ameerpet technologies
You can extract elements from an array and assign them to variables using square brackets [].
let arr=[1,2,3,4,5];
const[a,b,,d,e]=arr;
console.log(a,b,d,e); //[1,2,4,5]
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