JavaScript Functions - How Functions Work in JavaScript
JavaScript Functions
JavaScript functions are used to perform some operations. We can call JavaScript function many times to reuse the code.
1. Code reusability :
- We can able to call the function several times so it save coding.
2. Less coding :
- It makes our program more simple and easy. We don’t need to write many lines of code each time to perform the same task.
![javascript-function javascript-function](https://cdn.wikitechy.com/tutorials/javascript/javascript-function.gif)
Sample Code
<!DOCTYPE html>
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Output
![javascript-functions-alert javascript-functions-alert](https://cdn.wikitechy.com/tutorials/javascript/javascript-functions-alert.jpg)
Function with Return Value
- We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.
![javascript-function-return-value javascript-function-return-value](https://cdn.wikitechy.com/tutorials/javascript/javascript-function-return-value.gif)
Sample Code
<html>
<body>
<script>
function kaashivInfo(){
return "hello kaashivinfotech! How r u?";
}
</script>
<script>
document.write(kaashivInfo());
</script>
</body>
</html>
Output
hello kaashivinfotech! How r u?