0% found this document useful (0 votes)
6 views

CSS UNIT II

The document covers various concepts of arrays, functions, and strings in JavaScript, including array declaration, initialization, and methods for adding and removing elements. It also explains the scope of variables, calling functions, and returning values from functions, along with examples of each concept. Additionally, it discusses the use of strings and provides code snippets to illustrate the implementation of these concepts.

Uploaded by

hj05102006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CSS UNIT II

The document covers various concepts of arrays, functions, and strings in JavaScript, including array declaration, initialization, and methods for adding and removing elements. It also explains the scope of variables, calling functions, and returning values from functions, along with examples of each concept. Additionally, it discusses the use of strings and provides code snippets to illustrate the implementation of these concepts.

Uploaded by

hj05102006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CSS UNIT II : ARRAY, FUNCTION, STRINGS

ARRAY

i) Array It used to store multiple values in a single variable.

ii) Values in array are accessed, Modified by Array indices.

iii) start with zero and end with N – 1 where N is size of array.

iv) In javascript array is a flexible in nature. i.e size of array changes automatically as per
insertion of new values in array. If we delete existing element in array, then array size decrease
automatically.

WAP To implement type of declaration of array and print size.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<script>

var arr1 = new Array(); //empty array

var arr2 = new Array(3);

var arr3 = new Array(1, 2, 3, 4, 5, 6);

document.write("<br> size of array 1 = " + arr1.length);

document.write("<br> size of array 2 = " + arr2.length);

document.write("<br> size of array 3 = " + arr3.length);


</script>

</body>

</html>

Output :

size of array 1 = 0
size of array 2 = 3
size of array 3 = 6

WAP To initialize elements of array and print them.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<script>

var arr = new Array();

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

document.write("<br>First Element = "+arr[0]);

document.write("<br>Second Element = "+arr[1]);

document.write("<br>Third Element = "+arr[2]);

</script>
</body>

</html>

Output :

First Element = 10
Second Element = 20
Third Element = 30

WAP to implement array as a collection different data type elements.

<body>

<script>

let arr = new Array();

arr[0] = 10;

arr[1] = "dev";

arr[2] = 34.4;

arr[3] = true;

for (let i = 0; i < arr.length; i++) {

document.write("<br>Element " + i + " = " + arr[i]);

</script>

Output :

Element 1 = dev
Element 2 = 34.4
Element 3 = true
WAP To implement two dimension array in javascript.

i) Js does not support two dimensional array.

ii) However, we can implement the concept of two dimensional array by creating array of an
array.

<body>

<script>

//creating 2d arry of rows 3 and column 3

let arr = new Array(3);

for (let i = 0; i < arr.length; i++) {

arr[i] = new Array(3);

//initializing array element

arr[0][0] = 1;

arr[0][1] = 2;

arr[0][2] = 3;

arr[1][0] = 4;

arr[1][1] = 5;

arr[1][2] = 6;

arr[2][0] = 7;

arr[2][1] = 8;

arr[2][2] = 9;

//displaying array elements

for (let i = 0; i < arr.length; i++) {


for (let j = 0; j < arr.length; j++) {

document.write(arr[i][j]+" ");

document.write("<br>"); //line break after each row

</script>

</body>

Output :

123
456
789

Adding new element in the Array:

i) Sometime it is necessary to add extra element in the existing array of specific size.

ii) We can do this by following three methods.

1. push( ) method :

i) The push method is used to add one or more elements at the end of the array.

ii) syntax : arrayname.push(element1,element2……elementN);

2. unshift( ) method :

i) the unshift( ) method is used to add one or more elements at the beginning of array.

ii) syntax : arrayname.unshift(value1,value2…….valueN);

3. length property of array :

i) syntax : arrayname.[arrayname.length] = new_value;


Note : using length property we can add only one value.

WAP to implement technique to add elements in Array.

<body>

<script>

let arr = new Array(2);

arr[0] = 10;

arr[1] = 20;

