You are on page 1of 20

Chapter 2:Array, Function and String

1. Array- declaring an array, initializing array, defining an array elements, looping an array
Array:
• An array is a special variable, which can hold more than one value at a time.
• Array is an object that represents a collection of similar type of elements.
• There are 3 ways to construct array in JavaScript
I. By array literal
II. By creating instance of Array directly (using new keyword)
III. By using an Array constructor (using new keyword)

I) JavaScript array literal : The syntax of creating array using array literal is given below:
var arrayname=[value1,value2 valueN];
Ex:
<script>
var emp=["Sonoo","Vimal","Ratan"]; for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>

II) JavaScript Array directly (new keyword): The syntax of creating array directly is given below:
var arrayname=new Array();
<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>

III) 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>
Initializing array
- You can declare an array and specify values for elements at the same time. This is called initialisation
- This statement creates the scores array in a single line
scores = new Array(39,40,100,49);
- In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents.
- The following statement is an alternative way to create the scores array:
scores = [39,40,100,49];

defining and accessing array elements


scores[0] = 39;
scores[1] = 40;
scores[2] = 100;
scores[3] = 49;
scores = new Array(30);
document.write(scores.length);
test = new Array();
test[0]=21;
test[5]=22;
scoredisp = “Scores: “ + scores[0] + “,” + scores[1] + “,” +scores[2];
document.write(scoredisp);
looping an array :Looping of array can be done in following ways:
1. using standard loops
cars = {" alto", " verna" , " city" , "bolero" }
var i;
for (i = 0; i < cars.length; i++)
{
document.write(cars[i] + "<br>");
}
2. using forEach() Loop
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt = txt + value + "<br>";
}
3.using Array.map()
- The map() method creates a new array by performing a function on each array element.
- The map() method does not execute the function for array elements without values.
- The map() method does not change the original array.
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
4.using Array.filter()
-The filter() method creates a new array with array elements that passes a test.
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}

2. Adding an array element, sorting array element, combining an array elements into a string
Adding an array element: Elements in an array can be added at various locations as follows
a. adding elements at end of array: push method is used to add elements at end of array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
fruits.push("Kiwi", "Lemon", "Pineapple");
b. adding elements at beginning of array : unshift method is used for adding elements at the beginning of array
var list = ["foo", "bar"];
list.unshift("baz", "qux");
["baz", "qux", "foo", "bar"] // result
c. adding elements in between : splice method is used for adding elements in between. It need the position at which new
elements are to be added and the number of elements to be removed from that position
var list = ["foo", "bar"];
list.splice( 1, 0, "baz"); // at index position 1, remove 0 elements, then add "baz" to that position
["foo", "baz", "bar"]
d. adding array to another array: concat method is used for adding one array to another
var list = ["foo", "bar"];
var newlist = list.concat( ["baz", "qux"] );
["foo", "bar", "baz", "qux"] // newlist result
e. add an Array Element at a Particular Index:index position is used for adding elements at a particular position
var list = ["foo", "bar"];
list[2] = "baz"; // add element "baz" to the index position 2 in the array
list[3] = "qux";
["foo", "bar", "baz", "qux"] // result

sorting array element:


Sort() method is used to sort the array elements
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
To reverse an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Sort() method treats its objects as string so to sort numbers u have to use compare function
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

combining an array elements into a string:


- The join() method returns the array as a string.
- The elements will be separated by a specified separator. The default separator is comma (,).
- This method will not change the original array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(" and ");
o/p Banana and Orange and Apple and Mango
- The JavaScript method toString() also converts an array to a string of (comma separated) array values.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.toString(); will return a string as Banana,Orange,Apple,Mango
3. Changing elements of an array, Objects as associative arrays
Different Methods that can be used with arrays are:
Sr. Methods Description
No.

