JavaScript Functions and Loops

JavaScript Loops and Functions
JavaScript Loops and Functions

JavaScript Functions

JavaScript functions are used to perform certain tasks. Once created we can call a JavaScript function many times to reuse the code. A function always has a return type. It makes the programs more manageable.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

  1. Code reusability: A function is created once and called several times so it save coding.
  2. Less coding: It makes our program compact. repetition of code can be avoided hence there is no need to write many lines of code each time to perform a common task .

JavaScript Function Syntax

The function can be declared with a syntax given below.

function functionName([arg1, arg2, …argN]){

//code to be executed

}

JavaScript Functions can have 0 or more arguments.

Example

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
function msg(){  
alert("hello! India");  
}  
</script>  
<input type="button" onclick="msg()" value="function call"/>
</body>
</html>

JavaScript Function Arguments

As we have discussed a function can have 0 or more arguments. So let us call a function by passing arguments.

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

Here we have used cube(4) to call the function so 4 is our function argument. so it will return the cube of number 4.

JavaScript Function with Return Value

JavaScript function can returns values and you can use it in your program.

Example:

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
function getInfo(){  
return "hello javatpoint! How r u?";  
}  
</script>  
<script>  
document.write(getInfo());  
</script>  
</body>
</html>

JavaScript Function Object

In JavaScript, The Function constructor is used to create a new Function object. It executes the code globally. However, if the constructor is called directly, a function is created dynamically but in an unsecured way.

Syntax

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

Parameter

arg1, arg2, …. , argn – It represents the argument used by function.

function Body – 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

A Simple JavaScript program to display the sum of given numbers.

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

Example 2

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
var pow=new Function("num1","num2","return Math.pow(num1,num2)");  
document.writeln(pow(2,3));  
</script>  
</body>
</html>

 

JavaScript Loops

Repetition of a task is called Iteration. The iterations are nothing but repeating some piece of code, for finite number of times until it’s condition remains true. This repetition is called Loops in JavaScript. A JavaScript Loop makes the program code compact. The JavaScript loops are most commonly used in arrays handling.

JavaScript loops has five types.

  1. For Loop
  2. While Loop
  3. Do-While loop
  4. For-in Loop
  5. For-of Loop

1) JavaScript For loop

The most common JavaScript loop is  for loop, it repeats a sequence for fixed number of times. So you can use for loop where the number of iteration is known before hand. For loop’s syntax is given below.

for (initialization; condition; increment)

{

code to be executed

}

A simple example of for loop in JavaScript.

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
for (i=1; i<=5; i++)  
{  
document.write(i + "<br/>")  
}  
</script> 
</body>
</html>

Result of the above program
1
2
3
4
5

2) JavaScript while loop

The JavaScript while loops are more suitable when it is not sure how many times the iteration will take place. It is also called a pre test loop because it first tests a condition and as long as the  condition remains true the loop continues to execute.

The syntax of while loop is as under.

while (condition)

{

code to be executed

}

JavaScript while loop example.

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
var x=1;  
while (i<=5)  
{  
document.write(x + "<br/>");  
x++;  
}  
</script>  
</body>
</html>

Output:

1
2
3
4
5

3) JavaScript do while loop

The JavaScript do while loop also called post test loop or bottom test loop. It executes its body at least once even if its condition is false. If loop condition is true then it is will continue executing its body until the condition becomes false.

Syntax:

do{

code to be executed

}while (condition);

Example:

<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script>  
var i=21;  
do{  
document.write(i + "<br/>");  
i++;  
}while (i<=25);  
</script> 
</body>
</html>

4) JavaScript for in loop

The JavaScript for-in loop is a special type of a for loop that iterates over the properties of an object, or the elements of an array.

The syntax of the for-in loop is:

for(variable in object) {
//Write the Code to be  executed here
}

The JavaScript loop counter for, for-in loop is a string, not a number. It accesses the current  property name or the current array index of the element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>For-in Loop</title>
</head>
<body>
    <script>
    var person = {"name": "Clark", "surname": "Kent", "age":     "36"};
    for(var prop in person) { 
        document.write("<p>" + prop + " = " + person[prop] + "</p>");
    }
    </script>
</body>
</html>

In this program for-in loop will iterate through object person’s properties and will keep each object in a paragraph one by one until all properties are finished.

5) The For-Of Loop

The JavaScript for-of loop iterates through the values of an iterable objects

for-of is used to  loop over data structures that are iterable such as Arrays, Strings, NodeLists and Maps  etc

The for-of loop  can be declared as under:

for (variable of iterable object) {
// code block to be executed
}

variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with constlet, or var.

iterable – An object with iterable properties.

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript code of For-Of Loop</h2>
<p>The for-of statement loop.</p>
<script>
var cars = ['BMW', 'Hyundai', 'Maruti'];
var a;
for (a of cars) {
document.write(a + "<br >");
}
</script>
</body>
</html>

To visit the  Official website of JavaScript Click here

Similar Posts:  JavaScript Variable and its Scope,        How To Enable JavaScript in Browsers,    

                           Where to write JavaScript Code ,         How to Generate Output in JavaScript

What is the use of functions in JavaScript ?

JavaScript Functions introduces re-usability feature. write once and use any number of times. makes the program structure clean and help debugging the program errors quickly. To create a function keyword function preceeds the function name.

How many loops are in JavaScript?

JavaScript has five types of loops
1. For Loop
2. While Loop
3. Do-While Loop
4. For-in Loop
5. For-of Loop

What is use of Do-while loop

Do-while Loop is particularly helpful in Menu making programs. where is executes at least once without even testing any loop conditions. Rest all other loops execute when the condition is true.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

[…] posts : JavaScript Objects ,    JavaScript Functions and Loops    JavaScript Control Statements and Operators  Data Types in […]

trackback
3 years ago

[…] is New in HTML5        JavaScript Functions and Loops          How to Activate GST in Tally.ERP9 […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap