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

chapter 41

Chapter 4 discusses the creation and usage of JavaScript functions, highlighting their advantages such as code reusability and compactness. It covers function syntax, parameters, arguments, and various methods associated with functions, as well as string manipulation and event handling in JavaScript. Additionally, it explains different types of dialog boxes like alert, confirmation, and prompt for user interaction.

Uploaded by

laita nikam
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)
2 views

chapter 41

Chapter 4 discusses the creation and usage of JavaScript functions, highlighting their advantages such as code reusability and compactness. It covers function syntax, parameters, arguments, and various methods associated with functions, as well as string manipulation and event handling in JavaScript. Additionally, it explains different types of dialog boxes like alert, confirmation, and prompt for user interaction.

Uploaded by

laita nikam
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/ 12

Chapter 4 JavaScript function

Creating JavaScript function

JavaScript Functions
An important part of JavaScript is the ability to create new functions within <script> and </script> tag.
Declare a function in JavaScript using function keyword. The keyword function precedes the name of the
function.

JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.

Code reusability: We can call a function several times so it save coding.

Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

The syntax of declaring function is given below.

function name(parameter1, parameter2, parameter3)

{
// code to be executed
}

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}
function functionName(parameter or not)
{
.........
.........
}
<html>
<body>
<script>
function msg()

{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other programming languages.

JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument.

<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the example of function that
returns value.

<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
JavaScript Function Object
In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally.
However, if we call the constructor directly, a function is created dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods


Let's see function methods with description.

Method Description
apply() It is used to call a function contains this value and a single array of arguments.
bind() It is used to create a new function.
call() It is used to call a function contains this value and an argument list.
toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1

Let's see an example to display the sum of given numbers.

<!DOCTYPE html>
<html>
<body>

<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

</body>
</html>

JavaScript String
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
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given
below:

var stringname="string value";

<!DOCTYPE html>

<html>

<body>

<script>

var str="This is string literal";

document.write(str);

</script>

</body>

</html>

By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let's see the example of creating string in JavaScript by new keyword.

<!DOCTYPE html>

<html>

<body>

<script>

var stringname=new String("hello javascript string");

document.write(stringname);

</script>

</body>

</html>

1) JavaScript String charAt(index) Method

The JavaScript String charAt() method returns the character at the given index.
<!DOCTYPE html>

<html>

<body>

<script>

var str="javascript";

document.write(str.charAt(2));

</script>

</body>

</html>

2) JavaScript String concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.

<!DOCTYPE html>

<html>

<body>

<script>

var s1="javascript ";

var s2="concat example";

var s3=s1+s2;

document.write(s3);

</script>

</body>

</html>

3) JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of the given string.

<!DOCTYPE html>

<html>

<body>

<script>

var s1="javascript from javatpoint indexof";

var n=s1.indexOf("from");

document.write(n);
</script>

</body>

</html>

4) JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given string.

<!DOCTYPE html>

<html>

<body>

<script>

var s1="javascript from javatpoint indexof";

var n=s1.lastIndexOf("java");

document.write(n);

</script>

</body>

</html>

5) JavaScript String toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.

<!DOCTYPE html>

<html>

<body>

<script>

var s1="JavaScript toLowerCase Example";

var s2=s1.toLowerCase();

document.write(s2);

</script>

</body>

</html>

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.
<html>

<body>

<script>

var s1="JavaScript toUpperCase Example";

var s2=s1.toUpperCase();

document.write(s2);

</script>

</body>

</html>

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.

<!DOCTYPE html>

<html>

<body>

<script>

var s1="abcdefgh";

var s2=s1.slice(2,5);

document.write(s2);

</script>

</body>

</html>

8) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces from the string.

<!DOCTYPE html>

<html>

<body>

<script>

var s1=" javascript trim ";

var s2=s1.trim();

document.write(s2);
</script>

</body>

</html>

9) JavaScript String split() Method

1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching
a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
match() It searches a specified regular expression in a given string and returns that
regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified
index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as
well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current
locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current
locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.

Handling Web page event

The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is included
in HTML, js react over these events and allow the execution. This process of reacting over the events is
called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:
Event Performed Event Handler Description
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the element
mouseout onmouseout When the cursor of the mouse leaves an element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:
Event Performed Event Handler Description
focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form element

Window/Document events
Event Event Description
Performed Handler
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads
it
resize onresize When the visitor resizes the window of the browser

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his mouse.
You can put your validation, warning etc., against this event type.
<html>
<head>

<script type = "text/javascript">


<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>

</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>

</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following example.
<html>
<head>

<script type = "text/javascript">


<!--
function over() {
document.write ("Mouse Over");
}

function out() {
document.write ("Mouse Out");
}

//-->
</script>

</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover = "over()" onmouseout = "out()">


<h2> This is inside the division </h2>
</div>

</body>
</html>

Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and
alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss
each dialog box one by one.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users. For example, if one input field
requires to enter some text but the user does not provide any input, then as a part of validation, you can
use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to
select and proceed.

Example
<html>
<head>

<script type = "text/javascript">


<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>

</head>
<body>
<p>Click the following button to see the result: </p>

<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>

</body>
</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box
with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on
the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.

Example
<html>
<head>

<script type = "text/javascript">


<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
}
else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>

</head>
<body>
<p>Click the following button to see the result: </p>

<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>

</body>
</html>

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it
enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label
which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the
window method prompt() returns null.

Example
The following example shows how to use a prompt dialog box −
<html>
<head>

<script type = "text/javascript">


<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>

</head>

<body>
<p>Click the following button to see the result: </p>

<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>

</body>
</html>

You might also like