Question

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
Was it helpful?

Solution

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".

OTHER TIPS

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");

Try this:

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top