for (let i = 0; i < arr.length; i++) {

document.write(" " + arr[i]);

document.write("<br>");

//directly adding elements

arr[2] = "direct";

//using push() method (back)

arr.push("push1", "push2");

//using unshift() method (front)

arr.unshift("unshift");

//using length property

arr[arr.length] = "lengthproperty";

for (let i = 0; i < arr.length; i++) {

document.write(" " + arr[i]);

}
</script>

</body>

Output :

10 20
unshift 10 20 direct push1 push2 lengthproperty

Remove elements from the array :

1. pop( ) method

The pop( ) method is used to remove existing element from end of the array.

2. shift( ) method

The shift( ) method is used to remove exiting element from first index of array.

WAP to implement pop( ) and shift( ) method

<body>

<script>

let arr = new Array(3);

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

document.write("Array elements:<br>")

for (let i = 0; i < arr.length; i++) {

document.write(arr[i], " ");


}

document.write("<br>Array elements after pop :<br>")

arr.pop(); //removes elements from last position

for (let i = 0; i < arr.length; i++) {

document.write(arr[i], " ");

arr.shift(); //removes element from first position

document.write("<br>Array elements after shift : <br>");

for (let i = 0; i < arr.length; i++) {

document.write(arr[i], " ");

</script>

</body>

Output :

Array elements:
10 20 30
Array elements after pop :
10 20
Array elements after shift :
20

Combining array elements into string :

1. concat( ) method

2. join( ) method
1. concate( ) method

i) The concat( ) method is used to combine two or more arrays.

ii) Each element of the array is separated comma (,) by default.

iii) Syntax to combine element of single array

arrayname.concate( );

iv) syntax to combine element of multiple array

arrayname.concate(arrayname1,arrayname2…..);

Here elements of array2 and array3 will combine to element of array 1.

WAP to implement concate( ) method

<body>

<script>

let a = [1, 2, 3];

let s1 = a.concat();

document.write(s1);

let b = [4, 5, 6];

let s2 = a.concat(b);

document.write("<br>" + s2);

</script>

</body>

Output :
1,2,3
1,2,3,4,5,6

2.join( ) method :

i) The join method is also used to combine element of array into string separated by comma(,)
by default.

ii) using joint method, we can use any special symbol to separate elements of array like #, @, -
etc.

iii) syntax : arrayname.join(“separator”);

WAP to implement join( ) method.

<body>

<script>

let a = [1, 2, 3];

let b = [4, 5, 6];

let s1 = a.join();

document.write(s1);

let s2 = a.join("#");

document.write("<br>" + s2);

</script>

</body>

Output :

1,2,3
1#2#3
Sorting elements of Array :

i) syntax to sort elements of array in ascending order :

arrayname.sort();

ii) syntax to sort element of array in descending order :

arrayname.reverse();

Note : reverse() method must be apply after sort method.

iii) to get numbers in ascending order use following syntax:

arrayname.sort(function(a,b){return a-b});

iv) to get number in descending order use following syntax:

arrayname.sort(function(a,b){return b-a});

WAP to implement sort() and reverse method on strings and numbers.

<body>

<script>

let a = ["dev", "prath", "himanshu", "vinayak"];

let asc = a.sort();

document.write(asc);

let b = ["dev", "vinayak", "prathmesh", "himanshu"];

let dsc = b.sort();

dsc = b.reverse();

document.write("<br>" + dsc);
//sorting integer array

let c = [1, 6, 3, 4, 2, 0];

let ascnum = c.sort(function (a, b) { return a - b });

document.write("<br>" + ascnum);

let d = [5, 4, 7, 2, 10];

let dscnum = d.sort(function (a, b) { return b - a });

document.write("<br>", dscnum);

</script>

</body>

Output :

dev,himanshu,prath,vinayak
vinayak,prathmesh,himanshu,dev
0,1,2,3,4,6
10,7,5,4,2
Object as associative array :

i) In order to access the value of property of object, there are two methods.

A. objectname.propertyname
B. objectname[“propertyname”]

ii) for ex. We want to access rno property of student object, there are two ways

A) Student.rno
B) Student[“rno”]

iii) here in the first method, the property name is an identifier and in the second method, the
property name is string

iv) An associative array is a collection of key-value pairs where each key is unique.

v) Instead of using numerical indices to access values (like in a regular array), you use keys,
which are usually strings or symbols.

vi) in order to access the values of associative array special for loop is used.

WAP to implement Object as associative array

<body>

<script>

let student = {

name: "devesh",

rno: 06,

city: "Mumbai"

};
for (let key in student) { //here key is name,rno,city(loop will run 3 times as
there are 3 keys)

let value = student[key]; //let value = student[name]

document.write("<br>" + key + " = " + value);

</script>

</body>

Output :

name = devesh
rno = 6
city = Mumbai
fuction

i) Function is block of code which performs specific task.

ii) there are 2 types of function

A) Built in or system defined


Function defined by javascript are built-in functions.
Ex : write(), alert(), promt()
B) User defined function
Functions defined by users are user defined function.

iii) Syntax :

<script>

Function functionName(<parameters>)

//block of code

</script>

WAP to print Hello world! Using user defined function.

<head>

<script>

