Functions are very important and useful in any programming language as they make the code reusable A function is a block of code which will be executed only if it is called. If you have a few lines of code that needs to be used several times, you can create a function including the repeating lines of code and then call the function wherever you want.
Creating a Function
- Use the keyword function followed by the name of the function.
- After the function name, open and close parentheses.
- After parenthesis, open and close curly braces.
- Within curly braces, write your lines of code.
Syntax:
1
2
3
4
5
6
7
| function functionname() { lines of code to be executed } |
Try this yourself:
You can create functions with arguments as well. Arguments should be specified within parenthesis
Syntax:
1
2
3
4
5
6
7
| function functionname(arg1, arg2) { lines of code to be executed } |
Try this yourself:
You can also create functions that return values. Inside the function, you need to use the keyword returnfollowed by the value to be returned.
Syntax:
1
2
3
4
5
6
7
8
9
| function functionname(arg1, arg2) { lines of code to be executed return val1; } |
Try this yourself: