In JavaScript, to return a string in a function, we simply need to use the return statement. Here is a very simple example.

function someFunction(){
  return "someString";
};

If we were to call the function, someFunction(), then the string "someString" would be returned.

function someFunction(){
  return "someString";
};

console.log(someFunction());

#Output
someString

The return statement will end the function right when it is called and return whatever value is next to it.

And that’s how easy it is to return a string. Let’s see a couple more examples.

function examplefunction1(name){
  var nameString = "Hello " + name;
  return nameString;
};

function examplefunction2(){
  return "Function ends here";
  var anotherString = "This code and the return statement below it will not run";
  return anotherString;
};

function examplefunction3(){
  var currDate = new Date();
  var month = currDate.toLocaleDateString('en-US', { month: 'long'});
  return month;
};

console.log(examplefunction1("Henry"));
console.log(examplefunction2());
console.log(examplefunction3());

#Output
Hello Henry
Function ends here
September

Return Multiple Strings in JavaScript

If we wanted to return more than one string using JavaScript, we could simply put the strings in an array and return the array. Here is a simple function to do this.

function someFunction(){
  var string1 = "This is a string.";
  var string2 = "This is another string.";
  var arr = [];
  arr.push(string1);
  arr.push(string2);
  return arr;
};

console.log(someFunction());

#Output
["This is a string.", "This is another string."]

Hopefully this article has helped you understand how to use JavaScript to return a string.

Categorized in:

JavaScript,

Last Update: March 11, 2024