JavaScript Functions
What are Functions?
Functions are fundamental building blocks in all programming.
Functions are reusable block of code designed to perform a particular
task.
Functions are executed when they are "called" or "invoked".
Example
Function to compute the product of two numbers:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function to compute the product of p1 and p2 and return the
result:</p>
<p id="demo"></p>
<script>
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
[Link]("demo").innerHTML = "The result is: " +
result;
</script>
</body>
</html>
JavaScript Function Syntax
function name( p1, p2, ... ) {
// code to be executed
}
Functions are defined with the function keyword:
followed by the function name
followed by parentheses ( )
followed by brackets { }
The function name follows the naming rules for variables.
Optional parameters are listed inside parentheses: ( p1, p2, ... )
Code to be executed is listed inside curly brackets: { }
Functions can return an optional value back to the caller.
Why Functions?
Functions enable better code organization and efficiency.
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.
Function Invocation ()
The code inside the function will execute when "something" invokes (calls)
the function:
When it is invoked (called) from JavaScript code
When an event occurs (a user clicks a button)
Automatically (self invoked)
The () operator invokes a the function.
Example
toCelsius() invokes the toCelsius funnction:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Invoke (call) a function that converts from Fahrenheit to
Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius(77);
[Link]("demo").innerHTML = value;
</script>
</body>
</html>
Arguments are Passed by Value
The parameters, in a function call, are the function's arguments.
JavaScript arguments are passed by value: The function only gets to know
the values, not the argument's locations.
If a function changes an argument's value, it does not change the
parameter's original value.
Changes to arguments are not visible (reflected) outside the
function.
Objects are Passed by Reference
In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the
function.
Class task
1. Write a program using a function that accepts three interger
values compares the values and outputs the largest on the screen.
2. Password Strength Checker
Write a function checkPassword(password) that checks if a password length ≥ 8 and
contains numbers and letters.
3. Palindrome Checker
Create a function isPalindrome(word) that returns true if the word is the same
backward and forward.
4. Prime Number Checker
Write a function isPrime(num) that determines whether a number is prime.
5. Find the Largest Element in an Array
Write getMax(arr) that returns the largest number in an array.
6. Sum of Array Elements
Write a function sumArray(arr) that returns the total of all array values.
7. Count Vowels in a String
Create countVowels(str) that returns the number of vowels in a string.
8. Temperature Converter Menu
Use a function with multiple conditions to convert Celsius ↔ Fahrenheit ↔ Kelvin based
on user choice.
9. Simple Calculator Function
Create calculate(a, b, operator) that performs +, -, *, or /.
10. Find Minimum and Maximum
Write a function that returns both min and max values from an array.
11. Bank Withdrawal Simulation
Create a function withdraw(balance, amount) that deducts and returns the new
balance if enough funds exist.