Function
Functions are reuseable code blocks that are used for particular task. It is executed when the particular function is called. Functions are fundamental in all programming languages.
- A function can be created with the function keyword, a name, and parentheses.
- The code to run is written inside curly brackets.
<script>
function sayHello() {
return "Hello World";
}
let greeting = sayHello();
console.log(sayHello());
</script>
A function can be used many times,
function add(a, b) {
return a + b;
}
let sum1 = add(5, 5);
let sum2 = add(50, 50);
Local Variables
- Variables declared within a JavaScript function, become LOCAL to the function.
- Local variables can only be accessed from within the function.
// code here can NOT use ActorName
function myFunction() {
let ActorName = "Surya";
// code here CAN use ActorName
}
// code here can NOT use ActorName
Local variables are created when a function starts, and deleted when the function is completed.
Function Input and Output
- Parameters - some values are sent to the function
- Arguments - some values are received by the function
- Function Code - some work is done inside the function
- Return Output - some value is returned from the function
The working flow of the Function:
1
The function returns the value "Hello world". But it will not run the code.
function sayHello() {
return "Hello World";
}
2
The code below will call the function; but it will not use the result.
function sayHello() {
return "Hello World";
}
sayHello();
3
When a function returns a value, you can store the value in a variable.
function sayHello() {
return "Hello World";
}
let greeting = sayHello();
4
Display the result
function sayHello() {
return "Hello World";
}
console.log(sayHello());
Top comments (0)