CSS Unit02 Final
CSS Unit02 Final
JavaScript Array
An array is a special type of variable, which can store multiple values using special syntax.
Every value is associated with numeric index starting with 0. The following figure illustrates
how an array stores values.
JavaScript Array
Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array
constructor.
a) Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in
square brackets.
Syntax:
var array_name = [element0, element1, element2,... elementN];
The following example shows how to define and initialize an array using array literal
syntax.
Example:
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var mixedArray = [1, "two", "three", 4];
JavaScript array can store multiple element of different data types. It is not required to store
value of same data type in an array.
b) Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:
Var arrayName = new Array ( Number length ); //creates new array with specified length
Syntax.
Var arrayName = new Array (element1, element2, element3, elementN); // creates new
array with elements specified in the bracket
Example:
var mixed Array = new Array(1, "two", 3, "four");
2) Array can be declared first and we can define the elements later. For this array make
use of index.
Example
Array can only have numeric index (key). Index cannot be of string or any other data type.
Example:
length property
Array includes “length” property which returns number of elements in the array.
Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.length; // the length of fruits is 4
<script type=”text/javascript”>
var Arr = new Array("one", "two", "three", "four");
for (var i = 0; i < Arr.length ; i++)
{
document.write(Arr[i]);
}
</script>
Syntax
The push() method is represented by the following syntax:
array.push(element1,element2 ... elementn)
Let's see some examples of push() method
Example 1
<script>
var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
document.writeln("Update array: "+arr);
</script>
Output:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Example 1
Let's see a simple example to sort the array of string elements.
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.sort();
document.write(result)
</script>
Output:
Apple,Mango,Pineapple,WaterMelon
Numeric Sort
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than
"1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
<script type="text/javascript">
var arr=[100,25,200,30,45]
var result=arr.sort();
document.write(result)
</script>
Output:
100,200,25,30,45
When the sort() function compares two values, it sends the values to the compare function,
and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values.
Example:
The compare function compares all the values in the array, two values at a time (a, b).
When comparing 40 and 100, the sort() method calls the compare function(40, 100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort
function will sort 40 as a value lower than 100.
Example
Arrange the elements in ascending order using function.
<script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
return a-b;
});
document.writeln(result);
</script>
Output:
20,40,50,80,100
Reversing an Array
The reverse() method reverses the elements in an array. You can use it to sort an array in
descending order:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements
Example
Arrange the elements in descending order using function.
<script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
return b-a;
});
document.writeln(result);
</script>
Output:
100,80,50,40,20
Example 1:
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.join();
document.write(result)
</script>
Output:
Mango,Apple,WaterMelon,Pineapple
Example 2
In this example, we will separate the array elements using '-' separator.
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.join('-');
document.write(result)
</script>
Syntax:
array.concat(arr1,arr2, ... ,arrn)
Parameter:
arr1,arr2, .. ,arrn - It represent the arrays to be combined.
Return :
A new array object that represents a joined array.
Example 1
Here, we will print the combination of two arrays.
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android
Example 2
Here, we will print the combination of three arrays.
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
var result=arr1.concat(arr2,arr3);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android,Ruby,Kotlin
Syntax
array.slice(start,end)
Parameter
start - It is optional. It represents the index from where the method starts to extract the
elements.
end - It is optional. It represents the index at where the method stops extracting elements.
Return
A new array contains the extracted elements.
Example
<script>
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var result = arr.slice(1, 3);
document.writeln(result);
</script>
Output:
Orange,Lemon
If the end argument is omitted, like in the first examples, the slice() method slices out the rest
of the array.
Example
<script>
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var result = arr.slice(1);
document.writeln(result);
</script>
Output:
Orange,Lemon,Apple,Mango
Return
The last element of given array.
Example 1
<script type="text/javascript">
var arr=["Mango","Apple","WaterMelon","Pineapple"]
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
</script>
Output:
Original array: Mango,Apple,WaterMelon,Pineapple
Extracted element: Pineapple
Remaining elements: Mango,Apple,WaterMelon
Example 2
In this example, we will pop all the elements from the given array.
<script>
var arr=["Mango","Apple","WaterMelon","Pineapple"]
var len=arr.length;
for(var x=1;x<=len;x++)
{
document.write("Extracted element: "+arr.pop()+"<br>");
}
</script>
Output:
Extracted element: Pineapple
Extracted element: WaterMelon
Extracted element: Apple
Extracted element: Mango
Syntax
for (key in object)
{
// code block to be executed
}
In each iteration of the loop, a key is assigned to the key variable. The loop continues for all
object properties.
Note: Once you get keys, you can easily find their corresponding values.
Example
<script type="text/javascript">
var person = {fname:"Spc", lname:"Academy", age:25}; for
(x in person)
{
document.write(x+":"+person[x]);
}
</script>
Example Explained
The for in loop iterates over a person object
In each iteration key is assigned to variable x.
These keys are used to access the value of the key.
The value of the key is person[x]
Example:
<script type="text/javascript">
var numbers = [45, 4, 9, 16, 25];
for (key in numbers)
{
document.write(key+":"+numbers[key]+"<br>"); }
</script>
Output:
0:45
1:4
2:9
3:16
4:25
Example:
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}
Unlike simple arrays, here we use curly braces instead of square brackets.
This has implicitly created a variable of type Object.
The content is accessed by keys, whatever the method used to declare the array.
<script type="text/javascript">
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}
var x = employee[101];
document.write(x);
</script>
<script type="text/javascript">
var employee = new Object();
employee["one"] = "Akshay";
employee["two"] = "Sai";
employee["three"] = "Amol";
for(var i in employee)
{
document.write(i + "=" + employee[i] + '<br>');
}
</script>
<script type="text/javascript">
var employee = new Object();
employee.one = "Akshay";
employee.two = "Sai";
employee.three = "Amol";
for(var i in employee)
{
document.write(i + "=" + employee[i] + '<br>');
}
</script>
Function
A function is a group of statements that perform specific tasks.
We can write the functions in the JavaScript for bringing the modularity in the script.
Separate functions can be created for each separate task.
Defining a Function
We can define the function anywhere in the script either in head or body section or in both.
But it is standard practice to define the function in the head section and call that function
from the body section
The declaration of a function start with the function keyword, followed by the name of the
function you want to create, followed by parentheses i.e. ( ) and finally place your function's
code between curly brackets {}.
function functionName( )
{
// Code to be executed
}
Example:
// Defining function
function sayHello( )
{
alert("Hello, welcome to Spc!");
}
Note: A function name must start with a letter or underscore character not with a number,
optionally followed by the more letters, numbers, or underscore characters. Function names are
case sensitive, just like variable names.
Example
The displaySum() function in the following example takes two numbers as arguments, simply
add them together and then display the result in the browser.
// Defining function
function displaySum (num1, num2)
{
var total = num1 + num2;
alert(total);
}
// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12
Calling a Function
Defining a function does not execute it. Defining it simply names the function and specifies
what to do when the function is called.
Once a function is defined it can be called (invoked) from anywhere in the document, by typing
its name followed by a set of parentheses.
Syntax: functionName( );
</body>
</html>
For calling a function from HTML normally, JavaScript events are used. For example the function
will be called in response to an event such as web page is loaded or unloaded by the browser.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
<script type="text/javascript">
function sum(a,b)
{
var tot = a+b;
document.write("Total is" + tot)
difference(a,b);
}
function difference(a,b)
{
var result = a-b;
document.write("<br>Difference is" + result)
}
</script>
</head>
<body>
<script type="text/javascript">
sum(50,34);
</script>
</body>
</html>
The return statement usually placed as the last line of the function before the closing curly
bracket and ends it with a semicolon, as shown in the following example.
Example
function sum(a, b)
{
return a + b;
}
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function A()
{
var a =100 //local variable
document.write ("from function A (): a is" + a)
}
function B()
{
document.write ("from function B (): a is" + a) // variable a is not accessible
}
</script>
</head>
<body>
<script type = "text/javascript">
A( )
B( )
</script>
</body>
</html>
Output:
from function A (): a is100
Explanation:
(1) We have created two functions namely A() and B().
(2) Inside the A() function variable ‘a’ is declared and initialized to the value 100. The value of
this variable is displayed. Here variable ‘a’ is accessible.
(3) Inside the B() function, we are trying to display the value of same variable a. But the output
does not display value of variable ‘a’ through function B(). This is because variable a is a local
variable declared in function A(). Hence its scope is upto the function A(). Outside this function,
the variable a is not accessible.
Global Variable
A variable is called global variable, if it is defined outside the function. The variable having
global scope is accessible by any function.
Following example illustrates the use of global variable.
JavaScript Example for Demonstrating the scope of Global Variable
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
var a =100//global variable
function A()
{
document.write ("from function A (): a is" + a)
}
function B()
{
document.write ("<br> from function B (): a is" + a)
}
</script>
</head>
<body>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
JavaScript strings are used for storing and manipulating text.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes.
syntax:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
This is string literal
Methods Description
charCodeAt() It provides the Unicode value of a character present at the specified index.
indexOf() It provides the position of a char value present in the given string.
It is used to fetch the part of the given string on the basis of the specified
substr()
starting position and length.
It is used to fetch the part of the given string on the basis of the specified
substring()
index.
It is used to fetch the part of the given string. It allows us to assign positive
slice()
as well negative index.
toLocaleLowerCase It converts the given string into lowercase letter on the basis of host?s
() current locale.
toLocaleUpperCase It converts the given string into uppercase letter on the basis of host?s
() current locale.
It splits a string into substring array, then returns that newly created
split()
array.
trim() It trims the white space from the left and right side of the string.
Joining a String
1) using + operator.
For Example
<!DOCTYPE html>
<html>
<script type = "text/javascript">
var firstName="AAA"
var lastName="BBB"
var name=firstName+lastName
alert(name);
</script>
<body>
</body>
</html>
Output: AAABBB
Syntax
string.concat(str1,str2,...,strn)
Parameter
str1,str2,...,strn - It represent the strings to be combined.
Return
Combination of strings.
Example 1:
<script>
var x="Spc";
var y=".com";
var z=" Tutorials";
</script>
Output:
Javatpoint.com Tutorials
Example 2
<script>
var str="Javatpoint";
document.writeln(str.charAt()); //print first character
</script>
Output:
J
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
string.charCodeAt(index)
Parameter
index - It represent the position of a character.
Return
A Unicode value
Example 1
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
Output:
97
Example 2
In this example, we will not pass any index number with the method. In such case, it will
return the Unicode value of first character.
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
</script>
Output:
74
Syntax
indexOf(ch,index)
It start searching the element from the provided index value and then returns the index
position of specified char value.
index - It is optional which represent the index position from where search starts.
Example 1
Here, we will print the position of a single character.
<script>
var web="Learn JavaScript on Javatpoint";
document.write(web.indexOf('a'));
</script>
Output:
2
Example 2
In this example, we will provide the index value from where the search starts.
<script>
var web="Learn JavaScript on Javatpoint";
document.write(web.indexOf('a',3));
</script>
Output:
7
2) search() Method
The JavaScript string search() method is used to search the regular expression in the given
string. This method returns -1, if match is not found.
Syntax
string.search(regexp)
Parameter
regexp - It represents the regular expression which is to be searched.
Return
The position of searched character.
Example:
<script>
var str="JavaScript is a scripting language. Scripting languages are often interpreted";
document.writeln(str.search("scripting"));
</script>
Output:
16
Copying a substring
1) substr() Method
The JavaScript string 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 original string.
Syntax
string.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 fetch.
Return: Part of the string.
Example:
<script>
var str="Javatpoint";
document.writeln(str.substr(0,4));
</script>
Output:
Java
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.
Return: Part of the string.
Example
<script>
var str="Javatpoint";
document.writeln(str.substring(0,4));
</script>
Output:
Java
The JavaScript string slice () method is used to fetch the part of the string and returns the new
string. It is required to specify the index number as the start and end parameters to fetch the
part of the string. The index starts from 0. It allows us to assign positive as well negative index.
Syntax
string.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.
Return
Part of the string
Example 1
Here, we will print the part of the string by passing starting and ending index.
<script>
var str = "SpcAcademy";
document.writeln(str.slice(2,5));
</script>
Output:
row
Example 2
Here, we will provide starting index only. In such case, the method fetches the string up to its
length.
<script>
var str = "SpcAcademy";
document.writeln(str.slice(4));
</script>
Output:
wAcademy
Example 3
In this example, we will provide negative number as an index. In such case, the method starts
fetching from the end of the string.
<script>
var str = "SpcAcademy";
document.writeln(str.slice(-5));
</script>
Output:
ademy
syntax
parseInt(value);
This function takes a string and converts it into an integer. If there is no integer present in the
string, NaN will be the output.
Example
In the following example, various cases of strings such as only strings, strings with
numbers, etc have been taken and sent through the parseInt() function. Later on, their
integer values, if present, have displayed as shown in the output.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script>
var a = "10";
document.write("value is " + parseInt(a)+"<br>");
var b = "420-23-567";
document.write('value is ' + parseInt(b)+"<br>");
var c = "string";
document.write("value is " + parseInt(c)+"<br>");
var d = "2String"
document.write("value is " + parseInt(d)+"<br>");
</script>
</head>
<body>
</body>
</html>
Output
value is 10
value is 420
value is NaN
value is 2
Output:
Spcacademy
2) toUpperCase() Method
The JavaScript string toUpperCase() method is used to convert the string into uppercase letter.
This method doesn't make any change in the original string.
Syntax
string.toUpperCase()
Return
String in uppercase letter.
Example
<script>
var str = "javatpoint";
document.writeln(str.toUpperCase());
</script>
Output:
JAVATPOINT
Dividing Text
String split()
As the name implies, the split() method in JavaScript splits the string into the array of
substrings, puts these substrings into an array, and returns the new array. It does not change
the original string.
Syntax
string.split(separator, limit)
separator: It is an optional parameter. It specifies the point where the split should take place.
If it has multiple characters, then the sequence of the entire character must be found to split.
If the separator is not present in the given string, or if it is omitted, then the entire string
becomes a single array element. In these cases, the returned array contains a single element
consisting of the entire string.
If the separator is present at the beginning or the end of the string, then it still has the effect of
splitting. The returned array consists of an empty string of zero length that appears at the
beginning or the last position of the returned array.
limit: It is also an optional parameter. It is a non-negative integer that specifies the number of
limits. It defines the higher limit on the number of splits to be found in the given string. If it is
given, it splits the string at each occurrence of the specified separator. It stops when the limit
entries have been placed in the array.
An array can contain fewer entries than the given limit. It happens when the end of the string
is reached before the limit is reached.
Example1
In this example, the split() function splits the string str wherever the whitespace (" ") occurs and
returns an array of strings. Here, we are using the limit argument and providing the value of the
limit argument to 3.
<script>
var str = 'Welcome to the Spc Computer Academy'
var arr = str.split(" ", 3);
document.write(arr);
</script>
Output
Welcome,to,the
Example2
In this example, we are using the letter 't' as the separator of the given string. The split() function
will make an array of strings by splitting the given string at each occurrence of the letter 't'.
Here, we are not specifying the limit argument.z
<script>
var str = 'Welcome to the Spc Academy'
var arr = str.split("t");
document.write(arr);
</script>
Output
Welcome ,o ,he Spc Academy
Example 3
In this example, we are omitting the separator parameter. In the output, we can see that the
returned array contains a single element consists of the given string.
<script>
var str = "Welcome to the Spc Academy"
var arr = str.split();
document.write(arr);
</script>
Output
Welcome to the Spc Academy