Functions are basically magic boxes that do things. They can often take input and give output.
In math an example function is very commonly named f
. Imagine you input 2 into f and you get back 4… The function f could look like f(x)=2+x
or f(x)=2x
, you’d need to input a few more numbers to figure out the nature of that function… but let’s just say it’s f(x)=2x
and try to translate it to javascript.
One simple way to write it would be
function f(x){
return 2*x;
}
Note that if we invoke the function now to test it:
f(16);
…it’ll execute the code but the user won’t see anything.
To do that we would have to console.log(f(16));
The tricky thing about javascript is how it uses multiple programming paradigms so sometimes you might see something like
const f = (x) => 2 * x;
to describe the same function. It’s important to note that the two functions behave almost the same (except notably, this last example is missing the return
keyword… but the same result is being returned).
If you want to learn this type of style of writing functions I would read up more on function expressions and arrow functions.
Good video for reference: Python Tutorial for Beginners 8: Functions - YouTube (I know it’s python but it may still help)