0% found this document useful (0 votes)
9 views58 pages

Teks JavaScript notes

JavaScript is a high-level programming language primarily used for creating interactive web content, allowing manipulation of HTML and CSS. It supports various programming concepts including data types, variables, operators, and control statements, making it versatile for both client-side and server-side development. Key features include dynamic content updates, event handling, and the ability to enhance user experience without page reloads.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views58 pages

Teks JavaScript notes

JavaScript is a high-level programming language primarily used for creating interactive web content, allowing manipulation of HTML and CSS. It supports various programming concepts including data types, variables, operators, and control statements, making it versatile for both client-side and server-side development. Key features include dynamic content updates, event handling, and the ability to enhance user experience without page reloads.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

JavaScript

Introduction to JavaScript
What is JavaScript?

JavaScript is a versatile, high-level programming language used primarily for creating dynamic
content on web pages. It allows you to manipulate HTML and CSS to make web pages
interactive, responsive, and visually engaging.

 Client-Side Language: JavaScript runs directly in the user's browser, making it a client-
side language. It is often used in combination with HTML (structure) and CSS (style).
 Interactivity: JavaScript enables actions like form validation, animation, AJAX (loading
content without reloading the page), event handling (like clicks), and much more.

Why Use JavaScript?

 To manipulate the DOM (Document Object Model).


 To add interactive elements like forms, animations, and games.
 To improve user experience by dynamically changing content without needing to reload
the page.

To insert a JavaScript into an HTML page, use the <script> tag. The <script> and
</script> tells where the JavaScript starts and ends.

The lines between the <script> and </script> contain the JavaScript code.

<script type="text/javascript">

</script>

We can place this JavaScript code in head part as well as body part also.
To insert a JavaScript into an HTML page, use the <script> tag. The <script> and </script> tells
where the JavaScript starts and ends.
The lines between the <script> and </script> contain the JavaScript code.

<script type="text/javascript">

</script>

We can place this JavaScript code in head part as well as body part also.

Comments
Comments are very useful in any programming language.
Comments will
- Improves the program understand ability and readability.
- To skip executing certain statements in a program by placing
them under comments.

To write single line comments we will use //


Example :
<script type="text/javascript">
document.write("hello");
//document.write("Hi"); -- This line will never execute because it is in
comments
</script>
To write multi line comments we simply place those particular statements
witin /*---------------------------*/
<script type="text/javascript">
document.write("hello");
/*
document.write("Hi");
document.write("welcome");
*/
</script>

We can print any text in a web page by using JavaScript


in following ways.

1) document.write("hello") ;

This statement is equivalent to writing the text hello


in body part.

<html>
<head>
<script type="text/javascript">
document.write("Hello...Welcome to JavaScript Class from Teks Academy");
</script>
</head>
<body>

</body>
</html>

Here document is an object that represents html document (body part).


Whatever the text that we write within the document.write
statement, that text will be directly placed within body part
of the webpage.
------------------------------------------------------------
2) innerHTML
If we want to place a text within start and end of any tag
(innerHTML) then this method will be used.

To implement this we need to assign a id to the tag so that we


can place the content within this particular tag from javascript
part by identifying the tag using the id assigned.

<html>
<head>
</head>
<body>
<h1 id="special"></h1>
<script type="text/javascript">
document.getElementById("special").innerHTML = "Welcome to JS Class from Teks Academy";
</script>
</body>
</html>
------------------------------------
3) window.alert(Hello);
To display output message in separate window then we may use alert box.
By using this method whatever the message that we send to browser through window.alert
that will be displayed in a
separate window.
<html>
<head>
</head>
<body>
<script type="text/javascript">
window.alert("Welcome to JS from Teks Academy");
</script>
</body>
</html>

Difference between JavaScript and Java


JavaScript:

JavaScript is a high-level, interpreted scripting language primarily used for web development.

It's executed by web browsers to add interactivity, dynamic content, and behavior to websites.

JavaScript is versatile, being used for client-side scripting (running in the browser) as well as
server-side scripting (with environments like Node.js).

It's dynamically typed, meaning you don't have to declare the data type of variables explicitly.

JavaScript is more forgiving and flexible than Java, allowing for rapid development and
prototyping.

It's primarily used for front-end web development, but with the advent of Node.js, it's also used
for back-end development and building full-stack web applications.
Java:

Java is a high-level, object-oriented programming language developed by Sun Microsystems


(now owned by Oracle).

It's compiled into bytecode which can run on any platform with a Java Virtual Machine (JVM),
providing platform independence.

Java is known for its strong type system, where data types of variables must be explicitly
declared.

It's used for a wide range of applications, including web applications (using frameworks like
Spring), mobile applications (Android development), enterprise software, embedded systems,
and more.

Java emphasizes portability, security, and performance.

While it can be used for web development (Java Servlets, JavaServer Pages), it's not as
commonly used for front-end web development as JavaScript.

DATA TYPES
In JavaScript, there are several data types that are used to represent different kinds of values.
Here are the main data types:

Primitive Data Types:

String: Represents textual data, enclosed within single ('') or double ("") quotes.
Number: Represents numeric data, including integers and floating-point numbers.

Boolean: Represents a logical value, true or false.

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

Null: Represents the intentional absence of any object value.

Symbol: Introduced in ECMAScript 6 (ES6), represents a unique and immutable value


used as object property keys.

Non-Primitive Data Types (also known as reference types):

Object: Represents a collection of key-value pairs (properties and methods).


Objects can be created with curly braces {} or with constructor functions.

Array: Represents a list-like collection of elements, stored sequentially and accessed


by index.
Arrays can be created with square brackets [].

