Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build an Interactive Website Form Validation and Manipulation Checking Values

Nthulane Makgato
PLUS
Nthulane Makgato
Courses Plus Student 19,602 Points

Confusion over method and function

Hi Guys

Here is a code challenge question that generated a lot of confusion for me:

"Create a method called 'isValidEmail' that takes one argument that returns true when a string with an '@' symbol is passed, false if not."

the answer that was accepted is:

function isValidEmail(email){ return email.indexOf('@') != -1; }

My question is, why do they ask for a method when a method is a function in an object?

ie var object = { method: function(){} }

The final answer is not nested in curly braces which makes me wonder why I am asked to create a method.

I would also like to know how the answer to this question is boolean

Thanks for your input.

1 Answer

This is true, for most programming languages, but strictly speaking, in JavaScript, all functions are methods.

When you define a function in JavaScript (inside the global scope), it actually becomes a property of the global object. Try doing this:

function test() {
    console.log("I am actually a method.");
}

// You can invoke it "normally"
test(); // output: I am actually a method.
// You can invoke it as a method on the global object (inside a browser, that object is window)
window.test(); // output: I am actually a method.
// Or inside the global scope, you can refer to the global object by using this
this.test(); // output: I am actually a method.

I agree, the challenge wording is a bit confusing, and it's much better to refer to functions as functions and use methods for functions attached to objects, but I repeat, strictly speaking, in JavaScript, all functions are methods.