Functions in Javascript
1.1 Simple example of a javascript function: create and invoke
<script>
function showMessage() {
alert( 'Welcome to KMIT!' );
showMessage();
// showMessage(); // can call many times for eg.
</script>
1.2 Local variables
A variable declared inside a function is only visible inside that function.
function showMessage2() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
showMessage2(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function. look at Inspect>>console
How to solve this error? One solution is
Outer variables
A function can access an outer variable as well, for example:
let userName = 'John';
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
showMessage(); // Hello, John
let userName = 'John';
function showMessage() {
userName = "Bob"; // reassigned another value to the outer
variable
let message = 'Hello, ' + userName;
alert(message);
}
alert( userName ); // John before the function call
showMessage();
alert( userName ); // Bob, the value was modified by the function