1. concat() It returns a new array object that contains two or more merged
arrays. array.concat(arr1,arr2, ......................................,arrn)
2. copyWithin() It copies the part of the given array with its own elements and returns the modified
array. array.copyWithin(target, start, end) target - The position where the copied
element takes place. start - It is optional. It represents the index from where the
method starts copying elements. By default, it is 0.
end - It is optional. It represents the index at which elements stops copying. By default,
it is array.length-1.
3. fill() It fills elements into an array with static values.
arr.fill(value[, start[, end]])
value - The static value to be filled.
start - It is optional. It represents the index from where the
value starts filling. By default, it is 0.
end - It is optional. It represents the index where the value stops
filling. By default, it is length-1.
4. includes() It checks whether the given array contains the specified element.
array.includes(element,start)
element - The value to be searched.
start - It is optional. It represents the index from where the method starts search
5. indexof() It searches the specified element in the given array and returns the index of the first
match. array.indexOf(element,index)
element - It represent the element to be searched.
index -It represent the index position from where search starts. It is optional.
6. join() It joins the elements of an array as a string.
array.join(separator)
Separator() - It is optional. It represent the separator used between array elements
7. lastindexof() It searches the specified element in the given array and returns the index of the last
match array.lastIndexOf(element,index) element - It represent the element to be
searched.
index - It represent the index position from where search starts. It is optional.
8. push() It adds one or more elements to the end of an array
array.push(element1,element2....element n)
9. pop() It removes and returns the last element of an array
array.pop()
10. reverse() It reverses the elements of given array.
array.reverse()
11. sort() It returns the element of the given array in a sorted order. By default, sort() method
follows the ascending order. array.sort(compareFunction)
compareFunction - It is optional. It represents a function that provides an alternative
sort order.
12. shift() The shift() method removes the first element of the given array and returns that
element. This method changes the length of the original array.
array. shift()

13. unshift() adds a new element to an array (at the beginning), and "unshifts" older elements:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits

14. delete() It is used to delete element from array


var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined

15. splice() This method can be used to add new items to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
New Array:
Banana,Orange,Lemon,Kiwi,Apple,Mango
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
16. slice() This method slices out a piece of an array into a new array. The slice() method creates a
new array. It does not remove any elements from the source array.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
o/p Orange,Lemon,Apple,Mango
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
Here the method selects elements from the start argument, and up to (but not including)
the end argument.
o/p : Orange,Lemon
If the end argument is omitted, like in the first examples, the slice() method slices out
the rest of the array.
var citrus = fruits.slice(2);
o/p Lemon,Apple,Mango

Objects as associative arrays


- Associative arrays are dynamic objects that the user redefines as needed.
- When you assign values to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and
methods of Array.
- The length attribute has no effect because the variable is not longer of Array type.
var arr = { "one": 1, "two": 2, "three": 3 };
- It uses key:value pairs separated by commas
- The content is accessed by keys
eg:array[“one”] or array.one
- Example
var o = new Object();
o["one"] = 1;
o["two"] = 2;
o["three"] = 3;
for(var i in o)
{
document.write(i + "=" + o[i] + '<br>');
}
o/p
one=1
two=2
three=3
4. Function-Defining a function, writing a function
- A JavaScript function is a block of code designed to perform a particular task.
- A JavaScript function is executed when "something" invokes it (calls it).
eg: function myFunction(p1, p2) {
return p1 * p2;
}
- There are mainly two advantages of functions.
• Code reusability: We can call a function several times so it save coding.
• Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
• Syntax:
function functionName([arg1, arg2, ...argN])
{
//code to be executed
}

Rules while defining a function


- A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
- Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
- The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
- The code to be executed, by the function, is placed inside curly brackets: {}

5. adding an arguments, scope of variable and arguments


- arguments are the parameters which are passed to a function
- example of adding arguments to a function:
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
- In JavaScript there are two types of scope:
i. Local scope
-Variables declared within a JavaScript function, become LOCAL to the function.
- Local variables have Function scope: They can only be accessed from within the function.
- Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
- Local variables are created when a function starts, and deleted when the function is completed.
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
ii. Global scope
- A variable declared outside a function, becomes GLOBAL.
- A global variable has global scope: All scripts and functions on a web page can access it.
- If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
- The lifetime of a JavaScript variable starts when it is declared.
- Local variables are deleted when the function is completed.
- In a web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded
into the same window.

