2
function space(str,numSpace){
     str = "";
     numSpace = (" " + " ");
     document.write(numSpace + str + numSpace);
}
console.log(space("hi", " "));

This is not working out, I'm not too sure how I can add whitespace to both ends of a string.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Tiago Sa
  • 87
  • 1
  • 6
  • well, line one you're overwriting the incoming string with "". Then in line two you make a string with two spaces, again, ignoring the value passed in .. and then in line 3 you travel back to the 1990's and `document.write` the 2 spaces, and empty string and 2 spaces - and you never return anything, so the `console.log` will log `undefined` – Jaromanda X Mar 30 '17 at 01:02
  • another thing to keep in mind, most web browsers collapse whitespace; No matter if you enter 1 space or 1000, the browser will collapse them down to 1. – Claies Mar 30 '17 at 01:32

2 Answers2

-1

Don't overwrite you're function's parameters with constants, and don't use document.write but return the result:

function space(str, numSpace) {
    return numSpace + str + numSpace;
}
console.log(space("hi", " "));

Also I would suggest renaming numSpace to spaces, as the former suggests to be used with an integer count, not a string of spaces.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

This is not working out, i'm not too sure how I can add whitespace to both ends of a string.

you're always resetting the parameter str to empty string hence the unexpected behaviour.

there are two ways you could solve the issue at hand.

1) you could use console.log() inside the method, example:

function space(str, numSpace) {
    var result = numSpace + str + numSpace;
    console.log(result);
}
space("hi", " ");

2) you could return the value then use console.log():

function space(str, numSpace) {
    return numSpace + str + numSpace;
}
var result = space("hi", " ");
console.log(result);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126