function display() {

document.write("Welcome to javascript!");

</script>

</head>
<body>

<script>

display();

</script>

</body>

Output :

Welcome to javascript!

Scope of variable :

i) The scope of a variable in programming refers to the context within which the variable is
accessible or visible.

ii) In JavaScript, the scope of a variable determines where you can use it in your code.

iii) JavaScript has two main types of scope: A) Global scope B) Local scope

Local variable :

i) A variable declared within a function or block is called local variable.

ii) No other function is allow to access the value of local variable

Global variable :

i) A variable declared outside any function or block is called Global variable.

ii) It is accesible from anywhere in the code.


WAP to implement Local and Global Scope.

<head>

<script>

//global variable

let global = "global variable";

function abc() {

//we can access global variable anywhere in the code

document.write("<br>" + global);

function xyz() {

//local variable. we cannot use it outside this function

local = "local variable";

document.write("<br>" + global);

document.write("<br>" + local);

</script>

</head>

<body>

<script>

abc();

xyz();

</script>

</body>
Output :

global variable
global variable
local variable

Calling a function :

i) There are 2 types of calling a function

A) calling a function without parameter

i) syntax : function_name();

B) calling a function with argument or parameter

i) syntax : function_name(<parameter_list>);

WAP to calling function without parameter

<head>

<script>

let price = 50;

function show() {

let item = "pen";

document.write("the price of " + item + " = " + price);

</script>
</head>

<body>

<script>

show();

</script>

</body>

Output :

the price of pen = 50

WAP To calling function with parameter.

<head>

<script>

function add(a, b) {

return a + b;

</script>

</head>

<body>

<script>

let sum = add(5, 20);

document.write("sum = " + sum);

</script>
</body>

Output :

sum = 25

Calling Function from HTML

i) Function can be Called from Html on your web page.

ii) The function isn’t called explicitly rather, It will be called in response to an event, such as a
web page is loaded or unloaded by the browser.

iii) For example, if we Have two Different function namely welcome and goodbye. And you
want to code of welcome to be executed when the html web page is loaded in the browser and
goodbye function to be executed when web page is unloaded from the browser.

iv) In order to do this following syntax is used.

<body onload=”welcome()” onunload=”goodbye()” >

WAP to implement calling a function from HTML.

<head>

<script>

function welcome() {

window.alert("Welcome to the program!");

function goodbye() {

window.alert("Bye.....Bye!");

</script>
</head>

<body onload="welcome()" onunload="goodbye()">

</body>

</html>

Output :

Calling function from another function :

WAP To implement calling function from another function or to implement working of login
page.

<head>

<script>

function login() {

let username = prompt("Enter Username :");

let password = prompt("Enter Password :");

let valid = validate_login(username, password); //promtwale parameters

if (valid == true) {
window.alert("Login Successfully!");

else {

window.alert("Invalid Credentials!");

function validate_login(user, pass) {

let flag;

if (user == "dev" && pass == "dev@333") {

flag = true;

else {

flag = false;

return flag;

</script>

</head>

<body onload="login()">

</body>

Output :
Returning value from a function:

WAP to implement returning value from a function

<head>

<script>

function area(r) {

let a = 3.14 * r * r;

return a;

</script>

</head>

<body>

<script>

let radius = prompt("Enter Radius : ");

let ans = area(radius);

document.write("Area = " + ans);

</script>

</body>

Output :

Area = 78.5
Strings :

i) String is a collection of zero or more unicode characters(alphabets, number, special symbol)

ii) syntax :

1. Var s1 = new String(); //empty string


2. Var s2 = new String(“dev”);
3. Var s3 = new String(‘dev’);
4. Var s4 = “dev”;

WAP to find length of string

<body>

<script>

let s1 = new String(); //empty string

let s2 = new String("dev");

let s3 = "karan";

let s4 = 'ritu'

document.write("<br> s1 = " + s1);

document.write("<br> s2 = " + s2);

document.write("<br> s3 = " + s3);

document.write("<br> s4 = " + s4);

document.write("<br> length of s2 = " + s2.length)

</script>

</body>

Output :
s1 =
s2 = dev
s3 = karan
s4 = ritu
length of s2 = 3

Joining a strings :

i) there are 2 methods

1. using concatination operator(+) :

The + operator is used to concat if one of the operand is string and returns concatenated string
as a result.

2. concat( ) method :

The concat( ) method is used to join two or more strings and returns the new single string as a
result.

Syntax : stringname1.concat(string2,string3…);

WAP to implement joining of string using + and concat()

<body>

<script>

let s1 = "dev";

let s2 = "karan";

let s3 = "welcome!"

//concatination operator (+)

let s4 = s1 + s2;
document.write("<br>" + s4);

//concat() method

let s5 = s1.concat(s2, s3);

document.write("<br>" + s5);

</script>

</body>

Output :

devkaran
devkaranwelcome!

Accessing character from perticular position :

i) A string is Array of characters.

ii) The charAt( ) function is used to find/access character from particular position.

iii) The charAt( ) function need one parameter as index of character.

WAP to implement charAt( ) method

<body>

<script>

let s1 = "Welcome to Javascript!";

document.write("<br> character at index 0 : " + s1.charAt(0));

document.write("<br> character at index 7 : " + s1.charAt(7));

document.write("<br> character at index 15 : " + s1.charAt(15));

document.write("<br> character at index 50 : " + s1.charAt(50));


</script>

</body>

Output :

character at index 0 : W
character at index 7 :
character at index 15 : s
character at index 50 :

Accessing position of specific character in a string:

i) there are two methods

1. indexOF() method

i) This method is used to return the position fo first occurance of specific charactors in a string.

ii) if the desired character isn’t present then it returns “-1”.