Function: Represents reusable blocks of code that can be invoked by name.

Date: Represents a date and time value.

RegExp: Represents a regular expression, used for pattern matching within strings.
Variables
var:

Variables declared with var are function-scoped.


This means they are accessible anywhere within the function in which they are
declared,
even before the point where they are declared (due to hoisting).

Variables declared with var can be reassigned and updated.

var x = 10;
console.log(x); // Output: 10
x = 20;
console.log(x); // Output: 20

var x = 10;
var x = 20; // Redeclaration allowed
console.log(x); // Output: 20
--------------------------------------------------------------------------
let:

Variables declared with let are block-scoped. This means they are accessible only
within the block in which they are declared (e.g., within loops, conditionals, or
functions).
Variables declared with let can be reassigned, but they cannot be redeclared
within the same scope.
let x = 10;
console.log(x); // Output: 10
x = 20;
console.log(x); // Output: 20
// let x = 30; // SyntaxError: Identifier 'x' has already been declared

------------------------------------------------------------------------------------
const:

Variables declared with const are also block-scoped like let.


The value of a const variable cannot be reassigned once it has been initialized.
However, if the variable is an object or array, its properties or elements can still
be modified.

const x = 10;
console.log(x); // Output: 10
// x = 20; // TypeError: Assignment to constant variable

const person = { name: 'divya' };


person.name = 'rishi'; // Valid, modifies the property
console.log(person); // Output: { name: 'rishi' }

1. Variable Names Cannot Start with a Number

A variable name cannot begin with a digit (0-9).


 Invalid:

1name = "Alice"; // Syntax error: Cannot start with a number

 Valid:

name1 = "Alice"; // Valid: Starts with a letter

Variable names must start with a letter (a-z, A-Z), an underscore (_), or a dollar sign ($).

2. Variable Names Can Contain Letters, Digits, Underscores, and Dollar Signs

Variable names can include:

 Letters (a-z, A-Z)


 Digits (0-9) (but not at the start)
 Underscores (_)
 Dollar Signs ($)
 Valid Names:

javascript
Copy code
name1 = "Alice"; // Starts with a letter, contains a digit.
_name = "Bob"; // Starts with an underscore.
$age = 30; // Starts with a dollar sign.
name_123 = "Charlie"; // Contains an underscore and digits.

3. Variable Names Are Case Sensitive

JavaScript is case-sensitive, so myVariable and myvariable are considered two different


variables.

 Valid:

let myVariable = "Alice";


let myvariable = "Bob";

 Invalid (if you expect them to be the same):

let myVariable = "Alice";


let myvariable = "Bob"; // This is a valid variable, but it's not the
same as 'myVariable'

4. Variable Names Cannot Be JavaScript Reserved Keywords


Certain keywords are reserved by JavaScript, as they have special meanings in the language.
These reserved words cannot be used as variable names.

 Reserved Keywords (examples):


o if, else, for, while, return, function, var, let, const, class, new, null,
undefined, try, catch, etc.
 Invalid:

let function = "This won't work"; // 'function' is a reserved keyword

 Valid (alternative names):

let myFunction = "This works"; // Use alternative names

5. Variable Names Cannot Contain Spaces

Variable names must be a single, uninterrupted word (without spaces). If you want to separate
words, use camelCase, underscores, or other styles.

 Invalid:

let first name = "Alice"; // Error: Variable names cannot have spaces

 Valid:

let firstName = "Alice"; // Camel case


let first_name = "Alice"; // Underscore

6. Variable Names Can Be Descriptive

While this is not a strict "rule" in JavaScript syntax, it's important to choose descriptive variable
names to make your code more readable and understandable.

 Good Practice:

let age = 25; // Descriptive, easy to understand


let firstName = "Alice"; // Descriptive, clear

 Avoid ambiguous names:

let x = 25; // Not descriptive, hard to understand


let a = "Alice"; // Ambiguous

Best Practices for Naming Variables


 Start with a letter, underscore, or dollar sign.
 Use meaningful and descriptive names to improve code readability.
 Follow consistent naming conventions (like camelCase) to make your code easier to
maintain.

Examples of Good Variable Names:


 userAge
 firstName
 totalAmount
 isValid
 userList

List of keywords:

list of some of the keywords in JavaScript:

break
case
catch
class
const
let
continue
debugger
default
delete
do
else
export
extends
finally
for
function
if
import
in
instanceof
new
return
super
switch
this
throw
try
typeof
var
void
while
with
yield

OPERATORS :
In JavaScript, operators are symbols that perform operations on operands,
which can be values or variables.
JavaScript supports various types of operators,including arithmetic,
assignment, comparison, logical, bitwise, and more. Here's a brief overview:

Arithmetic Operators: These are used to perform mathematical operations


like addition, subtraction, multiplication, division, modulus, and
exponentiation.

Example:
let a = 5;
let b = 2;
let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulus
let power = a ** b; // Exponentiation
-----------------------------------------------------------
Assignment Operators: These are used to assign values to variables.
Example:

let x = 10;
x += 5; // Equivalent to x = x + 5;
--------------------------------------------------
Comparison Operators: These are used to compare values and return a boolean

let a = 5;
let b = 3;
console.log(a > b); // Output: true
------------------------------------------------------
Logical Operators: These are used to combine or manipulate boolean values.
Example:

let x = true;
let y = false;
console.log(x && y); // Logical AND
console.log(x || y); // Logical OR
console.log(!x); // Logical NOT//f
---------------------------------------------------------
Bitwise Operators: These are used to perform bitwise operations on integer
operands.
Example:
let a = 5; // 0101
let b = 3; // 0011
console.log(a & b); // Bitwise AND (result: 1)
console.log(a | b); // Bitwise OR (result: 7)
console.log(a ^ b); // Bitwise XOR (result: 6)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log('operators :')