6. calling a function- calling a function with or without an argument, calling function from HTML

To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following
code:

<script> function msg(){


alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
- We can call function by passing arguments.
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 Expressions
A JavaScript function can also be defined using an expression. A function expression can be stored in a variable:
Ex 1:
var x = function (a, b) {return a * b};
Ex 2:
var x = function (a, b) {return a * b}; var z = x(4, 3);

7. Function calling another function, returning a value from a function


Function Calling another function
A function can call another function from within.
Eg:
<script>
function display()
{
document.write("Welcome");
}
function welcome()
{
document.write("Hello");
display();
}
Function with Return Value
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This
statement should be the last statement in a function.
<script>
function getInfo()
{
return “Hello How r u?";
}
</script>
<script> document.write(getInfo());
</script>
8. String-manipulate a string, joining a string, retrieving a character from given position
- JavaScript strings are used for storing and manipulating text.
- A JavaScript string is zero or more characters written inside quotes.
- You can use single or double quotes:
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
- You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer2 = "He is called 'Johnny'";
- Normally, JavaScript strings are primitive values, created from literals:
var firstName = "John";
- But strings can also be defined as objects with the keyword new:
var firstName = new String("John");
- 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

9. Retrieving a position of character in a string, dividing text, copying a substring, converting a string to
number and numbers into string

Methods used with Strings:


a.concat(): It provides a combination of two or more strings.
Syntax: concat(str1,str2,...,strn)
Parameter: str1,str2,...,strn - It represent the strings to be combined. Return: Combination of strings.
Ex:
<script>
var x=“KKW"; var
y=“Poly";
document.writeln(x.concat(y));
</script>
//Output: KKWPoly
b. charAt(): The charAt() method is used to find out a char value present at the specified index in a string.
The index number starts from 0 and goes to n-1, where n is the length of the string. The index value can't be a negative,
greater than or equal to the length of the string.
Syntax: charAt(index)
Ex:
<script>
var str=“Welcome"; document.writeln(str.charAt(4));
</script>
//Output: ‘o’

c.charCodeAt(): The charCodeAt() method is used to find out the Unicode value of a character at the specific index in a
string.The index number starts from 0 and goes to n-1, where n is the length of the string. It returns NaN if the given index
number is either a negative number or it is greater than or equal to the length of the string.
Syntax: charCodeAt(index)
Ex:
<script>
var str=“Welcome"; document.writeln(str.charCodeAt(4));
</script>
//Output:111
d.indexOf(): The indexOf() method is used to search the position of a particular character or string in a sequence of given char values.
This method is case-sensitive.
Syntax:
- indexOf(ch):It returns the index position of first occurrence of char value passed with method.
- indexOf(ch,index): It start searching the element from provided index value and then returns the index position of first
occurrence of specified char value.
- indexOf(str):It returns the index position of first character of string passed with method.
- indexOf(str, index):It start searching the element from the provided index value and then returns the index position of first
character of string.
Parameters
ch - It represent the single character to search like 'a'.
index - It represent the index position from where search starts.
str - It represent the string to search like "Java".
Ex:
<script>
var s1=“Welcome To JavaScript"; document.write(s1.indexOf('a'));
</script>
//Output:12
e.lastIndexOf(): The lastIndexOf() method is used to search the position of a particular character or string in a sequence of given
char values. It behaves similar to indexOf() method with a difference that it start searching an element from the last position of the
string.
Syntax:
- lastIndexOf(ch)
- lastIndexOf(ch,index)
- lastIndexOf(str)
- lastIndexOf(str, index)
Parameters
ch - It represent the single character to search like 'a'.
index - It represent index position from where search starts. str - It represent the string to search like "Java".
Ex: <script>
var s1=“Welcome to JavaScript";
document.write(s1.lastIndexOf('a'));
</script>
//Output: 14
Note : Both indexOf(), and lastIndexOf() return -1 if the text is not found. The lastIndexOf() methods searches backwards
(from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the
beginning of the string.
f.search():This is used to search the regular expression in the given string. This method returns -1, if match is not found.
Syntax: search(regexp)
Parameter regexp - It represents the regular expression which is to be searched.
Return: The position of searched character.
Ex 1:
<script>
var str="JavaScript is a scripting language. Scripting languages are often interpreted";
document.writeln(str.search("scripting"));
</script>
//Output: 16
Ex 2:
<script>
var str="JavaScript is a scripting language. Scripting languages are often interpreted";
document.writeln(str.search(“Scripting"));
</script>
//Output: 36
g.match(): The match() method is used to match the string against a regular expression. We can use global search modifier with
match() method to get all the match elements otherwise the method return only first match.
Syntax: match(regexp)
Parameter: regexp - It represents the regular expression which is to be searched.
Return: The matched regular expression. Ex:
<script>
var str="JavaScript"; document.writeln(str.match("Java"));
</script>
//Output: Java
h.replace(): The replace() method is used to replace a part of a given string with a new substring. This method searches for
specified regular expression in a given string and then replace it if the match occurs.
Syntax: replace(originalstr,newstr)
Parameter: originalstr-It represents string to be searched & replaced.
newstr - It represents new string that replaced with searched string.
Return: It returns the new string with the specified replacement.
Ex: <script>
var str="Javalanguage"; document.writeln(str.replace(“language","Script"));
</script>
//Output: JavaScript
i) substr(): The substr() method fetch the part of the given string and return the new string. The number of characters to be fetched
depends upon the length provided with the method. This method doesn't make any change in the originalstring.
Syntax: substr(start,length)
Parameter: start - It represents the position of the string from where the fetching starts.
length - It is optional. It represents the number of characters to be fetched. It usually retrieves length-1 characters.
Return: Part of the string. Ex:
<script>
var str="JavaScript"; document.writeln(str.substr(0,4));
</script>
//Output: Java
j.substring(): The substring() method fetch the string on the basis of provided index and returns the new sub string. It works
similar to the slice() method with a difference that it doesn't accepts negative indexes. This method doesn't make any change in
the original string.
Syntax: substring(start,end)
Parameter: start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches
Return: Part of the string. Ex:
<script>
var str="JavaScript"; document.writeln(str.substr(0,4));
</script> //Output: Java
k) slice(): This method is used to fetch the part of the string and returns the new string. It required to specify the index number as
the start and end parameters to fetch the part of the string. The index starts from 0.
Syntax: slice(start,end)
Parameter: start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches. In other words, the end parameter is not included.
Return: Part of the string. Ex:
<script>
var str = “Welcome"; document.writeln(str.slice(2,5));
</script>
//output: lco
l)toLowerCase(): This method is used to convert the string into lowercase letter. This method doesn't make any change in the
original string.
Syntax: toLowerCase() Return: string in
Lower case. Ex: <script>
var str = “WELCOME"; document.writeln(str.toLowerCase());
</script>
//output: welcome
m)toUpperCase(): This method is used to convert the string into uppercase letter. This method doesn't make any change in the
original string.
Syntax: toUpperCase() Return: string in
Upper case. Ex: <script>
var str = “welcome"; document.writeln(str.toLowerCase());
</script>
//output: WELCOME
n) trim():method removes whitespace from both sides of a string
ex: var str = " Hello World! ";
alert(str.trim());

10. Finding a unicode of character- charCodeAt(), fromCharCode()

1. charCodeAt(): It returns the unicode of the character at a specified index in a string


var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
2. fromCharCode() : It converts a Unicode number into a character. This is a static method of the String object, and the syntax is always
String.fromCharCode()
eg: String.fromCharCode(72, 69, 76, 76, 79);
o/p : HELLO

You might also like