JavaScript Functions

What is Function?

If some pieces of code will be used repeatedly in the program, instead of rewriting these lines each time, we can write them in a function and call them from anywhere with the name of the function. 

In addition, in event-driven languages ​​such as JavaScript, operations are performed by determining which function will run when an event occurs. 

Thanks to the functions, our programs will be more organized and it will be easier to make corrections when necessary.

Defining Functions in JavaScript

A simple function named Calculate has been defined below, and when a button in the body part is clicked, it works.

<html> <head>

<script>

function hesapla()

{

The actions to be taken are written here.

}

</script>

</head>

<body>

<input type="button" value="Hesapla" onclick="hesapla()" />

</body>

</html>

Local and Global Variables in JavaScript

A variable defined in a function is valid only within that function and cannot be accessed from other places. 

A variable defined outside of functions, between script tags, is a global variable and can be called from any other function.

<script>

var k;

function1()

{

var a;

}

function function2()

{

var b;

}

</script>

In the example above, the variable k is a global variable. Accessible from anywhere. Variable a is valid only inside function1.

A variable defined with the var command is automatically considered global. Variables created with the let command do not work globally.
Variables that are assigned values directly without using the var or let command are also considered global.

function function3()

{

c = "Computer";

}

The variable c in this example will be accessible from anywhere as a global variable.

javascript functions, javascript function tutorials, javascript method creation, javascript global variable usage, local and global variables and their differences

EXERCISES

JavaScript events and functions Try It
Click the Try It Yourself button, change the codes, see the result...
 
In this example, a function has been prepared for the onclick, onmouseover and onmouseout events of the img tag.
 
Html Section:
<img onmouseover="on()" onmouseout="outside()" onclick="clicked()" src="../images/pic.jpg" />
 
<b id="status"></b>

 



COMMENTS




Read 529 times.

Online Users: 663



javascript-functions