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 jQuery Basics (2014) Creating a Password Confirmation Form Perfect

Nicholas Woods
Nicholas Woods
6,260 Points

Struggling with my understanding of functions as functions and functions used in methods.

In JavaScript Basics we were taught that a function has to return something with return (from what I took from it anyway). But Andrew has us using functions as methods (or in methods), which has me a little confused. I know this is a fundamental concept and was wondering if someone could do their best to shed light on the matter.

Examples:

Standard function called:

standardfunction.js
function canSubmit() {
  return isPasswordValid() && arePasswordsMatching();
}

Function used in method:

methodfunction.js
function passwordEvent() {
  //find out if password is valid
   if(isPasswordValid()) {
    //hide hint if password is valid
    $password.next().hide();
   } else {
    //else show hint
    $password.next().show();
   }
}

3 Answers

Functions and methods are not the same. They have very similar features, but they are used in different ways. Functions can be explicitly called, whereas methods are implicitly called by an object. Methods are attached to objects and return information to an object. Functions can return information to objects, variables, other functions, etc.

Edit:

I admit that my original example was a poor example because although the sayhello and sayhola functions were attached to an object, they were still functions because they did not require nor act upon the object they were initialized with.

However, follow along with me, and let's look at a function and a method. I'm going to use the following function "prompt()". And I'm also going to use the following method "toUpperCase()".

The difference between these two is that "prompt()" does not require an object to act upon which is what makes it a function. It can be called from anywhere explicitly and can have parameters passed into it. I can call "prompt()" completely by itself with a parameter without getting any reference errors. It will just have nowhere to send the data and will log it to the console if you're using Firefox or Chrome. Verify this by running the following in your web console (or a test JS page):

prompt();
//Or:
prompt("Put something in here:");
//Or:
var someVariable = prompt("Put something in here:");

Now, let's take a look at "toUpperCase()". "toUpperCase()" requires a string to act upon in order to act correctly. I cannot pass in parameters to this method, nor can I call it by itself. Verify this by running the following in your web console (or a test JS page):

//Throws a reference error of not being defined:
toUpperCase();
//Throws another reference error of not being defined:
toUpperCase("hi");
//This will work because it has an object to act upon
"hi".toUpperCase();

You can never call the "toUpperCase()" method without an object for it to act upon, because otherwise, it is undefined. To further support my claim, read over the MDN (Mozilla Developer Network) terminology used in the "toUpperCase()" article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

Nicholas Woods
Nicholas Woods
6,260 Points

Thanks Marcus.

