Js Notes
Js Notes
Advantages of JavaScript:
The merits of using JavaScript are:
• Less server interaction: You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors: They don't have to wait for a page reload to
see if they have forgotten to enter something.
• Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
JAVASCRIPT – SYNTAX
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the <head>
tags.
The <script> tag alerts the browser program to start interpreting all the text
between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
This function can be used to write text, HTML, or both. Take a look at the
following
code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE: Care should be taken while writing variable and function names in JavaScript.
===================================================================================
===============
Comments in JavaScript
JavaScript s.
upports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may
span multiple lines
JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
===================================================================================
=====================================
operators:
==>java script operators are symbols which are used to assign values,compare
values,perform arithmatic operations.
==>variables are called operands
==>the operation is defined by operator
types of operators
1)Arithmatic operators
2)comparison operators
3)logical operators
4)Assignment Operators
5)Conditional operators
6)String operators
7)type operators
8)Bitwise Operators
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>
comparison operators: comparison and logical operators are used to test true or
false.
comparison operators are used in logical statements to
determine equality or defference between variables or values
eg: == (equal to)
=== (equal to and equal type)
!= (not equal )
!== (not equal value or not equal type)
> (gearter than)
< (lesser than)
>= (gearter than and equal to )
<= (lesser than equal to )
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
(a <= b) => true
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
output
(a && b) => false
(a || b) => true
!(a && b) => true
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) =>0
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
output
Result => B is String
Result => A is Numeric
<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Output
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
===================================================================================
=============
function :the set of instruction which is used to perform some specific task.
//statement
eg1: <script>
function display()
{
document.write("welcome to js");
}
eg2: <script>
function ipl_team()
{
document.write("rcb"+"</br>");
document.write("csk"+"</br>");
document.write("kkr"+"</br>");
document.write("mi"+"</br>");
}
functionName(args1,args2,.......argsN);
eg2: <script>
function car(brand,price,color)
{
document.write("name is "+brand+"</br>");
document.write("price is "+price+"</br>");
document.write("color is "+color+"</br>");
}
car("audi",1200000,"black");
car("bmw",2000000,"red");
car("lambo",3000000,"white");
</script>
===================================================================================
=========
Return type Function
Syntax 1: function functionName()
{
return data;
}
eg1:
<script>
function display() //syntax1
{
return 123;
}
==>return type function has to be stored in the variable to print the output or
==>we can write in the printing statemnets like documents.write() and console.log()
===================================================================================
============================
eg1: <script>
function display(a=33 ,b=32,c=10 )
{
document.write(a+"</br>");
document.write(b+"</br>");
document.write(c+"</br>");
}
display();//function call
</script>
eg2: <script>
function display(a ,b,c=10 )
{
document.write(a+"</br>");
document.write(b+"</br>");
document.write(c+"</br>");
}
display();//function call
</script>
===================================================================================
========================
Rest parameter function
syntax:function functionName(...args)
{
//statement
}
eg1: <script>
function display(...args )
{
document.write(args[0]+"</br>");
document.write(args[1]+"</br>");
document.write(args[2]+"</br>");
}
display(109,30,59);//function call
</script>
eg2:<script>
function display(a,...args )
{
document.write(a+"</br>")
document.write(args[0]+"</br>");
document.write(args[1]+"</br>");
document.write(args[2]+"</br>");
}
display("js,"java","html");//function call
===================================================================================
=========================
function Expression:
syntax:var varname=function functionName()
{
// statement
}
eg1:<script>
var v=function play()
{
document.write("play music")
}
eg2 <script>
var v=function display(name)
{
document.write("name is "+name+"</br>")
}
eg 3:
<script>
var v=function display(name)
{
return name
}
document.write(v("amruth"));
document.write( v("sudha"));
</script>
===================================================================================
==============
anonymous function:
anonymous function are those function which has no spcified function name
syntax: function ()
{
//statemnet
}
eg 1: <script>
var t=function (name)
{
return name
}
document.write(t("mogli"));
document.write( t("dinga"));
</script>
eg2: <script>
var t=function ()
{
document.write("js");
}
var x= y(function()
{
return "java script"
});
document.write(x());//function call
</script>
Arrow function:
syntax: var varname= () => {
//statement
};
eg1: <script>
var z=()=>{document.write("angular js")}
z();//function call
</script>
eg2: <script>
var z=(name)=>{document.write("name is "+name+"</br>")}
z("agasthya");//function call
</script>
eg3: <script>
var z=name=>document.write("name is "+name+"</br>");
z("nithya");//function call
==>we also write Arrow function as mentioned in the above eg if function contains
only
one parameter and statement
==>in above function the function is returing NAME. if the arrow function contains
more than
one parameter in such case we cnt elemenate ( ) brackets
==>if the function contains more than one statements then we cnt elemenate { }.
===================================================================================
=============================================
inner function :
function inside an another function is called we call inner function
eg2: <script>
function outerfunction()
{
function innerfunction()
{
return "node js"
}
innerfunction();
}
outerfunction();
</script>
eg2: <script>
function outerfunction()
{
function innerfunction()
{
document.write("java script")
}
return innerfunction();
}
var x= outerfunction();
x();//function call
</script>
• This provides a great deal of utility in writing more
maintainable code. If a function relies on one or two
other functions that are not useful to any other part of
your code, you can nest those utility functions inside
the function that will be called from elsewhere. This
keeps the number of functions that are in the global
scope down, which is always a good thing.
eg1:
<script>
function outerfunction()
{
var x=100;
function innerfunction()
{
var y=890;
document.write(y+"</br>");
document.write(x+"</br>");
}
innerfunction();
}
outerfunction();
</script>
eg2: <script>
function outerfunction()
{
var x=100;
document.write(y)// error y is not defined at outerfunction
function innerfunction()
{
var y=890;
document.write(y+"</br>");
document.write(x+"</br>");
}
innerfunction();
}
outerfunction();
</script>
===================================================================================
=======
Simple User Interaction
• There are three built-in methods of doing simple
user interaction
– alert(msg) alerts the user that something has happened
eg1:alert("There's a monster on the wing!");
===================================================================================
=======
Class :
A Class is Logical entity or Blue print using which we can create multiple Object.
Step1 :create class and then create any numberof objects.
Multiple Objects created using same class is called as Similar Object or Identical
Object.
Every Object work independently
i.e.., if one Object is modified or destroyed then it does not affect
another Object .
Object : Object is Real world Physical entity.
Anything which has Physical presence or Physical appearance can be considered as an
Object .
Object has States and Behavior .
States :
State of an object is nothing but the property / information or a data which
describes
an Object.
The data member is nothing but a data holder , which holds / stores the data.
Example:
class Pen
{
color="green";
type="marker";
}
===================================================================================
==========
Identifiers :
Identifiers is the one which is used to Identify out many class , We can Identify a
class by it’s
Name , Hence class name is called Identifier .
}
new Bike();
eg1: <script>
class Bike
{
}
document.write(new Bike());//[object Object]
console.log(new Bike());//Bike
</script>
eg2: <script>
class car
{
}
var c1=new car();
console.log(c1)
</script>
Object Creation & direct Initialization
eg1: <script>
class car
{
brand="audi";
price=2000000;
color="black";
}
var c1=new car();
console.log(c1.brand);
console.log(c1.color);
console.log(c1.price);
</script>
eg2: <script>
class car
{
brand="audi";
price=2000000;
color="black";
}
var c1=new car();
console.log(c1.brand);
console.log(c1.color);
console.log(c1.price)
var c2=new car();
console.log(c2.brand);
console.log(c2.color);
console.log(c2.price)
var c3=new car();
console.log(c3.brand);
console.log(c3.color);
console.log(c3.price)
</script>
declearation of states :
the proccess of writing a states without assign any value or data
Initialization of states:
the process of assigning values to the states.
direct Initialization:
the process of declear the states Initialization states then and there only
eg1: <script>
class car
{
brand;
price;
color;
}
var c1=new car();
c1.price=300000;
c1.color="black";
c1.brand="audi";
console.log(c1.brand);
console.log(c1.color);
console.log(c1.price);
===================================================================================
======
this keyword :this keyword refer s to current calling object reference
eg1: <script>
class Bike{
}
var b1=new Bike();
console.log(b1)//Bike
function display() {
console.log(this)//Window
}
display()
eg2: <script>
class Bike{
details= function ()
{
console.log(this)
}
}
var b1=new Bike();
console.log(b1)//Bike
b1.details();//Bike
</script>
EG3: <script>
class Bike{
brand;
price;
details= function ()
{
console.log(this.brand)
console.log(this.price)
}
}
var b1=new Bike();
b1.brand="yamaha";
b1.price=450000;
b1.details();//Bike
</script>
===================================================================================
================
CONSTRUCTOR:
constructor is a member of the class
use of constructor:
1) To create an object
2)To Initialize states
syntax:constructor()
{
// statement
}
eg1: <script>
class book
{
constructor()
{
document.write("hi i am constructor"+"</br>")
}
}
var b=new book();
var b1=new book();
var b2=new book();
var b3=new book();
</script>
eg2: <script>
class book
{
brand;
price;
constructor(b,p)
{
this.brand=b;
this.price=p;
document.write(this.brand+" "+this.price+"</br>")
}
}
var b=new book("classmate",50);
var b1=new book("paper gride",45);
var b2=new book("vidhya",35);
var b3=new book("mangala",20);
</script>
===================================================================================
=============================
constructor function:
constructor function is the combination of function expression and constructor
this.details=function()
{
document.write("first name is "+this.firstName+"</br>")
document.write("last name is "+this.lastName+"</br>")
document.write("age is "+this.age+"</br>")
document.write("eye color is "+this.eyeColor+"</br>")
};
}
var myFather = new person ("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
myFather.details();
myMother.details();
===================================================================================
=========================
ARRAY:
JavaScript array is an object that represents a collection of similar type of
elements.
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
2)every():
It determines whether all the elements of an array are satisfying
the provided function conditions.
3)filter():
It returns the new array containing the elements that pass the provided
function conditions.
4)find():
It returns the value of the first element in the given array that satisfies
the specified condition.
5)pop():
It removes and returns the last element of an array.
6)push():
It adds one or more elements to the end of an array.
7)reverse();
It reverses the elements of given array.
8)shift():
It removes and returns the first element of an array.
9)unshift():
It adds one or more elements in the beginning of the given array.
10)some():
It determines if any element of the array passes the test of
the implemented function.
11)slice():
It returns a new array containing the copy of the part of the given array.
12)sort():
It returns the element of the given array in a sorted order.
13)splice():
It add/remove elements to/from the given array.
===================================================================================
=========================
2)slice():
syntax: slice(start, end)
slice() extracts a part of a string and returns the extracted part in a new
string.
The method takes 2 parameters: the start position, and the end position (end not
included).
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -
6:
Example
let str = "Apple, Banana, Kiwi";
let part = str.slice(-12, -6);//Banana
3) substring()
syntax:substring(start, end)
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);//Banana
4) substr()
syntax: substr(start, length)
The difference is that the second parameter specifies the length of the
extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);//Banana
5)replace()
The replace() method replaces a specified value with another value in a string:
By default, the replace() method replaces only the first match:
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "qspider");//"Please visit qspider!";
6)trim()
The trim() method removes whitespace from both sides of a string:
Example
let text1 = " Hello World! ";
let text2 = text1.trim();
document.write("Length text1=" + text1.length + "<br>Length2 text2=" +
text2.length);
output:
Length text1=22
Length2 text2=12
7) String indexOf()
String indexOf()
The indexOf() method returns the index of (the position of) the first
occurrence of a
specified text in a string:
indexOf() return -1 if the text is not found:
Example
let str = "Please locate where 'locate' occurs!";
str.indexOf("locate");//7
8)
String lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified
text in a string:
lastIndexOf() return -1 if the text is not found:
Example
let str = "Please locate where 'locate' occurs!";
str.lastIndexOf("locate");//21
9)String match()
The match() method searches a string for a match against a regular expression,
and returns the matches, as an Array object.
Syntax:string.match(regexp)
Example 1
Search a string for "ain":
Example 2
Perform a global, case-insensitive search for "ain":
10)String includes()
Syntax
string.includes(searchvalue, start)
Example
let text = "Hello world, welcome to the universe.";
text.includes("world");//true
11) repeat()
it will repeat specified string based on the number we pass
12) charAt()
it will return the charactor of the specified position
13) charCodeAt()
it will return the assci value of specified index value of that charactor
Object creation :
<script>
const person={
firstname: "dashwath",
lastname: "kotian",
age: 23,
hobbies :["hiking","sports","traveling"],
address : {
street :"btm_layout",
city: "banglore",
state : "karnataka"
}
}
console.log(person.firstname);
person.email="[email protected]";
console.log(person.email)
</script>
<script>
const deatils=[
{
id:1234,
name: "dashwath",
company: "textyendra"
},
{
id: 4322,
name : "shreya",
company : "accenture"
},
{
id: 876,
name: "thyani",
company: "byjus"
}
];
console.log(deatils)
//0: {id: 1234, name: 'dashwath', company: 'textyendra'}
//1: {id: 4322, name: 'shreya', company: 'accenture'}
//2: {id: 876, name: 'thyani', company: 'byjus'}
console.log(deatils[0].company);//textyendra
</script>