In this session today we will study the FUNCTIONS in an java script.
- To understand the functions in java script follow the steps given below :
- For passing a parameter in the function ,lets take an example, so write the following code in Notepad++ or any other text editor :
<!Doctype html> <html> <head> <title>Javascript Functions</title> <script> function add(num1,num2){ sum = num1 + num2; return sum; } </script> </head> <body> <script> document.write(add(5,5)); </script> </body> </html>
- So your Notepad++ window will have the following look after writing the code :
- When you open it in the browser you will have the following output :
- Let’s have another example of function which will display a message on the button click event :
<!DOCTYPE html> <html> <head> <script> function myFunction() { alert("Hello Friend!"); } </script> </head> <body> <button onclick="myFunction()">Click it</button> </body> </html>
- Hence after writting the code you editor window will have the following look :
- When you open it in the browser you will get the following output :
- Now lets have an example to call a function with arguments on the button click ,so write the given code in Notepad++ editor :
<!DOCTYPE html> <html> <body> <p>Click the button to call a function with arguments</p> <h1> Welcome </h1> <button onclick="myFunction('Tom ','Jerry')">Click it</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script> </body> </html>
- After writing the code your Notepad++ window will have the following look :
- Now when you open it in the browser you will get the following output :
- Thus, we have implemented functions with paramaters in javascript .