Unit II - Array, Function and String

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Unit II - Array, Function and String

Unit II - Array, Function and String


Array- JavaScript arrays are used to store multiple values in a single variable.
The Array in JavaScript is a global object which contains a list of items.
An array is an ordered collection of values: each value is called an element, and each element
has a numeric position in the array, known as its index.
or
In JavaScript, the array is a single variable that is used to store different elements. It is
often used when we want to store a list of elements and access them by a single variable.
Unlike most languages where array is a reference to the multiple variable, in JavaScript array is
a single variable that stores multiple elements.

Declaration of an Array
There are basically two ways to declare an array.
Example:

var House = [ ]; // method 1


var House = new array(); // method 2

But generally method 1 is preferred over method 2.


Example:

// Initializing while declaring


var house = ["ONE", "TWO", "THREE", "FOUR"];

// Defining the array element


house[0] = "ONE";
house[1] = "TWO";
house[2] = "THREE";
house[3] = "FOUR";

JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
Example
var cars = ["Swift", "Volvo", "BMW"];

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, ...];

1
Unit II - Array, Function and String

Example
var cars = ["Swift", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Swift",
"Volvo",
"BMW"
];
Putting a comma after the last element (like "BMW",) is inconsistent across browsers.

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Swift", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).

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 = ["Swift", "Volvo", "BMW"];
document.write(“The first Element is :” + cars[0]);
Note: Array indexes start with 0. [0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:
cars[0] = "Swift";
Example:
var cars = ["Swift", "Volvo", "BMW"];
cars[0] = "Alto800";
document.write(“The array element after change : ” + cars[0] );

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:
Example
var cars = ["Swift", "Volvo", "BMW"];
document.write(“The array element is : ” + cars );
Object:
var person = {firstName:" Brendan ", lastName:" Eich ", age:30};

2
Unit II - Array, Function and String

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in
an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:
Examples:
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays

The length Property


The length property of an array returns the length of an array (the number of array elements).
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
The length property is always one more than the highest array index.

Accessing the First Array Element


Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];
Accessing the Last Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];
Looping Array Elements
The safest way to loop through an array, is using a for loop:
Example
var fruits, text, len, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
len = fruits.length;

text = "<ul>";
for (i = 0; i < len; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

3
Unit II - Array, Function and String

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:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

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

Example
position 0th 1st 2nd 3rd
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits index position 6th
// this will creates holes at 4th and 5th position
Associative Arrays Or Objects as Associative Array:
1. Many programming languages support arrays with named indexes.
2. Arrays with named indexes are called associative arrays (or hashes).
3. JavaScript does not support arrays with named indexes.
4. In JavaScript, arrays always use numbered indexes.

Example
var person = [];
person[0] = " Brendan ";
person[1] = " Eich";
person[2] = 31;
var x = person.length; // person.length will return 3
var y = person[0];// person[0] will return "Brendan "
Important Note:
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.
Example:
var person = [];
person["firstName"] = " Brendan ";
person["lastName"] = " Eich ";
person["age"] = 31;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined

4
Unit II - Array, Function and String

Functions in JavaScript
A function is a set of statements that take inputs, do some specific computation
and produce output. Basically, a function is a set of statements that performs some
tasks or does some computation and then returns the result to the user.
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs, we
can call that function.
Like other programming languages, JavaScript also supports the use of
functions. You must already have seen some commonly used functions in JavaScript
like alert(), this is a built-in function in JavaScript. But JavaScript allows us to create
user-defined functions also.
We can create functions in JavaScript using the keyword function. The basic
syntax to create a function in JavaScript is shown below.
Syntax:
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}
1. To create a function in JavaScript, we have to first use the keyword function,
separated by name of function and parameters within parentheses.
2. The part of the function inside the curly braces {} is the body of the function.

Function Definition
Before, using a user-defined function in JavaScript we have to create one. We
can use the above syntax to create a function in JavaScript. Function definition are
sometimes also termed as function declaration or function statement.
Below are the rules for creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user defined function name which should be unique,

5
Unit II - Array, Function and String

A list of parameters enclosed within parentheses and separated by commas,


A list of statements composing the body of the function enclosed within curly
braces {}.
Example:
Function add(number1, number2)
{
return number1 + number2;
}
In the above example, we have created a function named add, this function accepts two
numbers as parameters and returns the addition of these two numbers.
Function Parameters or arguments
Till now we have heard a lot about function parameters but haven‟t discussed
them in detail. Parameters are additional information passed to a function. For example,
in the above example, the task of the function add() is to calculate addition of two
numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in
JavaScript can have any number of parameters and also at the same time a function in
JavaScript can not have a single parameter.
Scope of Variable and arguments:
JavaScript Function Scope
In JavaScript there are two types of scope:
1. Local scope
2. Global scope
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.

6
Unit II - Array, Function and String

Local variables have Function scope: They can only be accessed from within the
function.
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
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.

