You are on page 1of 21

CSS[22519] MR.SWAMI R.S.

{MOBILE NO:-+91-8275265361]

Deleting Properties
The delete keyword deletes a property from an object:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age;

The delete keyword deletes both the value of the property and the property
itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

The delete operator should not be used on predefined JavaScript object


properties. It can crash your application.

JavaScript Arrays
An array is an object that can store a collection of items. Arrays become really useful
when you need to store large amounts of data of the same type. Suppose you want to store
details of 500 employees. If you are using variables, you will have to create 500 variables
whereas you can do the same with a single array. You can access the items in an array by
referring to its indexnumber and the index of the first element of an array is zero.

JavaScript arrays are used to store multiple values in a single variable.

Example
var cars = ["Saab", "Volvo", "BMW"];

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by
referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:
var array_name = [item1, item2, ...];
Example
var cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

1) JavaScript array literal


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

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let’s see the simple example of creating and using array in JavaScript.

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

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

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

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

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

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:


var name = cars[0];

Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

WARNING !

Adding elements with high indexes can create undefined "holes" in an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits

The Difference between Arrays and Objects


In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

JavaScript Array join () Method


(Combining an Array elements into a String)
Example
Convert the elements of an array into a string:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


var energy = fruits.join();

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Definition and Usage


The join() method returns the array as a string.

The elements will be separated by a specified separator. The default separator is comma (,).

Note: this method will not change the original array.

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the
code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.


1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example


Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of
arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

Example 2
Let's see an example to display the power of provided value.
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>

What is Function in JavaScript?

Functions are very important and useful in any programming language as they make the
code reusable A function is a block of code which will be executed only if it is called. If you
have a few lines of code that needs to be used several times, you can create a function
including the repeating lines of code and then call the function wherever you want.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

How to Create a Function in JavaScript

1. Use the keyword function followed by the name of the function.


2. After the function name, open and close parentheses.
3. After parenthesis, open and close curly braces.
4. Within curly braces, write your lines of code.

Syntax:
function functionname()

lines of code to be executed

Try this yourself:


This code is editable. Click Run to Execute

<html>

<head>

<title>Functions!!!</title>

<script type="text/javascript">

function myFunction()

document.write("This is a simple function.<br />");

myFunction();

</script>

</head>

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

<body>

</body>

</html>

Function with Arguments

You can create functions with arguments as well. Arguments should be specified within
parenthesis

Syntax:
function functionname(arg1, arg2)

lines of code to be executed

JavaScript Return Value

You can also create JS functions that return values. Inside the function, you need to use the
keyword return followed by the value to be returned.

Syntax:
function functionname(arg1, arg2)

lines of code to be executed

return val1;

Try this yourself:


This code is editable. Click Run to Execute
<html>
<head>
<script type="text/javascript">
function returnSum(first, second)
{
var sum = first + second;

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

return sum;
}
var firstNo = 78;
var secondNo = 22;
document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
</script>
</head>
<body>
</html>

Introduction
A string is a sequence of one or more characters that may consist of letters, numbers, or
symbols. Each character in a JavaScript string can be accessed by an index number, and
all strings have methods and properties available to them.

String Primitives and String Objects


First, we will clarify the two types of strings. JavaScript differentiates between the string
primitive, an immutable datatype, and the String object.

In order to test the difference between the two, we will initialize a string primitive and a
string object.

// Initializing a new string primitive


const stringPrimitive = "A new string.";

// Initializing a new String object


const stringObject = new String("A new string.");
We can use the typeof operator to determine the type of a value. In the first example,
we simply assigned a string to a variable.

typeof stringPrimitive;
Output
string
In the second example, we used new String() to create a string object and assign it to
a variable.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

typeof stringObject;
Output
Object

Most of the time you will be creating string primitives. JavaScript is able to access and
utilize the built-in properties and methods of the String object wrapper without
actually changing the string primitive you've created into an object.

While this concept is a bit challenging at first, you should be aware of the distinction
between primitive and object. Essentially, there are methods and properties available to
all strings, and in the background JavaScript will perform a conversion to object and
back to primitive every time a method or property is called.

How Strings are Indexed


Each of the characters in a string correspond to an index number, starting with 0.

To demonstrate, we will create a string with the value How are you?.

H o w a r e y o u ?

0 1 2 3 4 5 6 7 8 9 10 11

The first character in the string is H, which corresponds to the index 0. The last character
is ?, which corresponds to 11. The whitespace characters also have an index, at 3 and 7.

Being able to access every character in a string gives us a number of ways to work with
and manipulate strings.

1. charAt(x) Returns the character at the “x” position within the string.

//charAt(x)

var myString = 'jQuery FTW!!!';

console.log(myString.charAt(7));

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//output: F

2. charCodeAt(x) Returns the Unicode value of the character at position “x” within the
string.

//charAt(position)

var message="jquery4u"

//alerts "q"

alert(message.charAt(1))

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.

//concat(v1, v2,..)

var message="Sam"

var final=message.concat(" is a"," hopeless romantic.")

//alerts "Sam is a hopeless romantic."

alert(final)

4. fromCharCode(c1, c2,…) Returns a string created by using the specified sequence


of Unicode values (arguments c1, c2 etc). Method of String object, not String instance.
For example: String.fromCharCode().

//fromCharCode(c1, c2,...)

console.log(String.fromCharCode(97,98,99,120,121,122))

//output: abcxyz

console.log(String.fromCharCode(72,69,76,76,79))

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

//output: HELLO

//(PS - I have no idea why you would use this? any ideas?)

Also see: Full List of JavaScript Character Codes

5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. “Start” is
an optional argument specifying the position within string to begin the search. Default is
0.

//indexOf(char/substring)