iii) syntax :

stringname.indexOf(“character”);

2. serch( ) method :

i) this method is used to search the desired string and returns the position fo matched string

ii) syntax : stringname.search(“character/string”);

WAP to implement indexOf( ) and serch( ) method.

<body>

<script>

let s1 = "How are you?";


let a = s1.indexOf("H");

let b = s1.indexOf("?");

let c = s1.indexOf("z"); //returns -1 if not found

let d = s1.search("you");

let e = s1.search("dev");

document.write("<br> 'H' found at location : " + a);

document.write("<br> '?' found at location : " + b);

document.write("<br> 'z' found at location : " + c);

document.write("<br> 'you' found at location : " + d);

document.write("<br> 'dev' found at location : " + e);

</script>

</body>

Output :

'H' found at location : 0


'?' found at location : 11
'z' found at location : -1
'you' found at location : 8
'dev' found at location : -1

Dividing string into characters

i) split( ) method is used to split the character of strings sequentially.

ii) split( ) method is also used to split words in sentence.


WAP to implement split( ) method

<body>

<script>

//split sentence to words

let sentence = "JavaScript is fun and powerful";

// Split the string into an array of words

let words = sentence.split(" "); //give space

let letters = sentence.split(""); //dont give space

document.write("Original sentence: " + sentence + "<br><br>");

document.write("After split sentence into words:");

document.write("<br>" + words);

document.write("<br><br>After split sentence into letters: ");

document.write("<br>" + letters);

</script>

</body>

Output :

Original sentence: JavaScript is fun and powerful

After split sentence into words:


JavaScript,is,fun,and,powerful

After split sentence into letters:


J,a,v,a,S,c,r,i,p,t, ,i,s, ,f,u,n, ,a,n,d, ,p,o,w,e,r,f,u,l
Accessing substring from given string :

1. substring( ) method :

i) this method is used to Extract the character from the string between the two specified indices
and return the new string as result.

ii) syntax : stringname.substring(s_index, e_index);

Here end index is optional and if not written then rest of string considered.

2. substr() method :

i) This method is used to extract characters from the string starting from start_index up to
length specified.

ii) syntax : stringname.substr(s_index, length);

Here length is optional and if not written rest of string considered.

WAP to implement substr( ) & substring( ) method.

<body>

<script>

let s1 = "Javascript is programming language";

document.write("<br>substring 1 = " + s1.substring(14)); //14 index to last index

document.write("<br>substring 2 = " + s1.substring(14, 25)); //14 index to 25


index(not include)

document.write("<br>substring 3 = " + s1.substring(25, 14)); //switching last index to


first index

document.write("<br>substring 4 = " + s1.substr(14)); //14index to last index


document.write("<br>substring 4 = " + s1.substr(14, 11)); //14 index pasun 11
characters

</script>

</body>

Output :

substring 1 = programming language


substring 2 = programming
substring 3 = programming
substring 4 = programming language
substring 4 = programming

Converting string to number or float :

Var s1 = 20;

Var s2 = “30”;

i) if we apply + on both s1 and s2 i.e s1+s2, we get string instead of 50.

ii) to get the desired output we must convert second variable from string to number datatype.

iii) To do this there are 3 methods :

A) parseInt( ) :
i) Used to convert string to Integer(whole number)
ii) It accepts 2 parameter a)string b)radix(base)

Note : radix is optional. Default is 10.

B) parseFloat( ) :
i) Used to convert string in floating point number.
C) number( ) method :
i) Used to convert string into number.
ii) These method accepts only number of float values and if the string contains any
character then it will return NAN.

