Teks JavaScript notes
Teks JavaScript notes
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.
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.
1) document.write("hello") ;
<html>
<head>
<script type="text/javascript">
document.write("Hello...Welcome to JavaScript Class from Teks Academy");
</script>
</head>
<body>
</body>
</html>
<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>
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:
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.
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:
String: Represents textual data, enclosed within single ('') or double ("") quotes.
Number: Represents numeric data, including integers and floating-point numbers.
Undefined: Represents a variable that has been declared but not assigned a value.
RegExp: Represents a regular expression, used for pattern matching within strings.
Variables
var:
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:
const x = 10;
console.log(x); // Output: 10
// x = 20; // TypeError: Assignment to constant variable
Valid:
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
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.
Valid:
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:
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:
List of keywords:
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:
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('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:
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')
}
//---------------------------------------
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.
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
This is the most common way to create an array. You define an array by using square brackets
([]) and separating the elements with commas.
Here, the array fruits holds three elements: "apple", "banana", and "cherry".
You can also create an array using the Array constructor. This method is less common but still
valid.
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:
Here, fruits[0] refers to the first item in the array, fruits[1] to the second, and so on.
You can modify an array element by assigning a new value to a specific index:
Array Length
You can find out how many elements are in an array using the .length property:
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.
The push() method adds one or more elements to the end of an array.
The pop() method removes the last element from an array and returns that element.
The unshift() method adds one or more elements to the beginning of an array.
The slice() method returns a shallow copy of a portion of an array. The original array remains
unchanged.
The concat() method combines two or more arrays into a single array.
The forEach() method allows you to execute a function for each element in the array.
The map() method creates a new array with the results of calling a function on each element.
The filter() method creates a new array with elements that pass a test (i.e., satisfy a
condition).
The reduce() method applies a function to reduce the array to a single value.
<!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)
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:
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):
----------------------------------------------------------------------------------
<!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('length: ',st1.length)
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'))
console.log(st2.concat(" ",st1))
console.log('tolowercase: ',st1.toLowerCase())
console.log('touppercase: ',st1.toUpperCase())
</script>
</body>
</html>
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.
<!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'])
//----------------------------------------------------------
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.
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:
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.
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.
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);
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) :
The spread operator can be used to copy the elements of one array into another array or to
combine multiple arrays.
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>
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.
When used in function declarations, it collects all remaining arguments passed to the
function into an array.
<!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:
<!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).
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).
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.