var a=100,b=10

console.log('a+b: ',a+b)
console.log('a-b: ',a-b)
console.log('a*b: ',a*b)
console.log('a/b: ',a/b)
console.log('a%b: ',a%b)

console.log(typeof a)//---datatype of variable

console.log('Assignment operator: ')

console.log('a+=b: ',a+=b)
console.log('a-=b: ',a-=b)
console.log('a*=b: ',a*=b)
console.log('a/=b: ',a/=b)
console.log('a%=b: ',a%=b)

var x=10,y='10'

console.log(x==y)//------true
console.log(x===y)//-----false

console.log(typeof x)
console.log(typeof y)

console.log('Relational operators:')

var s=200,t=20

console.log('s<t: ',s<t)
console.log('s>t: ',s>t)
console.log('s<=t: ',s<=t)
console.log('s>=t: ',s>=t)
console.log('s==t: ',s==t)
console.log('s!=t: ',s!=t)

console.log('Logical Operators')
console.log('AND')
console.log(true && true)
console.log(true && false)
console.log(false && true)
console.log(false && false)
console.log('OR')
console.log(true || true)
console.log(true || false)
console.log(false || true)
console.log(false || false)
console.log('NOT')
console.log(!true)
console.log(!false)
console.log('Bitwise operators')
var o=18,p=28
console.log('bitwise and: ',o&p)
console.log('bitwise or: ',o|p)
console.log('bitwise xor: ',o^p)
console.log('Unary Operators')
var q=10,w=10,e=10,r=10
console.log('pre incre: ',++q)
console.log('post incre: ',w++,w)
console.log('pre decre: ',--e)
console.log('post decre: ',r--,r)
console.log('Ternary operator')
var age=13
var result=(age>=18)?'do vote':'cant vote'
console.log(result)

</script>>

</body>
</html>
Control statements:

We generally use control statements to implement various functions in our


programs.
We have
1) if condition:
if is a selection statement which allows us to execute one block of statements
based on
the condition returns true.
syntax:
if(condition)
{
//statements
}
Above block of statements will be executed if condition becomes true.
Under if, we have if-else statement too where one block of statements among
two will be
executed based on the condition result (true or false).
syntax:
if(condition)
{
//statements
}
else
{
//else statement
}