Global JavaScript Variables


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.
Example
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}

Calling Functions:
After defining a function, the next step is to call them to make use of the function.
We can call a function by using the function name separated by the value of parameters
enclosed between parentheses and a semicolon at the end. Below syntax shows how to
call functions in JavaScript:

7
Unit II - Array, Function and String

functionName( Value1, Value2, ..);


Below is a sample program that illustrates the working of functions in
JavaScript:
<script type = "text/javascript">
// Function definition
function welcomeMessage(name) {
document.write("Hello " + name + " welcome to JavaScript");
}
// creating a variable
var name = "Admin";
// calling the function
welcomeMessage(name);
</script>
Output:
Hello Admin welcome to JavaScript
Calling function from HTML:
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns
the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>

8
Unit II - Array, Function and String

</body>
</html>
Output:
This example calls a function which performs a calculation and returns the result:
12

Return Statement:
There are some situations when we want to return some values from a function
after performing some operations.
In such cases, we can make use of the return statement in JavaScript.This is an
optional statement and most of the time the last statement in a JavaScript function.Look
at our first example with the function named as calcAddition. This function is calculating
two numbers and then returning the result. The most basic syntax of using the return
statement is:
return value;
The return statement begins with the keyword return separated by the value which we
want to return from it. We can use an expression also instead of directly returning the
value.

String:
The JavaScript string is an object that represents a sequence of characters.
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.
Manipulation of String:
Manipulating string values is a common function. This ranges from extracting portions of a string
to determine if a string contains a specific character. The following JavaScript functions for
manipulating a String using functions or methods:
concat() - Combines the text of two or more strings and returns a new string.
indexOf() – Returns the starting index of a substring within another string. A –1 is returned if no
match is found.

9
Unit II - Array, Function and String

charAt() – Returns the character at the specified location.


lastIndexOf() - Returns the index within the string of the last occurrence of the specified value,
or -1 if not found.
match() - Used to match a regular expression against a string.
substring() – A portion of a string is returned. A starting and ending location are passed to this
function.
replace() – Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search() - Executes the search for a match of a regular expression. If successful, search returns
the index of the match inside the string. Otherwise, it returns -1.
slice() - Extracts a section of a string and returns a new string.
split() - Splits a string into an array of strings by separating the string into substrings.
length() – The length of the string is returned as the count of the number of characters it
contains.
toLowerCase() – Converts the entire string to lowercase.
toUpperCase() – Converts the entire string to uppercase.

Joining a String:
The JavaScript string concat() method combines two or more strings and returns a new string.
This method doesn't make any change in the original string.
Syntax: The concat() method is represented by the following syntax:
string.concat(str1,str2,...,strn)
Parameter: str1,str2,...,strn - It represents the strings to be combined.
It returns a combination of strings.
Example:
Here, we will print the combination/joining of two strings.
<script>
var x="Java";
var y="Script";
document.writeln(x.concat(y));
</script>
Output: JavatScript

10
Unit II - Array, Function and String

Retrieving a character from given position:


The JavaScript string 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:
The charAt() method is represented by the following syntax:
String.charAt(index)
Parameter:
index - It represents the position of a character.
It returns a char value
JavaScript String charAt() Method Example
<script>
var str="JavaScript";
document.writeln(str.charAt(4));
</script>
Output: S

Retrieving a position of a character in a string:


The JavaScript string indexOf() method is used to search for the position of a particular
character or string in a sequence of given char values. This method is case-sensitive.
The index position of the first character in a string always starts with zero. If an element is not
present in a string, it returns -1.
Syntax:
These are the following methods used to search for the position of an element.
Method Description
indexOf(ch) It returns the index position of char value passed with method.
indexOf(ch,index) It start searching the element from the provided index value and
then returns the index position of specified char value.
indexOf(str) It returns the index position of the 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 the first character of the string.

11
Unit II - Array, Function and String

Parameters:
ch - It represents the single character to search like 'a'.
index - It represents the index position from where search starts.
str - It represents the string to search like "Java".
It returns the index of a particular character.
Example 1
Here, we will print the position of a single character.
<script>
var str="Hello this is just print Hello Javascript message";
document.write(str.indexOf('e'));
</script>
Output: 2
Example 2
In this example, we will provide the index value from where the search starts.
<script>
var str="Hello this is just print Hello Javascript message";
document.write(str.indexOf('i',8));
</script>
Output: 11
Example 3
Here, we will print the position of the first character of string.
<script>
var str="Hello this is just print Hello Javascript message";
document.write(str.indexOf("Hello"));
</script>
Output:
0
Example 4
In this example, we will provide the index value from where the search starts.
</script>
var str="Hello this is just print Hello Javascript message";
document.write(str.indexOf("Hello",7));
</script>
Output: 25

12
Unit II - Array, Function and String

Example 5
Here, we will try to search the element by changing its case-sensitivity.
<script>
var str="Hello this is just print Hello Javascript message";
document.write(str.indexOf("hello"));
</script>
Output: -1

