1

I am drawing a triangle with "#" as default value if 'char' is not defined. When I define 'char' I get the triangle drawn with that particular value.

If 'char' is defined then triangle must be drawn in characters from 'char' else it should use default value '#'.

What am I missing or doing wrong?

function triangle(size, char = 0) {

  if (typeof char === 'undefined') {
    let hashKey = "#"
    while (hashKey.length <= size) {
      console.log(hashKey);
      hashKey += "#";
    }
  } else {
    let hashKey = char
    while (hashKey.length <= size) {
      console.log(hashKey);
      hashKey += char;
    }
  }
}
5
  • 2
    With your default initialiser = 0 on the parameter declaration, char will never be undefined. Commented Oct 18, 2020 at 11:18
  • char is never undefined. Whenever it gets that value (either by omitting it in the call or explicitly passing undefined), it is automatically assigned the default value 0. So the first branch of your if will never be true. Commented Oct 18, 2020 at 11:19
  • Yes I saw this, thanks, but how else to make it an optional value? Commented Oct 18, 2020 at 11:19
  • 1
    Use char = '#' instead of char = 0 Commented Oct 18, 2020 at 11:20
  • 1
    just don't assign a default value function(triangle, char) { ... or set char to the desired value function triangle (size, char = '#') { ... instead Commented Oct 18, 2020 at 11:20

3 Answers 3

3

With your default initialiser = 0 on the parameter declaration, char will never be undefined.

You'll want to write

function triangle(size, char) {
    if (typeof char === 'undefined') {
        char = "#"
    }
    let hashKey = char;
    while (hashKey.length <= size) {
        console.log(hashKey);
        hashKey += char; 
    }
}

or

function triangle(size, char = '#') {
    let hashKey = char;
    while (hashKey.length <= size) {
        console.log(hashKey);
        hashKey += char; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to assign a default value to char you can do that in the parameter defintion:

function triangle (size, char = '#'){
  let hashKey = char
  while(hashKey.length <= size ){
    console.log(hashKey);
    hashKey += char; 
  }
}
triangle(4)

Comments

0

You don't have to declare 'char' in your parametr when you call a function.

Just make it like 'function triangle (size, char)' and change condition to 'if (!char)'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.