Javascript function and return


#1

Hello guys
I am a beginner in javascript and now i am learning javascript function but there is something i dont understand between function and return : why i do have to use return in case like this

function myInfo() {
var myName = “John”;
}
myInfo();

i got nothing from this even there is a value for var but nothing happens when i write this function
and i have to use return in it

function myInfo() {
var myName = “John”;
return myName;
}
myInfo();

but if i use alert without using return , it works

function myInfo() {
var myName = “John”;
alert(“Hello John”);
}
myInfo();
i don’t know the reason so i will really appreciate it if something can help me and explain this to me in easy way
Thanks


#2

Hey @thedriver51 :smiley:
So to put it simply, a variable is just something that stores a datatype for later usage.
It won’t do anything unless you return or console.log the value.
There’s also commands in the JavaScript library like that alert, prompt, and confirm that output the value in a pop-up box.
You could use your myName var and alert(myName);

Hope this clears everything up!!!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.