In javascript, as in any other programming language, functions are performed directly and indirectly.
Straight lines, for example, add two numbers and return
function sum(a, b) { return a + b; } // в этом случае результат роботы функции можно записывать в переменную var rez = sum(2,2); console.log(rez); // или просто выводить в лог console.log(sum(1,2));
Side effects of functions are those actions that they perform with the environment in which they are called, for example, the same addition, but the result is written to the global visibility variable, and is not returned as a result
var rez; function sum(a, b) { rez = a + b; } // функция еще не отработала значение `undefined` console.log(rez); // функция уже отработала однако видим значение `undefined` потому что функция ничего нам не возвращает console.log(sum(1, 2)); // видим тройку потому что во время работы функции в предыдущей инструкции она совершила побочное действие над переменной `var rez` присвоив ей сумму передаваемых параметров console.log(rez);
It is worth noting that in javascript functions always return something, if the return instruction is not explicitly specified in the body, then the return value is undefined
These things can be combined, for example
function sum(a, b) { console.log('я посчитала'); return a + b; } console.log(sum(1, 2));
Here the return of the sum of numbers is a direct action, and the output of the message to the log is side.
Now about your example. You have a function that performs only side effects, in this case passing an array of four names as parameters. You get into a block.
if (userNames.length > 3) { let loadingMessage = "This might take a while..."; console.log(loadingMessage); }
And you actually get this message to the log, however, since you are accessing the function through console.log too, it displays undefined in the second line, since the function returns nothing.
Rewrite the example and you will get the expected (I hope :)) result
function loadProfiles(userNames){ if (userNames.length > 3) { let loadingMessage = "This might take a while..."; console.log(loadingMessage); } else { let flashMessage = "Loading profiles"; console.log(flashMessage); } } loadProfiles(["user1","user2","user3","user4"]);
or so
function loadProfiles(userNames) { if (userNames.length > 3) { let loadingMessage = "This might take a while..."; return loadingMessage; } else { let flashMessage = "Loading profiles"; return flashMessage; } } console.log(loadProfiles(["user1", "user2", "user3", "user4"]));
javascriptfunctions? - Vasily Barbashev