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

Js Notes

Javascript is a dynamic programming language used primarily in web pages. It allows for client-side scripting to interact with users and make dynamic web pages. Javascript code is written within <script> tags and is interpreted by web browsers. It is a case-sensitive language that supports various data types, operators, and comments. Common operators include arithmetic, comparison, logical, and assignment operators.

Uploaded by

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

Js Notes

Javascript is a dynamic programming language used primarily in web pages. It allows for client-side scripting to interact with users and make dynamic web pages. Javascript code is written within <script> tags and is interpreted by web browsers. It is a case-sensitive language that supports various data types, operators, and comments. Common operators include arithmetic, comparison, logical, and assignment operators.

Uploaded by

Narendra A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

What is JavaScript?

Javascript is a dynamic computer programming language.


It is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make dynamic
pages.
It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript
made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

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>

This code will produce the following result:


Hello World!
===================================================================================
==========================
Whitespace and Line Breaks:
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.

Semicolons are Optional:


Simple statements in JavaScript are generally followed by a semicolon character,
just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example,
the
following code could be written without semicolons.

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.

<script language="javascript" type="text/javascript">


<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
===================================================================================
==========
JavaScript Datatypes
These are the type of values that can be represented and
manipulated in a programming language.
JavaScript allows you to work with three primitive data types:
 Numbers, e.g., 123, 120.50 etc.
 Strings of text, e.g. "This text string" etc.
 Boolean, e.g. true or false.
null :emty value
undefined:not defined
===================================================================================
==================================
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following table.
They
cannot be used as JavaScript variables, functions, methods, loop labels, or any
object
names.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
Instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

===================================================================================
=====================================

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

Arithmatic operators:Arithmatic operatorsperform Arithmatic operation


eg: + (add)
- (substraction)
* (multiply)
++ (increment)
--(decrement)
% (modulus)
/ (division)

<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 )

The following code shows how to use comparison operators in JavaScript.


<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
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) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>

Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
(a <= b) => true

logical operators: logical operators are used to test true or false.


logical operators are used to determine the logic between
variables and values.

eg: && (and)


|| (or)
! (not)

<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
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);
//-->
</script>
</body>
</html>

output
(a && b) => false
(a || b) => true
!(a && b) => true

Assignment Operators:Assignment Operators assign values to javascript variables


eg:=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
**=

<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>

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

Conditional(Ternary) operators:javascript also contains Conditional operatorsthat


assign a value to a variable based on some condition
SYNTAX:- variableName = (condition)? value1:value2;

var entry=(age<18)? "not eligible": "elogible";

<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100

String operators:the + operators can also be used to add (concatenate) String


eg : var text="dashwath";
var text1="kotian";
var result= test + " " + test1;

<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
</body>
</html>

output
Result => B is String
Result => A is Numeric

type operators:Used to determine the type of data being stored in variable.


eg: typeof (Return the type of variable )
instanceof (Return true if an object is an instance of an Object
type)

Bitwise Operators:Bit operation works on 32 bit number . any numerics operand in


the operation is converted into a 32 bit number .
the result is converted back to a javascript number
eg: & (AND)
| (OR)
~ (NOT)
^ (XOR)

<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
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("(~b) => ");


result = (~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);
//-->
</script>
</body>
</html>

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.

syntax: function functionName ()


{

//statement

functionName(); // function call

eg1: <script>
function display()
{
document.write("welcome to js");
}

display(); // function call


</script>

eg2: <script>
function ipl_team()
{
document.write("rcb"+"</br>");
document.write("csk"+"</br>");
document.write("kkr"+"</br>");
document.write("mi"+"</br>");
}

ipl_team(); //function call


</script>
===================================================================================
===================
PARAMETERIZED FUNCTION
syntax: function functionName(para1,para2,......paraN)
{
//statement
}

functionName(args1,args2,.......argsN);

eg1: function Student(name,place,age)


{
document.write("name is "+name+"</br>");
document.write("name is "+place+"</br>");
document.write("name is "+age+"</br>");
}
Student("DASHWATH","MANGLORE",26);
Student("SHISHIRA","BANGLORE",36);
Student("NAGABISHEK","BANGLORE",26);

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;
}

Syntax 2: function functionName()


{
return variable;
}

Syntax 3: function functionName()


{
return Expression;
}

eg1:
<script>
function display() //syntax1
{
return 123;
}

function display() //syntax2


{
var x="js"
return x;
}

function display() //syntax3


{
return 10*23+20;
}
</script>

==>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()

===================================================================================
============================

default parameter function


syntax: function functionName(para1,para2,......paraN=value)
{
//statement
}

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")
}

