7 Console.log and return - why are both necessary?


#1

Hi, I would like to understand why there needs to be a console.log inside the 'if' loop. When I comment out that line, everything still seems to work fine. The question could also be, what is the role of the 'return' command here?

var search = function(name){
for ( var key in friends){
if (friends[key].firstName===name){
//console.log(friends[key]);
return friends[key];

Thanks!


#2

console.log will output first name to the console, this function is used to ouput values from variables, or get useful information about arrays and other different types of data. console.log inside if condition is likely needed to find out first name, to understand fully you have to understand what your declared search function does. At first you declared function with name search this function has one parameter name so you can pass an argument to this function in order to find something.

Then, in for loop you loop through every item of friends array, at this point key is the current index of friends array, then you check: if friends[key].firstname === name , that means you check if firstname property from friends array by specified index is identical to passed argument value name and if it is then you output that value to the console. To see how console.log works in action you have to open Developer Tools in your browser, you should find it somewhere in the tools section, or by pressing F12 on a keyboard. It will simply print out value of friends[key] to the console, so you can see what you get.

About return statement, this statement is needed to return something, some functions return something and some don't. In this case return friends[key], returns value that is specified by key in friends array. It can be useful later if you want to store that value in variable or somewhere else or to make comparisons and return statement terminates further execution of function, by that I mean everything that is after return statement will be ignored and thus won't be executed, once function reaches return statement it stops. In a nutshell function is the thing in which you can put values and get values out of it.

I suggest you to try and play with console.log more so you can find out it for yourself how it can be useful to you. You can also find a lot and I mean a lot of information on the internet about console.log function and return statement once you know it all it will be like a second nature.