chapter 41
chapter 41
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.
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 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).
{
// code to be executed
}
{
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.
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>
<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.
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.
<!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.
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:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(str);
</script>
</body>
</html>
The syntax of creating string object using new keyword is given below:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(stringname);
</script>
</body>
</html>
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>
<!DOCTYPE html>
<html>
<body>
<script>
var s3=s1+s2;
document.write(s3);
</script>
</body>
</html>
The JavaScript String indexOf(str) method returns the index position of the given string.
<!DOCTYPE html>
<html>
<body>
<script>
var n=s1.indexOf("from");
document.write(n);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var n=s1.lastIndexOf("java");
document.write(n);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var s2=s1.toLowerCase();
document.write(s2);
</script>
</body>
</html>
<body>
<script>
var s2=s1.toUpperCase();
document.write(s2);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
</body>
</html>
The JavaScript String trim() method removes leading and trailing whitespaces from the string.
<!DOCTYPE html>
<html>
<body>
<script>
var s2=s1.trim();
document.write(s2);
</script>
</body>
</html>
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
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.
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.
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
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
</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.
Example
<html>
<head>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
Example
<html>
<head>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
Example
The following example shows how to use a prompt dialog box −
<html>
<head>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>