In the above code if condition satisfies then first block of statements will be
executed. If condition becomes false then else block will be executed.
Under if, we have if-else-if statements also where we can check more than one
condition
and based on the conditions result corresponding block of statements will be
selected for
execution.
syntax:
if(condition1)
{
//statements
}
else if(condition2)
{
//statement
}
else
{
//stmt
}
-------------------------------------------------------------------------
switch
switch case will also work same as if. It is also used to select and execute a block
of
statements based on a condition.
syntax:
switch(expression)
{
case ____: statements;
break;
case ____: statements;
break;
case ____: statements;
break;
default: statements;
break;
}
In above syntax the case that matches with expression value is selected for
execution. if no case is matched with the expression then default case will be
selected for execution

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// var op=parseInt(prompt('enter option: 1-telugu 2-english 3-
tamil 4-kannada 5-malayalam'))
switch(op)
{
case 1:console.log('change to telugu')
break;
case 2:console.log('change to english')
break;
case 3:console.log('change to tamil')
break;
case 4:console.log('change to kannada')
break;
case 5:console.log('change to malayalam')
break;
default:console.log('wrong input')

//--------------------------------------------------------------------

var a=10,b=20
var ch=parseInt(prompt('Enter 1-ADD 2-Mul 3-SUB 4-DIV 5-MOD'))
switch(ch)
{
case 1:console.log('ADD: ',a+b)
break;
}

</script>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var age=2
if(age>=18)
{
console.log('do vote')
}
else{
console.log('can not vote')
}
//---------------------------------------

var marks=67 // prompt('enter marks')

if(marks>=90)
{
console.log('first class')
}
else if(marks>=80)
{
console.log('GRADE 1')
}
else if(marks>=35){
console.log('pass')
}
else{
console.log('fail')
}
//------------------------------------------
var a=100,b=200,c=300

if(a>=b)
{
if(a>=c)
{
console.log('a is largest b and c')
}
else{
console.log('c is largest value')
}
}
else
{
if(b>=c)
{
console.log('b is largest value')
}
else{
console.log('c is largest value')
}
}

</script>
</body>
</html>

Looping Statements:
for
for loop also used to execute block of statements more than one time repeatedly
based on a condition

syntax:
for(initialization;condition;iteration)
{
}
------------------------------------------------------------------------------------------
while
By using while condition we can execute block of statements more than one time.
syntax :
while(condition)
{
statements
}
above block of statements will be repeatedly executed and whenever the
condition specified
is failed then it stops the execution

<html>
<head>
<script type="text/javascript">

var a=0;

while(a<10)
{
document.write("a is : "+a+"<br/>");
//0
//1//2 3 4 5 6 7 8 9
a++;

}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
for(let i=1;i<=15;i++)
{
console.log('Teks')
}

for(let j=15;j>=1;j--)
{
console.log('Batch34')
}
// ----------------------------------------------------

let a=100
while(a>20)
{
console.log('a values are'+a)
a-=10
}
// -----------------------------------------------------
let c=20
do{
console.log('c values are '+c)
c++
}while(c>=40)
//-----------------------------------------------------------------
for(let i1=1;i1<=10;i1++)
{
if(i1==3)
break;
console.log('count values i1 '+i1)
}
//------------------------------------------------------
for(let j1=1;j1<=10;j1++)
{
if(j1==3)
continue;
console.log('count values j1 '+j1)
}
</script>
</body>
</html>
ARRAYS:
An array is a special data structure used in JavaScript to store a collection of values in an
ordered way. Think of an array like a list, where each item has a specific position or index.
Arrays are especially useful when you need to work with multiple pieces of data that belong
together.

Why Use Arrays?

Arrays allow you to group values together under one variable. Instead of creating many
individual variables to hold related data, you can store everything in a single array.

Creating an Array

There are two primary ways to create an array in JavaScript:

1. Array Literal Syntax

This is the most common way to create an array. You define an array by using square brackets
([]) and separating the elements with commas.

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

Here, the array fruits holds three elements: "apple", "banana", and "cherry".

2. Using the Array Constructor

You can also create an array using the Array constructor. This method is less common but still
valid.

let numbers = new Array(1, 2, 3, 4, 5);

This creates an array numbers with the elements 1, 2, 3, 4, and 5.

Accessing Elements in an Array

Each element in an array is stored at a specific index. The index is the position of the item within
the array, and in JavaScript, array indices start at 0 (zero-indexed).

For example:

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


console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "cherry"

Here, fruits[0] refers to the first item in the array, fruits[1] to the second, and so on.

Modifying Array Elements

You can modify an array element by assigning a new value to a specific index:

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


fruits[1] = "blueberry"; // Changes "banana" to "blueberry"
console.log(fruits); // ["apple", "blueberry", "cherry"]

In this example, we update the second element (fruits[1]) to "blueberry".

Array Length

You can find out how many elements are in an array using the .length property:

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


console.log(fruits.length); // 3

Here, fruits.length returns the number of elements in the fruits array, which is 3.

Array Methods
JavaScript arrays come with many built-in methods that allow you to perform common
operations like adding, removing, or searching elements. Let's explore some of the most
commonly used array methods.

1. push() – Add Items to the End of an Array

The push() method adds one or more elements to the end of an array.

let fruits = ["apple", "banana"];


fruits.push("cherry"); // Adds "cherry" to the end
console.log(fruits); // ["apple", "banana", "cherry"]

2. pop() – Remove Items from the End of an Array

The pop() method removes the last element from an array and returns that element.

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


let lastFruit = fruits.pop(); // Removes "cherry"
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "cherry"

3. shift() – Remove Items from the Beginning of an Array


The shift() method removes the first element from an array and returns that element.

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


let firstFruit = fruits.shift(); // Removes "apple"
console.log(fruits); // ["banana", "cherry"]
console.log(firstFruit); // "apple"

4. unshift() – Add Items to the Beginning of an Array

The unshift() method adds one or more elements to the beginning of an array.

let fruits = ["banana", "cherry"];


fruits.unshift("apple"); // Adds "apple" to the beginning
console.log(fruits); // ["apple", "banana", "cherry"]

5. slice() – Extract a Portion of an Array

The slice() method returns a shallow copy of a portion of an array. The original array remains
unchanged.

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


let someFruits = fruits.slice(1, 3); // Extracts elements at index 1 and 2
console.log(someFruits); // ["banana", "cherry"]

6. concat() – Combine Two Arrays

The concat() method combines two or more arrays into a single array.

let fruits = ["apple", "banana"];


let moreFruits = ["cherry", "date"];
let allFruits = fruits.concat(moreFruits); // Combines both arrays
console.log(allFruits); // ["apple", "banana", "cherry", "date"]

7. forEach() – Iterate Over Each Element

The forEach() method allows you to execute a function for each element in the array.

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


fruits.forEach(function(fruit) {
console.log(fruit); // Prints each fruit: "apple", "banana", "cherry"
});

8. map() – Transform Each Element

The map() method creates a new array with the results of calling a function on each element.

let numbers = [1, 2, 3];


let doubled = numbers.map(num => num * 2); // Doubles each number
console.log(doubled); // [2, 4, 6]
9. filter() – Filter Elements Based on a Condition

The filter() method creates a new array with elements that pass a test (i.e., satisfy a
condition).

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


let evenNumbers = numbers.filter(num => num % 2 === 0); // Only even numbers
console.log(evenNumbers); // [2, 4]

10. reduce() – Reduce an Array to a Single Value

The reduce() method applies a function to reduce the array to a single value.

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


let sum = numbers.reduce((accumulator, num) => accumulator + num, 0); // Sum
of numbers
console.log(sum); // 10

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var a=[45,89,43,26,67]
//each and every value stored in according to index
//index start with 0 value and incremented default by 1
//45-->0,89--->1,43---->2,26--->3,67------>4

console.log(a)

// for(let i=0;i<a.length;i++)
// {
// console.log(a[i])
// }

console.log(a[3])
a[3]=200

for(k in a)
{
console.log(k)
}

for(let j of a)
{
console.log(j)
}

</script>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let a=[10,13,76,85,23]
console.log(a)
console.log(a.length)
a.pop();
console.log(a)
a.push(56)
console.log(a)
console.log(a.sort())
console.log(a.reverse())
console.log(a)

a.unshift(1,8)//add one or more values at begining

console.log(a)

a.shift();//removes the first element


console.log(a)

let b=[1,2,3,4,5]
console.log(b.find(x=>x>3))//return only one value
console.log(b.filter(y=>y>3))//return mul values like array
console.log(a.indexOf(56))//index value

console.log(a.includes(13))
console.log(a.includes(23))

console.log(b.map(x=>x*2))

console.log(b)

console.log(b.reduce((r,s)=>{return r+s;},0))

</script>
</body>
</html>

String Functions:

string length:The length property returns the length of a string:

let text = "Ramya";


let length = text.length;//5
----------------------------------------------------------------------------------
The charAt() method returns the character at a specified index (position) in a
string:

let text = "Teks Academy";


let char = text.charAt(0);//T
------------------------------------------------------------------------------
JavaScript String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
let text = "Teks AcademSecunderabad";
let part = text.slice(7, 13);
------------------------------------
let text = "Teks Academy Secunderabad";
let part = text.slice(7);
-----------------------------------
let text = "Teks Academy Secunderabad";
let part = text.slice(-12);
---------------------------------
let text = "Teks Academy Secunderabad";
let part = text.slice(-12, -6);
----------------------------------
let str = "Teks Academy Secunderabad";
let part = str.substring(7, 13);
-----------------------------------
concat() joins two or more strings:

let text1 = "Teks";


let text2 = "Academy";
let text3 = text1.concat(" ", text2);
-----------------------------------
The trim() method removes whitespace from both sides of a string:
let text1 = " Teks Academy ";
let text2 = text1.trim();
----------------------------------

The repeat() method returns a string with a number of copies of a string.

The repeat() method returns a new string.

The repeat() method does not change the original string.

let text = "Teks Academy";


let result = text.repeat(2);
-------------------------------------
The replace() method replaces a specified value with another value in a string:

By default, the replace() method is case sensitive. Writing TEKS ACADEMY (with
upper-case) will not work:
To replace case insensitive, use a regular expression with an /i flag (insensitive):
To replace all matches, use a regular expression with a /g flag (global match):

By default, the replace() method replaces only the first match:


let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Teks Academy");
-------------------------------------
A string can be converted to an array with the split() method:
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe

----------------------------------------------------------------------------------

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>

let st1="Batch67 students are very good"

console.log('length: ',st1.length)

console.log('charAt: ',st1.charAt(8))//returns char based on


position(index)

console.log('slice: ',st1.slice(3))

console.log('slice2: ',st1.slice(3,9))

console.log('sliceneg: ',st1.slice(-2))

console.log('sliceneg2: ',st1.slice(-9,-2))

console.log('substring: ',st1.substring(4))

console.log('substring2: ',st1.substring(4,9))

console.log('repeat: ',st1.repeat(2))
console.log('replace: ',st1.replace('Batch67','full stack'))

let st2='Teks Academy'

console.log(st2.concat(" ",st1))

console.log(st1.indexOf('s'))//return index value based on


character

console.log('tolowercase: ',st1.toLowerCase())

console.log('touppercase: ',st1.toUpperCase())

</script>
</body>
</html>

OBJECTS AND FUCNTIONS:


fundamental concepts used to organize and manipulate data and behavior. Let's
break down each:

Objects: In JavaScript, objects are collections of key-value pairs.


These key-value pairs are often referred to as properties and methods.
Properties hold data, while methods are functions associated with the object that
can perform actions or
calculations.

Example of an object:

let person = {
name: "divya",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
In this example, person is an object with properties name and age, and a method
greet.
this refers to the object itself, allowing access to its properties and methods from
within its own functions.

Methods: Methods are functions that are stored as object properties. They can be
called to perform a certain action
or computation on the object's data.

Continuing with the previous example, greet is a method:

person.greet(); // Output: Hello, my name is divya


Here, greet() is called on the person object, resulting in the method executing and
printing a greeting message.

Accessing Properties and Methods:


You can access object properties and methods using dot notation or bracket
notation.

console.log(person.name); // Output: divya


console.log(person['age']); // Output: 30
Both of these lines of code access the name and age properties of the person
object, respectively.

Creating Objects: There are multiple ways to create objects in JavaScript,


including object literals, constructor functions, and ES6 classes.

// Using object literal


let person = {
name: "divya",
age: 30
};

// Using constructor function


function Person(name, age) {
this.name = name;
this.age = age;
}
let person1 = new Person("sathish", 25);

// Using ES6 class


class student {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
let obj = new student("puppy", "123");
All of these approaches create objects with properties name and age, name and
age, and name and id,
respectively.

Understanding objects and methods is crucial for developing JavaScript


applications, as they form the
backbone of how data and behavior are organized and manipulated within the
language.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let person={
name:'Sri',
age:20,
marks:100
}
person.age=30 //update or modify
console.log(person.age) //retreive value
console.log(person)
console.log(person['name'])
console.log(person['age'])
//----------------------------------------------------------

let student=new Object()


student.id=101;
student.name="Anu";
student.marks=100
console.log(student)

console.log(student.id)

console.log(Object.keys(student))
console.log(Object.values(student))
console.log(Object.entries(student))

//-------------------------------
--------

function display()
{
console.log('This is the first function')
}

display()
//----------------------------------------------

function add(a,b)
{
console.log('a+b:',(a+b))
}

add(10,20)

//----------------------------------------------

let sample={
sid:101,
course:'FSD',
read:function()
{
console.log('practice every day')

}
}

console.log(sample.course)

sample.read()

</script>
</body>
</html>

DOM (Document Object Model) refers to the hierarchical structure representing the content of
an HTML or XML document. The DOM provides a way to interact with and manipulate the
content, structure, and styles of a webpage using JavaScript.

Key Points about the DOM in JavaScript:

1. What is the DOM?


o The DOM represents the structure of an HTML document as a tree of nodes. Each
element, attribute, and piece of text is represented as a node.
o The DOM allows JavaScript to access and modify the content, structure, and style
of a webpage dynamically.
2. DOM Structure:
o At the top level, you have the document object, which represents the entire
HTML document.
o Inside the document, the DOM elements are structured in a tree-like format. Each
HTML tag (like <div>, <p>, etc.) becomes a node in this tree.
o The nodes can be manipulated using JavaScript to create, delete, or modify
HTML elements.

Common DOM Manipulation Methods in JavaScript:

1. Selecting Elements:
o getElementById(id): Selects an element by its id.
o getElementsByClassName(className): Selects all elements with a specific
class name.
o getElementsByTagName(tagName): Selects all elements of a specified tag.
o querySelector(selector): Selects the first element that matches a CSS
selector.
o querySelectorAll(selector): Selects all elements that match a CSS selector.
2. Modifying Elements:
o innerHTML: Sets or retrieves the HTML content inside an element.
o textContent: Sets or retrieves the text content of an element.
o setAttribute(attribute, value): Sets an attribute's value on an element.
o style: Accesses the inline styles of an element.
3. Creating and Removing Elements:
o createElement(tagName): Creates a new HTML element.
o createTextNode(text): Creates a new text node.
o appendChild(node): Appends a new child node to an element.
o removeChild(node): Removes a child node from an element.
o replaceChild(newNode, oldNode): Replaces an existing child node with a new
one.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
document.write('Teks Academy')

var demo=document.createElement('h1')
console.log(demo)
demo.textContent='Teks Batch 67'
document.body.appendChild(demo)

var divvar=document.createElement('div')
console.log(divvar)
divvar.style.width='150px'
divvar.style.height='150px'
divvar.style.border='2px solid black'
divvar.style.marginBottom='20px'
document.body.appendChild(divvar)

var imgvar=document.createElement('img')
console.log(imgvar)

imgvar.setAttribute('src','https://img.freepik.com/free-photo/beautiful-
strawberry-garden-sunrise-doi-ang-khang-chiang-mai-thailand_335224-
762.jpg?ga=GA1.1.163535638.1715882484&semt=ais_hybrid')
document.body.appendChild(imgvar)
imgvar.style.width='300px'

var linkvar=document.createElement('a')
console.log(linkvar)
linkvar.setAttribute('href','https://www.freepik.com/search?
ai=excluded&format=search&last_filter=query&last_value=nature&query=natur
e&type=photo')
linkvar.textContent='visit'
document.body.appendChild(linkvar)

</script>

</body>
</html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="eid">Employee Eid:101</h1>
<h2 class="Ename">Employee Name:Lavanya</h2>
<h3>Employee salary:20000</h3>
<h2 class="dept">Employee Department : Data Analyst</h2>
<h1 class="exp">Employee with 5 year Experience</h1>
<h1 class="exp">Employee with 10 year Experience</h1>
<script>

let h1idvar=document.getElementById('eid')
console.log(h1idvar)
h1idvar.textContent='Employee Eid:102'

let h2cvar=document.getElementsByClassName('Ename')[0]
console.log(h2cvar)
h2cvar.textContent='Employee Name: Srilekha'

let h3tvar=document.getElementsByTagName('h3')[0]
console.log(h3tvar)
h3tvar.style.color="blue"

let qvar=document.querySelector('.dept')
console.log(qvar)
qvar.textContent='Employee Department: Full stack java'
let qvarall=document.querySelectorAll('.exp')
console.log(qvarall)

for(let i=0;i<=qvarall.length;i++)
{
qvarall[i].style.color="red"
}

</script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
<style>
.demo{
background-color: red;
color: white;
}
.para
{
text-align: center;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint,
ducimus?</p>

<script>

let pvar=document.getElementsByTagName('p')[0]

pvar.classList.add('demo','para')

console.log(pvar)

pvar.classList.remove('para')
pvar.classList.replace('demo','para')

</script>
</body>
</html>

Events refer to actions or occurrences that happen in the browser, typically as a result of user
interaction (like clicks, key presses, mouse movements, etc.), or other triggers (like loading a
page). JavaScript can be used to handle these events and respond to them.

Types of Events:

1. Mouse Events:
o click: Triggered when a user clicks an element (e.g., button, link).
o dblclick: Triggered when a user double-clicks on an element.
o mouseover: Triggered when the mouse pointer enters an element.
o mouseout: Triggered when the mouse pointer leaves an element.
o mousemove: Triggered when the mouse pointer moves over an element.
o mousedown: Triggered when the mouse button is pressed down on an element.
o mouseup: Triggered when the mouse button is released over an element.
2. Keyboard Events:
o keydown: Triggered when a key is pressed down.
o keypress: Triggered when a key is pressed and released (deprecated in modern
browsers).
o keyup: Triggered when a key is released.
3. Form Events:
o submit: Triggered when a form is submitted.
o change: Triggered when the value of an input field, select box, or textarea
changes.
o focus: Triggered when an element (like an input field) gains focus.
o blur: Triggered when an element loses focus.
o input: Triggered when the value of an <input>, <textarea>, or <select>
changes.
Event handling refers to the process of responding to events triggered by user actions or other
sources, such as clicks, key presses, or page loading. There are several types of event handling
methods you can use, each with its own advantages and use cases. The main types of event
handling in JavaScript are:

1. Inline Event Handlers (HTML Event Attributes)

 This is the simplest way of handling events, where you directly specify the event handler
in the HTML tag. It is not recommended for large-scale applications because it tightly
couples HTML with JavaScript, but it can be useful for quick, small scripts.

Example:

html
Copy code
<button onclick="alert('Button clicked!')">Click Me!</button>

 The onclick attribute directly specifies a JavaScript function that will run when the
button is clicked.

2. Event Handling using JavaScript Properties (Traditional)

 With this method, you assign an event handler directly to an element's event property. It's
a more JavaScript-centric approach, but it only allows for one handler per event.

Example:

html
Copy code
<button id="myButton">Click Me!</button>

<script>
const button = document.getElementById("myButton");
button.onclick = function() {
alert("Button clicked!");
};
</script>

 In this approach, the onclick property of the button element is set to a function that will
be executed when the button is clicked.

3. Event Handling using addEventListener() (Modern and Preferred)

 This is the most flexible and preferred method of event handling. addEventListener()
allows multiple event listeners to be attached to the same element for the same event
type, which is not possible with the other two methods. It also provides better control
over event propagation.
Syntax:

javascript
Copy code
element.addEventListener(event, callback, useCapture);

 event: The name of the event (e.g., "click", "keydown", etc.).


 callback: The function to run when the event occurs.
 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-
scale=1.0">
 <title>Document</title>
 <style>
 button{
 background-color: dodgerblue;
 color: white;
 padding: 10px 24px;
 }
 #parent
 {
 width: 200px;
 height: 200px;
 border: 2px solid black;
 margin: 50px;
 }
 #child{
 width: 100px;
 height: 100px;
 border: 2px solid black;
 margin: 30px;
 }
 </style>
 </head>
 <body>
 <button id="demo">Login</button>
 <div id="parent">
 <div id="child"></div>
 </div>
 <script>

 let btnvar=document.getElementById('demo')
 console.log(btnvar)

 btnvar.addEventListener('click',()=>{
 console.log('button is clicked')
 })

 btnvar.addEventListener('dblclick',()=>{
 console.log('double click executed')
 })

 btnvar.addEventListener('mouseup',()=>{
 console.log('mouse up executed')
 })

 btnvar.addEventListener('mousedown',()=>{
 console.log('mousedown executed')
 })

 btnvar.addEventListener('mousemove',()=>{
 console.log('mouse move counted')
 })

 let pvar=document.getElementById('parent')
 console.log(pvar)
 pvar.addEventListener('mouseover',()=>{
 console.log('mouse over executed')
 })

 pvar.addEventListener('mouseout',()=>{
 console.log('mouse out executed')
 })

 pvar.addEventListener('mouseenter',()=>{
 console.log('mouse enter executed')
 })

 pvar.addEventListener('mouseleave',()=>{
 console.log('mouse leave executed')
 })

 </script>
 </body>
 </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
border: 2px solid black;
margin-top: 20px;
}
</style>
</head>
<body>
<form id="fid">
Enter UserName:<input type="text" placeholder="enter username"
id="inid">
<br><br>
<button>Submit</button>
</form>
<div class="box">
<h1 id="demo"></h1>
</div>
<script>
let fvar=document.getElementById('fid')
let invar=document.getElementById('inid')
let boxvar=document.getElementById('demo')

fvar.addEventListener('submit',function(event){

event.preventDefault()
let temp=invar.value
boxvar.textContent=temp
fvar.reset()

})

invar.addEventListener('focus',function()
{
invar.style.background='pink'
})
invar.addEventListener('blur',function()
{
invar.style.background=''
})

</script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
border: 2px solid black;
margin-top: 120px;
}
</style>
</head>
<body>
<select id="sid">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="blue">blue</option>
</select>
<div class="box" id="boxid">

</div>
<script>

let svar=document.getElementById('sid')
let boxvar=document.getElementById('boxid')

svar.addEventListener('change',function()
{
boxvar.style.background=svar.value
})

</script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
Enter UserName: <input type="text" placeholder="enter username"
id="data">
<script>
let invar=document.getElementById('data')
console.log(invar)

invar.addEventListener('keypress',function(event){
console.log('key press executed')
console.log(event.key)
})

invar.addEventListener('keyup',()=>{
console.log('keyup event executed')
})

invar.addEventListener('keydown',()=>{
console.log('key down executed')
})
</script>
</body>
</html>

ES6(ECMASCRIPT) :

Spread Operator (...)


The spread operator is used to unpack elements from an array or object into individual
elements. It essentially "spreads" the elements of an array or properties of an object into a new
array or object.

Usage with Arrays:

 The spread operator can be used to copy the elements of one array into another array or to
combine multiple arrays.

Example (Array Spread):

javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // Spread elements of arr1 and add new values
console.log(arr2); // Output: [1, 2, 3, 4, 5]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//spread operator (...) extends the array or objects
let ex1=[10,20,30,40,50]
let ex2=[60,70,80,90,100]

let add=[...ex1,...ex2]

console.log(add)
//----------------------------------------------------

let student={
id:101,
name:"sri",
marks:100
}
let college={
collegename:"CBIT",
location:"HYD"
}

let studentdetails={...student,...college}
console.log(studentdetails)

console.log(studentdetails.id)
console.log(studentdetails.name)

</script>
</body>
</html>

Rest Operator (...)

The rest operator is used to collect multiple elements into an array, typically used in function
parameters to handle variable numbers of arguments. It gathers any remaining arguments into a
single array.

Usage in Function Parameters:

 When used in function declarations, it collects all remaining arguments passed to the
function into an array.

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

const [first, second, ...rest] = arr;

console.log(first, second); // Output: 1 2

console.log(rest); // Output: [3, 4, 5]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//rest operator (...) declare in function based
function add(name,...b)
{
console.log(b)
let sum=0
for(let i in b)
{
sum+=b[i]
}
console.log(sum)

}
add("Sri",10,20,80,90)

//-------------------------------------------------

function mul(num1,...num2)
{
return num2.map((num)=>num1*num);
}
console.log( mul(2,4,6,8,10))
//num1=2
//num2=4,6,8,10
//num[0]=4
//num[1]=6
//num[2]=8
//num[3]=10
//num1*num--->2*4=8
//2*6=12
//2*8=16
</script>
</body>
</html>

Destructuring Assignment

Destructuring is a convenient way of unpacking values from arrays or properties from objects
into distinct variables. It can be used to extract data from arrays or objects in a much more
concise and readable way.

Array Destructuring:

 You can assign variables to individual elements of an array directly.

Example (Array Destructuring):

const arr = [1, 2, 3];


const [a, b, c] = arr;
console.log(a); // Output: 1

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let Ex1=[90,87,56,34,25]
console.log(Ex1[3])
//Destructure the variable

let [j,k,l,o,p]=Ex1
console.log(o)

let [aa,bb,cc,dd,ee]=Ex1
console.log(aa)

</script>
</body>
</html>

Higher-order function
higher-order functions are functions that take one or more functions as arguments, return a
function as a result, or both. This concept is fundamental in JavaScript, as functions are first-
class objects, meaning they can be passed around like any other value (such as numbers, strings,
and objects).

Key Characteristics of Higher-Order Functions:

1. Accept Functions as Arguments: A higher-order function can take other functions as


parameters.
2. Return Functions: A higher-order function can return a function as a result.
3. Or Both: A function that takes another function and also returns a function can be a
higher-order function.
4. <!DOCTYPE html>
5. <html lang="en">
6. <head>
7. <meta charset="UTF-8">
8. <meta name="viewport" content="width=device-width, initial-
scale=1.0">
9. <title>Document</title>
10. </head>
11. <body>
12. <script>
13. // console.log('welcome page')
14. // console.log('Registration page')
15. // console.log('Login page')
16. // console.log('Profile page')
17. const Welcome=(wref)=>{
18. setTimeout(()=>{
19. console.log('Welcome page')
20. wref()
21. },1000)
22.
23. }
24. const Registration =(rref)=>{
25. setTimeout(()=>{
26. console.log('Registration page 2')
27. rref()
28. },2000)
29. }
30.
31. const Login=(lref)=>{
32. setTimeout(()=>{
33. console.log('Login Page 3')
34. lref()
35. },300)
36. }
37.
38. const Profile=()=>{
39. setTimeout(()=>{
40. console.log('profile page 4')
41. },4000)
42. }
43.
44. Welcome(function(){
45. Registration(function(){
46. Login(function(){
47. Profile()
48. })
49. })
50. })
51.
52.
53. </script>
54. </body>
55. </html>

Promise
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value. It is a modern way of dealing with asynchronous
operations, such as network requests, file reading, or timers, and provides an alternative to the
old callback-based approach (callback hell).

Key Characteristics of Promises:

1. States of a Promise:
o Pending: The initial state. The operation has not completed yet.
o Resolved (Fulfilled): The operation has completed successfully.
o Rejected: The operation failed, and an error occurred.
2. Promise Methods:
o then(): Handles the success case when the Promise is resolved.
o catch(): Handles the failure case when the Promise is rejected.
o finally(): Executes code after the Promise settles (whether fulfilled or rejected),
often used for cleanup.
3. <!DOCTYPE html>
4. <html lang="en">
5. <head>
6. <meta charset="UTF-8">
7. <meta name="viewport" content="width=device-width, initial-
scale=1.0">
8. <title>Document</title>
9. </head>
10. <body>
11. <script>
12. const Ex1=()=>{
13. return new Promise((resolve,reject)=>{
14. let age=22;
15. if(age>=20)
16. {
17. resolve("do vote")
18. }
19. else{
20. reject("can not vote")
21. }
22. })
23. }
24.
Ex1().then((str1)=>{console.log(str1)}).catch((str2)=>{console.log(s
tr2)})
25. </script>
26. </body>
27. </html>
28. <!DOCTYPE html>
29. <html lang="en">
30. <head>
31. <meta charset="UTF-8">
32. <meta name="viewport" content="width=device-width,
initial-scale=1.0">
33. <title>Document</title>
34. </head>
35. <body>
36. <script>
37. const Welcome=()=>{
38. return new Promise((resolve,reject)=>{
39. setTimeout(()=>{
40. console.log('Welcome page')
41. resolve()
42. },2000)
43.
44. })
45. }
46. const Registration=()=>{
47. return new Promise((resolve,reject)=>{
48. setTimeout(()=>{
49. console.log('Registration page')
50. resolve()
51. },2000)
52. })
53. }
54. const Login=()=>{
55. return new Promise((resolve,reject)=>{
56. setTimeout(()=>{
57. console.log('Login page')
58. resolve()
59. },3000)
60. })
61. }
62. const Profile=()=>{
63. return new Promise((resolve,reject)=>{
64. setTimeout(()=>{
65. console.log('Profile page')
66. resolve()
67. },400)
68. })
69. }
70. Welcome().then(Registration).then(Login).then(Profile)
71. </script>
72. </body>
73. </html>

Async/Await
async/await is a more modern and readable way to work with promises. It simplifies promise
handling by allowing you to write asynchronous code that looks synchronous.

 async: A function that always returns a promise.


 await: Waits for the promise to resolve before continuing with the next line of code.
 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-
scale=1.0">
 <title>Document</title>
 </head>
 <body>
 <script>
 async function add()
 {
 console.log('inside function stmnt1')
 let r=await 2+5;
 console.log(r)
 console.log('inside function stmnt2')
 }
 add()
 console.log('outside of function stmnt')
 </script>
 </body>
 </html>

You might also like