Dividing [split] Text:


split() function is used to split the given string into an array of strings by separating it into
substrings using a specified separator provided in the argument.
Syntax:
str.split(separator, limit)
Parameter:
The first argument to this function is a string which specifies the points where the split has to
take place. This argument can be treated as a simple string or as a regular expression. If the
separator is unspecified then the entire string becomes one single array element. The same
also happens when the separator is not present in the string. If the separator is an empty string
(“”) then every character of the string is separated.
The second argument to the function limit defines the upper limit on the number of splits to be
found in the given string. If the string remains unchecked after the limit is reached then it is not
reported in the array.
This function returns an array of strings that is formed after splitting the given string at each
point where the separator occurs.
Example 1:
var str = 'It iS a JavaScript'
var a = str.split(" ");
document.write(a);
Output:
It,iS,a,JavaScript
In this example the function split() creates an array of strings by splitting str wherever ” “ occurs.

13
Unit II - Array, Function and String

Example 2:
var str = 'It iS a JavaScript'
var a = str.split(" ",2);
print(a);
Output:
[It,iS]
In this example the function split() creates an array of strings by splitting str wherever ” “ occurs.
The second argument 2 limits the number of such splits to only 2.

Copying a substring:
The JavaScript string substring() method fetches the string on the basis of the provided
index and returns the new substring. It works similar to the slice() method with a difference that
it doesn't accept negative indexes. This method doesn't make any change in the original string.
Syntax:
string.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.
It returns a part of the string or copy of string.
JavaScript String substring() Method Example
Example
<script>
var str="JavaScript";
document.writeln(str.substring(0,4));
</script>
Output: Java

Converting a String to Number and Number to String:


1. String to Number:
The JavaScript number parseInt() method parses a string argument and converts it into an
integer value. With string argument, we can also provide radix argument to specify the type of
numeral system to be used.
Syntax: The parseInt() method is represented by the following syntax:

14
Unit II - Array, Function and String

Number.parseInt(string, radix)
Parameter
string - It represents the string to be parsed.
radix - It is optional. An integer between 2 and 36 that represents the numeral system to
be used.
It returns an integer number. It returns NaN, if the first character cannot be converted to
a number.
JavaScript Number parseInt() method example
Here, we will understand the parseInt() method through various examples.
Example 1
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
document.writeln(Number.parseInt(c)+"<br>");
document.writeln(Number.parseInt(d)+"<br>");
document.writeln(Number.parseInt(e));
</script>
Output:
50
50
NaN
50
50
2. Number to String:
The JavaScript toString() method returns a string representing the calling object and also
converts the number into string.
Syntax: The toString() method is represented by the following syntax:
object.toString()

15
Unit II - Array, Function and String

<script>
var num = 15;
var n = num.toString(); //convert number into string
document.write(n + 1); // display result as concat string
</script>
Output: 151
// it concat value of num with 1 so output is 151

Changing Case of String:


JavaScript String toLowerCase() Method
The JavaScript string toLowerCase() method is used to convert the string into lowercase letters.
This method doesn't make any change in the original string.
Syntax: The toLowerCase() method is represented by the following syntax:
string.toLowerCase()
It returns a string in lowercase letters.

JavaScript String toLowerCase() Method Example


Let's see some simple examples of toLowerCase() method.
Example
Here, we will print the string in lowercase letter.
<script>
var str = "JAVASCRIPT";
document.writeln(str.toLowerCase());
</script>
Output: javatscript
JavaScript String toUpperCase() Method
The JavaScript string toUpperCase() method is used to convert the string into uppercase letters.
This method doesn't make any change in the original string.
Syntax: The toUpperCase() method is represented by the following syntax:
string.toUpperCase()
It returns a string in uppercase letter.
JavaScript String toUpperCase() Method Example
Let's see some simple examples of toUpperCase() method.

16
Unit II - Array, Function and String

Example
Here, we will print the string in uppercase letter.
<script>
var str = "javascript";
document.writeln(str.toUpperCase());
</script>
Output: JAVASCRIPT

Finding a Unicode of the character:


charCodeAt() Method - The JavaScript string charCodeAt() method is used to find out the
Unicode value of a character at a 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: The charCodeAt() method is represented by the following syntax
string.charCodeAt(index)
Parameter: index - It represents the position of a character.
It returns a Unicode value
Example
Here, we will print the Unicode value of a character by passing its specific index.
<script>
var x="JavaScript";
document.writeln(x.charCodeAt(3));
</script>
Output: 97 //unicode at 3rd position character means small case letter „a‟ is 97
fromCharCode() Method:
The fromCharCode() method converts Unicode values into characters.
Note: This is a static method of the String object, and the syntax is always
String.fromCharCode(value1,value2, . . . , valueN)
Example:
<script> var str = String.fromCharCode(72);
document.write(“The char code value is =” + str);
</script> O/P : H

17

You might also like