JavaScript Functions
JavaScript Functions
Example
<html>
<body>
<h1>JavaScript Functions</h1>
<p id="demo"></p>
<script>
return p1 * p2;
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).
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
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":
Example
Calculate the product of two numbers, and return the result:
<html>
<body>
<h1>JavaScript Functions</h1>
<p id="demo"></p>
<script>
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 use the same code with different arguments, to produce different results.
The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius(77);
document.getElementById("demo").innerHTML = value;
</script>
</body>
</html>
JavaScript Regular Expressions
❮ PreviousNext ❯
The search pattern can be used for text search and text replace operations.
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
Regular expressions can be used to perform all types of text search and text
replace operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
Example explained:
/w3schools/i is a regular expression.
The search() method uses an expression to search for a match, and returns the position of
the match.
The replace() method returns a modified string where the pattern is replaced.
Example
Use a string to do a search for "W3schools" in a string:
Expression Description
\uxxxx Find the Unicode character specified by the hexadecimal number Try it
xxxx »
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
Since there is an "e" in the string, the output of the code above will be:
true