Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Functions Js

java script
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Functions Js

java script
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like