In the past few months that I've been learning Javascript, I've wondered which is the better usage of functions:
Functions that perform actions based on their arguments with no return value:
const someName = 'John';
function sayHello(name) {
console.log(`Hello, my name is ${name}!`);
}
sayHello(someName);
Or functions that return a value based on their arguments, which can then be used to perform an action:
const someName = 'John';
function hello(name) {
return `Hello, my name is ${name}!`;
}
console.log(hello(someName));
Maybe a more practical scenario... (Edited)
const myImage = document.getElementById('myImage'); // get image
const numberField = document.getElementById('myField').value; // get input field data
function calculateBrightness(input) { // option 1: return calculated brightness percentage
return `brightness(${input / 2}%)`;
}
function setBrightness(image, value) { // option 2: set image brightness to calculated percentage
image.style.filter = `brightness(${input / 2}%)`;
}
// option 1
let brightness = calculateBrightness(numberField);
myImage.style.filter = brightness;
// option 2
setBrightness(myImage, numberField);
My style is usually in line with the latter examples. To my understanding, the latter functions are also considered "pure" functions since they do not mutate any variables (which are a core principle in functional programming).
My main questions are:
- Does either style have any strict advantages, or is it all down to personal preference/use scenario?
- Should I be using either style over the other?
- Is there a name for the way in which the former examples are structured?
EDIT: Reorganized the second scenario as per Adam B's suggestion. Earlier answers may be referring to the old code.