Unit II - Array, Function and String
Unit II - Array, Function and String
Declaration of an Array
There are basically two ways to declare an array.
Example:
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.
2
Unit II - Array, Function and String
text = "<ul>";
for (i = 0; i < len; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
3
Unit II - Array, Function and String
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
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.
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
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
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
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
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
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
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
17