Learn JavaScript functions

Software Engineer | Full Stack Web developer | Javascript | React.js | Python | PHP | AWS | Docker
About this tutorial
Writing the code "as it happens" is sufficient for a simple algorithm but we will very quickly be led to repeat the same logic several times. To remedy this problem, it is possible to write functions.
Syntax
Functions allow you to store a certain logic in memory that you can use several times in the rest of your code. They generally take parameters and return a particular result.
function greet (name) {
return "Hi" + name
}
// We then call our function with
greet('James') // Hello James
Functions in JavaScript are special types of variables, so it is also possible not to give them a name, but to store them in a variable in a classic way.
var greet = function (name) {
return "Hi" + name
}
We will see the difference between these 2 notations the next time. However, it is important to note a few important points regarding the functions:
- If the function does not return anything at the end of its execution then it will automatically return the value undefined.
- If we call the function by omitting certain parameters, they will take the value undefined.
var demo = function (name) {
return "Hi" + name
}
demo() // name will be undefined in the function
Example If you want to convert a number of seconds to a number of minutes, you can create a function
convert_to_min
var convert_to_min = function(seconds){
return seconds / 60
}
convert_to_min(3600) // 60
If we want to make the parameter optional and assign it the value 0 by default, we just need to add a condition
var convert_to_min = function(seconds){
if (seconds === undefined) {
seconds = 0
}
return seconds / 60
}
convert_to_min(3600) // 60
convert_to_min() // 0
