Most time we want to write functions that take inputs.
function doSomething(input) {
console.log(run some code);
}
This syntax to say that a function is expecting something to be passed in that it's expecting an argument looks like this rather than an empty "()".
For example, if we want to calculate square, we can write it in function.
function square(num) {
console.log (num * num);
}
Here, we give a name "num" for the input, but you can give any name you want.
Then we give a number in the "()", then call the square(10), so we get the result 100.
It also works for the string. For example, if we want to say hello to someone, we can use function.
function sayHello(name) {
console.log ("Hello" + name + "!");
}
We call sayHello ("Tom"), it gives us Hello Tom!
Functions can have as many arguments as needed. For example, if we want to calculate area, we can give two inputs: length and width, and then run the code.
Arguments are one of the important pieces and functions that make them really useful because it is not only about shortening our code and repeating the same chunk of code every time. It is also about making that code change a little bit depending on some inputs.
Comments
Post a Comment