how to JavaScript function

Posted under javascript sample code On By mohammed.mutawe

JavaScript function

Since you have become a JavaScript coder, you will of course need to use functions in your code and the need to use JavaScript function came due to the repeated definition of variables and the same steps, but with different names, which made it necessary to have a block that you run once or hide away from the code in order not to loss controlling on your code.

 

Concepts

  • What a function is?
  • Call function.
  • Pass parameter on function.

 

Definition

JavaScript function uses the same system as C++ language, but in a simplified way, and if we define a function, writing it will be as follows:

function call_me()
{
   //Your code here
}

where the function is mentioned, followed by the name in memory, then the parentheses and bracket, with the code we want to write.

 

What a function is?

In fact, the JavaScript function does not differ from the conjunctions in which mathematical problems are solved, as well as the case of other programming languages, and it is a single task that is processed away from our code and then it is called and run whenever the need arises. As follows:

function print_func()
{
  document.write("I am a function you called!");
}

 

Call Function

Well, after we have defined the JavaScript function and created it, we will now call this function as follows:

<html>
<body>
<script>
    function print_func()
    {
        document.write("I am a function you called!");
    }
</script>
</body>
</html>

If you think that something will appear on the screen in front of you, you are wrong. Do you know why ?because we did not call this function and to achieve this we will do this by calling this function inside the script tags in this way:

<html>
<body>
<script>
    function print_func()
    {
        document.write("<h2>I am a function you called!</h2>");
    }

    print_func(); // You should call function like that
</script>
</body>
</html>

 

Passing parameter

If you master the previous steps then the rest is very easy ok now we will define parameter in parentheses javascript function and then try to print same as previous sentence but by passing data from above this method is very effective if you want to create javascript function for frequent use in more than one place ok We’ll include this step at the conclusion of this lesson.

 

Example

Copy this code inside your editor then try to see results on your browser :

<html>
<body>
<script>

    let a = "<h3>I am a function you called!<h3>";
    function print_func(a)
    {
        document.write(a + "You've Done!");
    }

    print_func(a); // You should call function like that
</script>
</body>
</html>

 

References

  • Third edition JavaScript

Leave a comment

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