1

I have defined my JavaScript function as follows:

function printCompanyName(company1, company2, company3, company4, company5)
{
document.write("<p>" + company1 + "</p>");
document.write("<p>" + company2 + "</p>");
document.write("<p>" + company3 + "</p>");
document.write("<p>" + company4 + "</p>");
document.write("<p>" + company5 + "</p>");
}

And called it as follows:

printCompanyName("Dell, Microsoft, Apple, Gizmodo, Amazon");

But I get the following output:

Dell, Microsoft, Apple, Gizmodo, Amazon

undefined

undefined

undefined

undefined

What gives!? I have been trying to figure this out for hrs. I want:

Dell
Microsoft
Apple
Gizmodo
Amazon
1
  • Let this be a lesson to you! Don't spend more than 1 hour before you (search, then ask) on stackoverflow. Commented Feb 8, 2010 at 2:45

4 Answers 4

3

You're passing a single string that happens to contain 4 commas.
Therefore, the first parameter contains that single string, and the other 4 are undefined. (Sisnce you only gave one value)
Since Javascript parameters are optional, you don't get an error by not passing values for the other parameters.

You need to pass 5 different strings with commas between them, like this:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon");
Sign up to request clarification or add additional context in comments.

Comments

2

You want to call:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon");

The way you're currently doing it you're passing in one company "Dell, Microsoft, Apple, Gizmodo, Amazon".

1 Comment

Thank you so much! You saved my life because i was about to take it!
1

Try this:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon");

Comments

0

additional informations :

A way to use the function with the parameter as a string commas separated :

function printCompanyName(names)
{
    // also check the type of names (you know "if it is a string object")

    var data = names.split(',');    
    for(var i in data) {
        document.write("<p>" + data[i].trim() + "</p>");  
    }
}

exemple: printCompanyName("Dell, Microsoft, Apple, Gizmodo, Amazon");

Otherwise a multi parameters function using the internal arguments var :

function printCompanyName()
{
    for(var i in arguments) {
        document.write("<p>" + arguments[i] + "</p>");  
    }
}

exemple: printCompanyName('Dell', 'Microsoft', 'Apple', 'Gizmodo', 'Amazon'); juste like SLaks said.

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.