JavaScript

JavaScript Function || JavaScript

javascript function

JavaScript function is the block of code which execute when something call it.

There are three main components of JavaScript function:

  • Write function keyword before naming that function.
  • Parameter of JavaScript function can be string , integer or variables as value is pass through variables.
  • If developer wants to return something after executing all the code, return keyword can return string or integer or array to the calling place.

In Java methods we use to write public, private etc and for return datatype write int, string etc. but in JavaScript function we don’t need to write public as it is accessible everywhere in its file and if we want to return something just add return statement at the end of function.Without return statement it will return default value.

Example #1:

Calculate the sum of array in function sum() and display sum in console.

<script> 
var array=[10,20,30]
function sum(array){
    var sum=0;
    for(var i=0;i<array.length;i++){
        sum=sum+array[i]
    }
    return sum;
}
console.log(sum(array))
</script>

Output:

60

When a function is called, it can access all the instances declared above that calling line. It can manipulate the values of objects,variables,array etc.

Example #2:

Create a student object and change its value.

<script> 
var student={
    name:"Qamar Shahzad",
    roll_no:12,
    pencentage:"",
    math:90,
    science:80,
    physics:85,
    chemistry:95
}
function calculate_grade(object){
    var math=object.math;
    var science=object.science;
    var physics=object.physics;
    var chemistry=object.chemistry;
    var total_marks=(math+science+physics+chemistry)/400;
    object.pencentage=total_marks*100;
}
calculate_grade(student);
console.log(student);
</script>

Output:

{name: "Qamar Shahzad", roll_no: 12, pencentage: 87.5, math: 90, science: 80, …}
chemistry: 95
math: 90
name: "Qamar Shahzad"
pencentage: 87.5
physics: 85
roll_no: 12
science: 80

Example #3:

Calculate the sum of array and display it.

<body>
    <button onclick="marks([1,2,3])">Marks</button> 
<script> 

function marks(array){
    var sum=0;
    for(var i=0;i<array.length;i++){
        sum=sum+array[i]
    }
    alert("The Sum is "+sum);
    }
</script>
</body>

Output:

Example #4:

Calculate the Average marks of student using function name “Average” and display on console.

<script> 
student_1=[90,80,100,50,60];
student_2=[100,80,79,43,65];
student_3=[32,54,87,98,23];
function Average(array){
    sum=0;
    for(var x=0;x<array.length;x++){
        sum=sum+array[x];
    }
     return sum/array.length;
}
console.log(Average(student_1));
console.log(Average(student_2));
console.log(Average(student_3));
</script>

Output:

76
73.4
58.8

 

Leave a Reply

Your email address will not be published. Required fields are marked *