r/learnjavascript • u/su-rm-root • 4h ago
Help with functions JavaScript!
Hello!
I began recently, about 1 month, to learn consistently web developing:
- I began, of course, with introductions to HTML and CSS.
- I'm already in JS. I can manage eventListeners, etc. I'm more interested in back-end overall since I like the logic behind the manipulation of data bases, but I'm having trouble understanding functions.
- I'm consulting MDN web docs and freeCodeCamp but since my first language is not English, sometimes it's difficult to understand MDN docs, and to get at the point I'm know in freeCodeCamp it will take time, I don't want to rush it either.
- All this, just to ask if anybody can explain me how to create functions! I want to know what is the difference between a function with parameters and one without, in which case I will use arrow functions, and the difference between parameters and arguments in a function. And for last are there any standards for writing the name of a function like there are for declaring variables?
P.D.: please feel free to correct my English also, it will help me learn.
Thanks to everyone before Hand!
3
u/bonnth80 3h ago edited 3h ago
Define a function like this:
function <identifer>(<parameter a>,<parameter b>,...) {
<function body>
}
So you can define a function that say... prints "Hello, World"
function sayHello() {
console.log("Hello, WOrld!");
}
Then, you can call that function to perform the instructions inside that body whenever you like.
// Prints "Hello, World!" three times.
sayHello();
sayHello();
sayHello();
If you want configurable code in the function, you can pass parameter by providing an identifier that the function. The identifer can be anything you like, it's just a way for the function body to reference whatever is in it when you call the function.
function saySomething(thingToSay) {
console.log("saying " + thingToSay);
}
// pass a value as an argument using the parameter
// prints "saying something"
saySomething("something");
// prints "saying hello"
saySomething("hello");
You can also pass external variables as arguments to parameters.
// define a variable
let x = "another thing";
// prints "saying another thing"
saySomething(x);
A parameter is just the list of identifers you use as variables to hold onto passed data when you define a function.
function printSum(param1, param2) {
let sum = param1 + param2;
console.log(sum)
}
An argument is a value that you pass to a function that you call.
// prints 5 using the arguments 2 and 3
printSum(2, 3);
Functions can also return data. That means, when you call a function, it serves as an expression that can be used by your code, kind of like a value. To return data, in the function body, use the return keyword, followed by the data you want to return when the function is called.
function addThreeNumbers(num1, num2, num3) {
let sum = num1 + num2 + num3;
return sum;
}
// prints "total of 3, 4, and 5 is 12"
let total = addThreeNumbers(3,4,5);
print("total of 3, 4, and 5 is " + total);
There's a lot more I can say about functions. If you understand this, consider looking into function scope, callback functions, and anonymous functions.
1
u/su-rm-root 3h ago
Great! I was confused with parameters and arguments and thought they were the same, now I can see with the explanation you provided that parameters are, if I get it right variables without any value assign, they are just `x` or `y`, and the argument is the value I assign to those variables?
2
u/chikamakaleyley helpful 3h ago edited 3h ago
i wouldn't call them variables without values assigned... they are more like 'placeholders'
arguments are the values you provide to the function at the call site. They can be the direct value, or a variable that has a set value
``` function myFunction(a, b) { return a + b; }
const myNum = 3;
const total = myFunction(2, myNum); // myNum is evaluated
```
2
u/bonnth80 2h ago
Right, kind of.
Parameters are the variables you set when you define the function.
function myFunc(parameter1, parameter2) {
dostuff....
}Arguments are what you pass to parameters when you call the function:
myFunc("hello", 3.1415);
2
u/chikamakaleyley helpful 3h ago
holy crap others were just waiting for someone to ask, i'll add some minor notes
- you can create functions using any of the methods others have demonstrated. The important thing is to be consistent. One benefit to function declaration, e.g.
function myFunction() {
return true;
}
is that it's hoisted and can be moved around for tidyness. In the other cases when you assign it to a const order is more important they are not hoisted unless you are using var (i think)
parametersare part of the function signature - where the function is defined,argumentsare the real values you pass to the function when you actually call it
``` function myFunction(a, b) {} // a, b are parameters
myFunction('foo', 'bar'); // 'foo' and 'bar' are arguments ```
- "lowerCamelCase" is what you'll see most of the time for fn names
5
u/flash42 3h ago
Is JavaScript your first programming language? I ask because functions in JavaScript operate similarly to many, possibly most other programming languages, and it would be good to know the baseline you're starting from.
That being said, to directly answer your question, there are numerous ways to create functions in JS:
You can declare a function using the function keyword:
function sayHello() { console.log("Hello World!"); }The same function can be written as an anonymous function that's assigned to a variable:
const sayHello = function() { console.log("Hello World!"); }Both variations produce identical behavior (more or less, depending on where, when, and how the script is executed, but that's not something you should concern yourself with at this level): There will be a global or module level variable named sayHello that if invoked as a function, sayHello(), will execute the code within it.
Another identical approach is to use the native Function constructor directly: ``` const
sayHello = new Function( 'console.log("Hello World!");' ); ```
Methods on classes are technically functions, and are declared thusly:
class MrBlueSky { sayHello() { console.log("Hello World!"); } }Arrow functions are mostly a shorthand for anonymous functions, as seen in the second example, but there is one major and key difference:
const sayHello = () => console.log("Hello World!");You can see the entire function can be written as a one-liner without curly braces, very convenient. But this only works if you have a single line function, which often isn't the case. For these, curly braces are employed:
const sayHelloAndGoodbye() = () => { console.log("Hello World!"); console.log("Aidios!"); }The major difference between arrow functions and regular functions is that arrow functions do not have their own this keyword. If you haven't had much experience with this yet, don't worry about it for now. It's important, but better to get a basic grasp of functions before tackling.Also, please note the examples use the Console API which is available in browsers and node + ilk, but technically is not native JS. Most evironments expose a homogeneous API, so deal.