Lucho Gizdov
Lucho Gizdov

Reputation: 105

What is wrong with this javascript code? The return is wrong

var number = prompt('Enter Number (as long as you want): '),
    output = [],
    sNumber = number.toString(),
    lastDigit,
    result,
    i;

function result(number) {
    for (i = 0, len = sNumber.length; i < len; i += 1) {
        output.push(+sNumber.charAt(i));
    }
    lastDigit = output.slice(-1);

    switch (lastDigit[0]) {
        case 0:
            return 'zero';
            break;
        case 1:
            return 'one';
            break;
            .....etc some more cases.......
            default: return 'not a valid number';
            break;
    }
}
jsConsole.writeLine('Last digit in English: ' + result);

Why the results ended with all the code but not one of the switch cases? I have struggled to get it fixed. I just want the result in the switch case to be printed.

Upvotes: 0

Views: 47

Answers (2)

musefan
musefan

Reputation: 48415

  1. You are not actually calling the result function
  2. Don't name functions and variables the same
  3. If you have a number parameter then use it, don't use global variables
  4. You don't need break if you have return
  5. prompt will return a string, so no need for toString() on it

Like this:

var sNumber = prompt('Enter Number (as long as you want): ');

function result(number) {
    var output = [];
    for (var i = 0; i < number.length; i ++) {
        output.push(+number.charAt(i));
    }
    var lastDigit = output.slice(-1);

    switch (lastDigit[0]) {
        case 0:
            return 'zero';
        case 1:
            return 'one';
        default: 
            return 'not a valid number';
    }
}

jsConsole.writeLine('Last digit in English: ' + result(sNumber));

Here is a working example


For your information, you can get the last character of a string without a loop:

var lastDigit = number[number.length-1]; 
// assuming it will always have at least 1 character, add validation to be sure

Upvotes: 3

bitifet
bitifet

Reputation: 3659

You are not actually calling result.

To call result you should do:

result()

Without parentheses you are meaning the value of result which in fact is a function.

If you also concatenate it to some string, type coercion make you to end up with the same as you were did:

jsConsole.writeLine('Last digit in English: ' + result.toString());

Upvotes: 0

Related Questions