0% found this document useful (0 votes)
9 views

JS notes

Uploaded by

Rana Zahid Zooni
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JS notes

Uploaded by

Rana Zahid Zooni
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed
when "something" invokes it (calls it).

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>

JavaScript Function Syntax


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).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: { }

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button).


 When it is invoked (called) from JavaScript code.
 Automatically (self-invoked).

You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the caller":

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.

You might also like