Here is what I understand (although I am not certain I'm right). In JavaScript you can create a function and if that function is in the global scope it can be called on it's own or passed to an object. If it's passed to an object it would be considered a method. However, if the object created is a method that holds a function, it needs another object to act upon for it to run in the code.

It's not a question of if it can be passed to another object, because both can pass values on to an object. Functions are called by themselves, without any other object attached to it. Methods require an object to act upon in order to be called.

For example, if you were calling the toUpperCase() method, you would put an object to be referenced, and then call the method upon it using dot notation:

var str = "hey there!";
str = str.toUpperCase();
//outputs HEY THERE!
alert(str);

toUpperCase() requires an object to act upon, which is why it is a method. It has to be implicitly called by a variable of the type String because it is in the String prototype methods. You can't call this method on any other type of variable such as a number, array, etc.

Functions can be called without any regard for variable type because they aren't attached to any object. They can return any type of valid value and do not require an object to be acted upon.

Paolo Scamardella
Paolo Scamardella
24,828 Points

I disagree Marcus. Functions and Methods are used interchangeably. They are just two different words for the same thing.

They are not the same thing, as I've stated, and as the JavaScript community agrees. A function can be independently called (explicit) whereas a method requires an object to act upon (implicit). If you take a look at the method such as toUpperCase(), it requires an object of type String to act upon. It can't be called the same as a function and have parameters passed into it. They are different.

Nicholas Woods
Nicholas Woods
6,260 Points

I've done a lot of hunting around and I think this video may be helpful: https://ilovecoding.org/tutorials/difference-between-method-and-function/. According to this video, a function is not a method, but all methods are a special type of function that are associated with an object - he goes into more detail.

Paolo Scamardella
Paolo Scamardella
24,828 Points

Nicholas and Marcus, I'm no JS expert, but you do realize when you defined a function like this:

function doSomething(){
   console.log("Do Something");
}

//or

var doSomethingTwo = function(){
    console.log("Do Something Two");
};

I can call both functions like:

doSomething();

doSomethingTwo();

window.doSomething();

window.doSomethingTwo();

I defined both as a function, but at the end, those two are attched to the window object.

So, are they a method?

What's the difference?

Maybe not in the JS world, but I have seen and hear people calling methods and functions interchangeably.

Nicholas Woods
Nicholas Woods
6,260 Points

Paolo I have just started learning JavaScript recently, so you would know more than me. I think in the broadest sense if you consider that everything in JavaScript is an object, then you could say all functions can be used as methods. However, from my understanding, don't you need to make the connection between the object and the function explicitly before it can be considered a method? It's nomenclature, and I guess the main thing is we know how to use them.

Here is the thing with your functions, Paolo, "doSomething()" and "doSomethingTwo()" do not require an object to act upon in order to function correctly. The "window" object applies to every single thing within a script, but it is not a required object. Please see the answer I posted that utilizes an already existing function and an already existing method.

Paolo Scamardella
Paolo Scamardella
24,828 Points
function canSubmit() {
  return isPasswordValid() && arePasswordsMatching();
}

canSubmit() is a function (or a method...same thing) that calls two functions inside (isPasswordValid() and arePasswordsMatching()). When you call canSubmit(), the canSubmit() method calls 2 more methods inside and returns a boolean (true or false). If isPasswordValid() and arePasswordsMatchning() are both true, then canSubmit() will return true. If one of them is not true or both of them are not true, then canSubmit() returns false.

The reason Andrew puts isPasswordValid() and arePasswordMatching() in its own function is because you can call it mulitple times in your script, and if you need to change the logic of those methods, you can do it in one place only, and you are done.

For example,

/*
    Lets image you need to change the logic of password.length > 0 to password.length > 3
    you now have to go to even single line and change it to password.length > 3.
*/

var password = "password";

if(password.length > 0) { // code } else { // code } // change here

if(password.length > 0) { // code } else { // code } // change here

if(password.length > 0) { // code } else { // code } // change here

if(password.length > 0) { // code } else { // code } // change here too and so on

// and more....

VS

/*
    Lets image you need to change the logic of password.length > 0 to password.length > 3
    you now have just have to go inside the isPassword() method and change it once, and you are done
*/

function isPasswordValid(){
  var password = "password";
  if (password.length > 0) // change here
  { 
       return true;
  { 
  else 
  { 
       return false;
  }
}

if(isPasswordValid()) { // code } else { // code }

if(isPasswordValid()) { // code } else { // code }

if(isPasswordValid()) { // code } else { // code }

if(isPasswordValid()) { // code } else { // code }

This is just a basic example...

Hope this helps!!!

I admit that my original example was a poor example because although the sayhello and sayhola functions were attached to an object, they were still functions because they did not require nor act upon the object they were initialized with.

However, follow along with me, and let's look at a function and a method. I'm going to use the following function "prompt()". And I'm also going to use the following method "toUpperCase()".

The difference between these two is that "prompt()" does not require an object to act upon which is what makes it a function. It can be called from anywhere explicitly and can have parameters passed into it. I can call "prompt()" completely by itself with a parameter without getting any reference errors. It will just have nowhere to send the data and will log it to the console if you're using Firefox or Chrome. Verify this by running the following in your web console (or a test JS page):

prompt();
//Or:
prompt("Put something in here:");
//Or:
var someVariable = prompt("Put something in here:");

Now, let's take a look at "toUpperCase()". "toUpperCase()" requires a string to act upon in order to act correctly. I cannot pass in parameters to this method, nor can I call it by itself. Verify this by running the following in your web console (or a test JS page):

//Throws a reference error of not being defined:
toUpperCase();
//Throws another reference error of not being defined:
toUpperCase("hi");
//This will work because it has an object to act upon
"hi".toUpperCase();

You can never call the "toUpperCase()" method without an object for it to act upon, because otherwise, it is undefined. To further support my claim, read over the MDN (Mozilla Developer Network) terminology used in the "toUpperCase()" article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

You will see this same terminology applied to a great many methods such as "toLowerCase()", "toLocaleLowerCase()", "isArray()", etc. etc. They all require an object to act upon in order to be successfully called.