Codekw
Codekw

Reputation: 17

How to concatenate values of parameter when strings

This calls me to concatenate two strings that are not yet declared they are still in parameter

I have tried to give the parameter values in string form and have console log the strings to become arguments in console.log(string + string2)

function concatenateTwoStrings(string1, string2) {

  var string1 = "dance"
  var string2 = "party"
}
console.log(string1 + string2)

expected result is danceparty actual result is syntax error.

Upvotes: 0

Views: 1541

Answers (2)

Sumner Evans
Sumner Evans

Reputation: 9157

JavaScript has function scoping which means that string1 and string2 are only accessible from within the concatenateTwoStrings function.

Where you have the console.log statement, the variables are out of scope.

Additionally, you probably want to pass the strings to the function instead of defining them inside of the function.

Maybe what you want to do is put the console.log inside of the function and call the function with "dance" and "party" as parameters:

function concatenateTwoStrings(string1, string2) {
  console.log(string1 + string2)
}

concatenateTwoStrings("dance", "party")

Or you may want to return the concatenated string and then console.log result:

function concatenateTwoStrings(string1, string2) {
  return string1 + string2;
}

console.log(concatenateTwoStrings("dance", "party"))


Further Resources:

Upvotes: 3

cullanrocks
cullanrocks

Reputation: 497

You have to define your variables outside of the function if you want them passed as a parameters. You also have to pass those arguments into the function and invoke the function.

var string1 = "dance"
var string2 = "party"

function concatenateTwoStrings(string1, string2) {
  return string1 + string2;
}
console.log(concatenateTwoStrings(string1, string2))

Upvotes: 1

Related Questions