WAP to implement parseInt( ), parseFloat and number( ) method.

<body>

<script>

let str1 = "42";

let str2 = "42.58";

let str3 = "42px";

let str4 = "Hello42";

let num1 = parseInt(str1); // 42

let num2 = parseInt(str2); // 42 (only the integer part)

let num3 = parseInt(str3); // 42 (ignores the non-numeric part)

let num4 = parseInt(str4); // NaN (cannot parse, starts with a non-numeric character)

document.write("parseInt(str1): " + num1 + "<br>");

document.write("parseInt(str2): " + num2 + "<br>");

document.write("parseInt(str3): " + num3 + "<br>");

document.write("parseInt(str4): " + num4 + "<br>");


let str5 = "42.58";

let str6 = "42px";

let str7 = "3.14 is pi";

let str8 = "Hello3.14";

let num5 = parseFloat(str5); // 42.58

let num6 = parseFloat(str6); // 42 (ignores the non-numeric part)

let num7 = parseFloat(str7); // 3.14 (parses up to the first non-numeric character)

let num8 = parseFloat(str8); // NaN (cannot parse, starts with a non-numeric character)

document.write("parseFloat(str1): " + num5 + "<br>");

document.write("parseFloat(str2): " + num6 + "<br>");

document.write("parseFloat(str3): " + num7 + "<br>");

document.write("parseFloat(str4): " + num8 + "<br>");

let str9 = "42";

let str10 = "42.58";

let str11 = "42px";

let str12 = "Hello42";

let num9 = Number(str9); // 42

let num10 = Number(str10); // 42.58

let num11 = Number(str11); // NaN (cannot convert non-numeric characters)


let num12 = Number(str12); // NaN (cannot convert non-numeric characters)

document.write("Number(str1): " + num9 + "<br>");

document.write("Number(str2): " + num10 + "<br>");

document.write("Number(str3): " + num11 + "<br>");

document.write("Number(str4): " + num12 + "<br>");

</script>

</body>

Output :

parseInt(str1): 42
parseInt(str2): 42
parseInt(str3): 42
parseInt(str4): NaN
parseFloat(str1): 42.58
parseFloat(str2): 42
parseFloat(str3): 3.14
parseFloat(str4): NaN
Number(str1): 42
Number(str2): 42.58
Number(str3): NaN
Number(str4): NaN

Conveting number to string :

toString( ) method :

i) this method is used to convert number to string.


WAP to convert number to string

<body>

<script>

let a = 10;

let b = 20;

let result = a + b.toString();

document.write("Result = " + result);

</script>

</body>

Output :

Result = 1020

Changing case of string :

There are two methods :

1. toLowerCase() :

i) It is used to convert complete string into lowercase.

ii) syntax : stringname.toLowerCase();

2. toUpperCase( ) :

i) It is used to convert complete string into Uppercase.

ii)syntax : stringname.toUpperCase();
WAP to implement changing case of string

<body>

<script>

let s1 = "Devesh Karan";

document.write("<br>Orignal string = " + s1);

document.write("<br>string in uppercase = " + s1.toUpperCase());

document.write("<br>string in lowercase = " + s1.toLocaleLowerCase());

</script>

</body>

Output :

Orignal string = Devesh Karan


string in uppercase = DEVESH KARAN
string in lowercase = devesh karan

Finding unicode of character :

i) unicode is Standard, which assigns a number to every character,number and symbol.

ii) A computer can understand only numbers, not characters.

iii) Hence, when we enter any character, number The corresponding character is automatically
convert into a number equivalent to its unicode.

1.charCodeAt( ) :

i) The charCodeAt() is string method which is used to access the unicode value for perticular
character or a given position.

ii) This method access one parameter as the index value of the desired character.
iii) syntax: stringname.charCodeAt(index);

iv) if the index not provided then default value is zero.

2.fromCharCode() :

i) this Method is used to create a string from sequence of unicode values.

ii) This method acepts one or more unicode values.

ii) syntax : stringname.fromCharCode(val1,val2,val3………..);

WAP to implement charCodeAt() & fromCharCode() method :

<body>

<script>

//stringname.charCodeAt(index);

let s1 = "Welcome to Javascript";

document.write("<br>Unicode of W = " + s1.charCodeAt(0));

document.write("<br>Unicode of space = " + s1.charCodeAt(7));

//String.fromCharcode(45,67,34)

document.write("<br>");

document.write(String.fromCharCode(68, 69, 86, 69, 83, 72));

</script>

</body>
Output :

Unicode of W = 87
Unicode of space = 32
DEVESH

You might also like