var sentence="Hi, my name is Sam!"

if (sentence.indexOf("Sam")!=-1)

alert("Sam is in there!")

6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. “Start” is an optional argument specifying the
position within string to begin the search. Default is string.length-1.

//lastIndexOf(substr, [start])

var myString = 'javascript rox';

console.log(myString.lastIndexOf('r'));

//output: 11

7. match(regexp) Executes a search for a match within a string based on a regular


expression. It returns an array of information or null if no match is found.

//match(regexp) //select integers only

var intRegex = /[0-9 -()+]+$/;

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var myNumber = '999';

var myInt = myNumber.match(intRegex);

console.log(isInt);

//output: 999

var myString = '999 JS Coders';

var myInt = myString.match(intRegex);

console.log(isInt);

//output: null

Also see: jQuery RegEx Examples to use with .match()

8. replace(regexp/substr, replacetext) Searches and replaces the regular expression


(or sub string) portion (match) with the replaced text instead.

//replace(substr, replacetext)

var myString = '999 JavaScript Coders';

console.log(myString.replace(/JavaScript/i, "jQuery"));

//output: 999 jQuery Coders

//replace(regexp, replacetext)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var myString = '999 JavaScript Coders';

console.log(myString.replace(new RegExp( "999", "gi" ), "The"));

//output: The JavaScript Coders

9. search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if
not found.

//search(regexp)

var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';

var isInt = myNumber.search(intRegex);

console.log(isInt);

//output: 0

var myString = '999 JS Coders';

var isInt = myString.search(intRegex);

console.log(isInt);

//output: -1

10. slice(start, [end]) Returns a substring of the string based on the “start” and “end”
index arguments, NOT including the “end” index itself. “End” is optional, and if none is
specified, the slice includes all characters from “start” to end of string.

//slice(start, end)

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

var text="excellent"

text.slice(0,4) //returns "exce"

text.slice(2,4) //returns "ce"

11. split(delimiter, [limit]) Splits a string into many according to the specified delimiter,
and returns an array containing each element. The optional “limit” is an integer that lets
you specify the maximum number of elements to return.

//split(delimiter)

var message="Welcome to jQuery4u"

//word[0] contains "We"

//word[1] contains "lcome to jQuery4u"

var word=message.split("l")

12. substr(start, [length]) Returns the characters in a string beginning at “start” and
through the specified number of characters, “length”. “Length” is optional, and if omitted,
up to the end of the string is assumed.

//substring(from, to)

var text="excellent"

text.substring(0,4) //returns "exce"

text.substring(2,4) //returns "ce"

13. substring(from, [to]) Returns the characters in a string between “from” and “to”
indexes, NOT including “to” inself. “To” is optional, and if omitted, up to the end of the
string is assumed.

//substring(from, [to])

var myString = 'javascript rox';

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

myString = myString.substring(0,10);

console.log(myString)

//output: javascript

14. toLowerCase() Returns the string with all of its characters converted to lowercase.

//toLowerCase()

var myString = 'JAVASCRIPT ROX';

myString = myString.toLowerCase();

console.log(myString)

//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted to uppercase.

//toUpperCase()

var myString = 'javascript rox';

myString = myString.toUpperCase();

console.log(myString)

//output: JAVASCRIPT ROX

JavaScript string (primitive or String object) includes default properties and


methods which you can use for different purposes.

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

String Properties
Property Description

length Returns the length of the string.

String Methods
Method Description

charAt(position) Returns the character at the specified position (in Number).

charCodeAt(position) Returns a number indicating the Unicode value of the character at the given
position (in Number).

concat([string,,]) Joins specified string literal values (specify multiple strings separated by
comma) and returns a new string.

indexOf(SearchString, Returns the index of first occurrence of specified String starting from
Position) specified number index. Returns -1 if not found.

lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from
Position) specified position. Returns -1 if not found.

localeCompare(string,position) Compares two strings in the current locale.

match(RegExp) Search a string for a match using specified regular expression. Returns a
matching array.

replace(searchValue, Search specified string value and replace with specified replace Value string
replaceValue) and return new string. Regular expression can also be used as searchValue.

search(RegExp) Search for a match based on specified regular expression.

slice(startNumber, Extracts a section of a string based on specified starting and ending index
endNumber) and returns a new string.

split(separatorString, Splits a String into an array of strings by separating the string into substrings
limitNumber) based on specified separator. Regular expression can also be used as
separator.

substr(start, length) Returns the characters in a string from specified starting position through
the specified number of characters (length).

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Method Description

substring(start, end) Returns the characters in a string between start and end indexes.

toLocaleLowerCase() Converts a string to lower case according to current locale.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.

toString() Returns the value of String object.

toUpperCase() Returns upper case string value.

valueOf() Returns the primitive value of the specified string object.

String Methods for Html


The following string methods convert the string as a HTML wrapper element.

Method Description

anchor() Creates an HTML anchor <a>element around string value.

big() Wraps string in <big> element.

blink() Wraps a string in <blink> tag.

bold() Wraps string in <b> tag to make it bold in HTML.

fixed() Wraps a string in <tt> tag.

fontcolor() Wraps a string in a <font color="color"> tag.

fontsize() Wraps a string in a <font size="size"> tag.

italics() Wraps a string in <i> tag.

link() Wraps a string in <a>tag where href attribute value is set to specified string.

small() Wraps a string in a <small>tag.

strike() Wraps a string in a <strike> tag.

sub() Wraps a string in a <sub>tag

VAPM,Almala-Inst.Code-1095
CSS[22519] MR.SWAMI R.S.{MOBILE NO:-+91-8275265361]

Method Description

sup() Wraps a string in a <sup>tag

VAPM,Almala-Inst.Code-1095

You might also like