v();// function call


</script>

eg2 <script>
var v=function display(name)
{
document.write("name is "+name+"</br>")
}

v("ashwath");// function call


v("narayan");// function call
</script>

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");
}

t();// function call


</script>

eg3:we can also pass function as arguments.


<script>
var y=function (subject)
{
return subject
}

var x= y(function()
{
return "java script"
});
document.write(x());//function call
</script>

eg4: function returning another function


<script>
var y=function ()
{
return function()
{
return "java script"
}
}
var result=y();
document.write(result());//function call
===================================================================================
============================

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

eg4: var x=name => {return name};


document.write(x("yash"));//function call

eg5: var y=name => name;


document.write(x("pandith"));//function call

==>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

syntax: function functionName1 ()


{
function functionNmae2 ( )
{
//statement
}
}
eg1: <script>
function outerfunction()
{
function innerfunction()
{
document.write("react js");
}
innerfunction(); // function call
}
outerfunction(); // function call
</script>

eg2: <script>
function outerfunction()
{
function innerfunction()
{
return "node js"
}
innerfunction();
}
outerfunction();
</script>

==> only the outerfunction will be having authority to call innerfunction ,


if we want call innerfunction we have to call through outerfunction.

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.

• This is also a great counter to the lure of global


variables. When writing complex code it is often
tempting to use global variables to share values
between multiple functions — which leads to code that
is hard to maintain. Nested functions can share
variables in their parent, so you can use that
mechanism to couple functions together when it
makes sense without polluting your global namespace
— 'local globals' if you like. This technique should be
used with caution, but it's a useful ability to have.
===================================================================================
===================
closure:-
is a behaviour where the innerfunction can acces the outerfunction
variables but vise versa is not possible
==>every innerfunction will be having 3 scope
1)local scope
2)outer function scope
3) global scope

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!");

– confirm(msg) asks the user to confirm (or cancel)


something
eg1:confirm("Are you sure you want to do that?");

– prompt(msg, default) asks the user to enter some text


eg1:prompt("Enter you name","Adam");

===================================================================================
=======
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 .

Rules for Identifiers :


• Identifier cannot have Space .
• Identifiers cannot have special characters except $ and _ (under score ) .
• Identifiers must not be Java Keyword.
• Identifiers must not start with Numbers , but it can have numbers.
===================================================================================
=======
Object creation:
syntax: var container_name=new className();

ex: class Bike{

}
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>

==>drowback in direct Initialization we are geting hard coded values(same output)

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);

var c2=new car();


c1.price=200000;
c1.color="white";
c1.brand="bmw";
console.log(c2.brand);
console.log(c2.color);
console.log(c2.price);

var c3=new car();


c1.price=400000;
c1.color="red";
c1.brand="lambo";
console.log(c3.brand);
console.log(c3.color);
console.log(c3.price);
</script>

===================================================================================
======
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

var b2=new Bike();


b2.brand="honda";
b2.price=50000;
b2.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

eg1: var person = function (first, last, age, eye)


{
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;

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.

There are 3 ways to construct array in JavaScript

By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)

The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>

The syntax of creating array directly is given below:

var arrayname=new Array();


Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

<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>

JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.

The example of creating object by array constructor is given below.

<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

JavaScript Array Methods


1)concat():
It returns a new array object that contains two or more merged arrays.

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.

===================================================================================
=========================

String Methods and Properties

1)JavaScript String Length:


The length property returns the length of a string:

eg: let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


let length = txt.length; //26

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).

eg: let str = "Apple, Banana, Kiwi";


let part = str.slice(7, 13);//Banana

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)

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);//Banana

4) substr()
syntax: substr(start, length)

substr() is similar to slice().

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)

regexp Required. The value to search for, as a regular expression.


Returns: An Array, containing the matches, one item for each match, or
null if no match is found

Example 1
Search a string for "ain":

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/g); //ain,ain,ain

Example 2
Perform a global, case-insensitive search for "ain":

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/gi);//ain,AIN,ain,ain

10)String includes()
Syntax
string.includes(searchvalue, start)

searchvalue: Required. The string to search for


start: Optional. Default 0. Position to start the search
Returns: Returns true if the string contains the value, otherwise false

The includes() method returns true if a string contains a specified value.

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

ex: var str="java script ";


var x=str.repeat(6);
console.log(x);

12) charAt()
it will return the charactor of the specified position

EX: var str="hi guys how are you all"


var x=str.charAt(3)
console.log(x)//g

13) charCodeAt()
it will return the assci value of specified index value of that charactor

Ex: var str="javaScript";


var a=str.charCodeAt(1);
console.log(a);//97

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>

You might also like