Chapter 2 Array Function String
Chapter 2 Array Function String
✓ push() : adds a one or more new elements to an array (at the end):
Syntax
Array.push(item1, item2 …)
Example:
var a=[10,20,30,40]
a.push(50)
a.push(60,70,80)
document.write(a)
output:
[10,20,30,40,50,60,70,80]
Array Methods
Array elements can be combined in two ways: by using the concat() method
or the join() method of the array object
The concat() method separates each value with a comma.
The join() method also uses a comma to separate values, but you can specify a
character other than a comma to separate values
Here’s how to use the concat() method:
var str = products.concat()
The value of str is
'Soda,Water,Pizza,Beer'
Here’s how to use the join() method. In this example, we use a space to separate values:
var str = products.join(' ‘)
The value of str in this case is
'Soda Water Pizza Beer'
The reverse() method reverses the order of
the elements in an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
Output : Mango,Apple,Orange,Banana
Function
Function
✓ A JavaScript function is a block of code designed to perform a particular
task.
✓ A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again.
✓ It helps programmers in writing modular codes.
✓ Functions allow a programmer to divide a big program into a number of small and
manageable functions.
✓ Two kinds of functions are used in JavaScript:
1.predefined functions
2.custom functions
✓ A predefined function is already created for you in JavaScript, such as the
alert() function.
✓ A custom function is a function that you create.
Custom function
function DisplayHelloWorld()
{
alert('Hello, world!')
}
3.Code Block
The code block is the part of the function definition where you insert JavaScript
statements that are executed when the function is called by another part of your
JavaScript application. Statements that you want executed must appear between the
open and close braces.
4.Return (Optional)
The return keyword tells the browser to return a value from the function definition to the
statement that called the function.
Writing a Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.
Syntax
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example:
function sayHello()
{
document.write ("Hello there!");
}
Calling a Function
You call a function any time that you want the browser to execute
statements contained in the code block of the function.
A function is called by using the function name followed by parentheses.
sayHello()
Example 1
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = “Click Me">
</form>
</body>
</html>
Adding Arguments
Sometimes you provide the data when you define the function.
Data that is needed by a function to perform its task that is not written into the
function definition must be passed to the function as an argument.
An argument is one or more variables that are declared within the parentheses
of a function definition.
You can create functions with arguments as well. Arguments should be specified
within parenthesis.
function functionname(arg1, arg2)
{
lines of code to be executed
}
Write a JavaScript function to count the number of vowels in a given string
<html>
<head>
<script type="text/javascript">
var count = 0;
function countVowels(name)
{
for (var i=0;i<name.length;i++)
{
if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
count = count + 1;
}
document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
}
var myName = prompt("Please enter your name");
countVowels(myName);
</script>
</head>
<body></body></html>
Adding Multiple Arguments
✓ A function reports back to the statement that calls the function by returning a
value to that statement using the return keyword, followed by a return value in a
statement.
Here’s what this looks like:
function name ()
{
return value
function add(a, b)
} function square(x) {
{ return a + b;
return x * x; }
}
var sum = add(5, 24);
var demo = square(3);
<html>
<head>
<script>
function concatenate(name, age)
{
var val;
val = name + age;
return val;
}
function DisplayFunction()
{
var result;
result = concatenate(‘Ganesh', 20) ;
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "DisplayFunction()" value = "Result">
</form> </body> </html>
Validation of user id and password by returning values
<html>
<head>
<title>Returning a value from a function</title>
<script language="Javascript" type="text/javascript">
function Logon()
{
var userID, password, valid;
userID = prompt('Enter user ID',' ‘)
password = prompt('Enter password',' ‘)
valid = ValidateLogon(userID, password)
if ( valid == true)
{
alert('Valid Logon')
}
else
{
alert('Invalid Logon')
}
}
function ValidateLogon(id,pwd)
{
var ReturnValue
if (id == 'Alinka' && pwd == 'Alinka123')
{
ReturnValue = true
}
else
{
ReturnValue = false
}
return ReturnValue
}
</script>
</head>
<body>
<p>Click the following button validate Login Details</p>
<form>
<input type = "button" onclick = "Logon()" value = "Validate
Login">
</form>
</body>
</html>
STRING
16/9/2020
STRING
➢ A string is text that is enclosed within quotation marks. It is called a string because
characters are put together to form the text.
➢ The JavaScript string is an object that represents a sequence of characters.
➢ There are 2 ways to create string in JavaScript
1. By string literal
var str="JavaScript";
document.write(str.charAt(4));
• concat() :
✓ The JavaScript string concat() method combines two or more strings and returns a new
string .
string.concat(str1,str2,...,strn)
var x="JavaScript";
var y=“ is a Client Side Scripting Language";
document.writeln(x.concat(y));
• indexOf():
• The JavaScript string indexOf() method is used to search the position of a particular
character or string in a sequence of given char values. The index position of first
character in a string is always starts with zero. If an element is not present in a string, it
returns -1.
var str="Learn JavaScript ";
document.write(str.indexOf('a'));
• lastIndexOf()
• The JavaScript string 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.
var str="Learn JavaScript";
document.write(str.lastIn dexOf('a'));
• replace()
• The JavaScript string 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.
string.replace(originalstr,newstr)
var str=“I m Pass";
document.write(str.replace(“Pass",“Fail"));
• substr()
• The JavaScript string substr() method fetch the part of the given string and return the new string.
string.substr(start,length)
var str="JavatScript";
document.write(str.substr(0,4));
• substring()
• The JavaScript string substring() method fetch the string on the basis of provided
index and returns the new sub string.
string.substring(start,end)
var str="JavaScript";
document.writeln(str.substri
ng(4,5));
• slice()
• The JavaScript string slice() 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.
string.slice(start,end)
var str = "Javatpoint";
document.writeln(str.slice(2,5));
• toLowerCase()
• The JavaScript string toLowerCase() method is used to convert the string into lowercase
letter.This method doesn't make any change in the original string.
string.toLowerCase()
var str = "JAVASCRIPT tutorials";
document.writeln(str.toLowerCase());
• toUpperCase()
• The JavaScript string toUpperCase() method is used to convert the string into uppercase
letter.
string.toUpperCase()
var str = "javascript";
document.writeln(str.toUpperCase());
• toString():
• This method returns a string representing the specified object.
string.toString( )
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
• split()
• This method splits a String object into an array of strings by separating the string into substrings.
string.split([separator][, limit]);
separator − Specifies the character to use for separating the string.
limit − Integer specifying a limit on the number of splits to be found.
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
document.write( splitted );
Converting Numbers and Strings
• We know that a number and a string are two different types of data in JavaScript. A
number is a value that can be used in a calculation; a string is text and can include
numbers, but those numbers cannot be used in calculations.
• The Letter.charCodeAt( ) method returns the number 119, which is the Unicode
number that is assigned the letter w. Uppercase and lowercase versions of each
letter have a unique Unicode number.