1

Can someone explain to me the difference of when to use a function by feeding your variables into the parenthesis, and when to tack the function on after the variable with a period, like using the toString() function?

example code

function addMe(a){
a = a+1;
return a;
}
var num = 1;
addMe(num);
num.toString();

I'm not actually sure if my syntax is correct, but I want to know when to feed a variable as a parameter, like how I feed the variable num, to the addMe function. And when to use the function .toString() by putting a period after the variable and typing out the function.

could I have done something like this- provided I built my function correctly?

var num = 1;
num.addMe();

Thanks for the help!

4
  • 3
    One is a function, the other is a method. Methods are functions of an object, inherited under what's known as prototypal inheritance. See also Functions vs. methods Commented Feb 13, 2019 at 18:37
  • 1
    "I'm not actually sure if my syntax is correct" Have you tried running your code. You will be able to ask a better question if you first attempt to understand the concept you are asking about. If you run this from a browser you will get good information from the console log. Commented Feb 13, 2019 at 18:40
  • Have a look at developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… Commented Feb 13, 2019 at 18:44
  • Utkanos your article was perfect, i didnt even know what to search for thank you this answers my question Commented Feb 13, 2019 at 19:08

3 Answers 3

3

The first is used for simple 'stand alone' functions, while the latter is used for object methods. E.g a number object by default has a toString() method. Some object methods may also require parameters to be passed between the parentheses.

Sign up to request clarification or add additional context in comments.

Comments

0

Variables (a function declaration is just a function stored in a variable) are looked up in the scope chain (going up to the next outer scope until a variable with the name is found):

 let a = 1; // outer scope

 { // inner scope
   console.log(a); // looked up in "inner scope", than "outer scope"
}

Properties of an object are looked up in the objects prototype chain, so if you do

a.b

then a gets looked up in the scopes as explained above, then b is accessed on the resulting object (everything is an object in JavaScript, except for "nothing" (undefined, null)) by looking up the prototype chain. For a simple object, the chain is quite short:

 const a = { b: 1 }; // object -> Object.prototype

Here b will be found in the object itself. However all objects inherit from the Object.prototype object, so if you add a property to that (please don't):

 Object.prototype.test = 1;

you can then look it up on every object, as the lookup traverses up the prototype chain, and reaches Object.prototype:

 console.log({}.test); // 1

Now for numbers (like in your case), they inherit the Number.prototype so you could do:

Number.prototype.addMe = function() {
 console.log(this);
};

// two dots are needed to distinguish it from numbers with a fraction (e.g. 1.2)
1..addMe();

That said, now addMe can be called on every number, everywhere in your code. While that might seems useful, it is actually a pain as you don't know where a certain method was added

 1..whereDoIComeFrom()

that makes code unreadable and unstructured. Instead if you need a certain functionality multiple times, abstract it into a function, don't touch the native prototypes.


I assume that addMe is just a simplified example, if it isn't, read on:

If you pass an argument to a function in JavaScript, the value will be copied (it is a bit more complicated with non primitives (everything except numbers, booleans etc.)) into the parameter variable of the function called so here:

function addMe(a){
 a = a+1;
 console.log(a); // 2
 return a;
}

var num = 1;
addMe(num);
console.log(num); // 1 ... ?

you actually got two variables (a and num), changing a does not change num. But as you return a you can do:

num = addMe(num);

which copies the value of num into a, then increases a by one and then copues the value of a back to num.

6 Comments

"a function is just a variable too" Debatable ;) I know what you are trying to say, but a function in and of itself is a value. A variable is a container for a value.
Not everything in JavaScript is an object. undefined, null, numbers, strings, and booleans are not objects. typeof null === 'object' is just a quirk. numbers, strings, and booleans can implicitly be converted to Number, String, or Boolean objects, but null and undefined are never objects and have no object equivalents.
@paulpro as primitives are "boxed" (yes, not a JS term) I think it's a reasonable simplification
Yes, but if one thinks that numbers and strings are objects he might be very confused when he tries to do something like var x = 5; x.foo = 'bar'; console.log(x.foo); one day.
@paulpro yes, we could write another book explaining every part of JS just to answer this question without leaving out details. I tried to answer enough to give the OP a starting point for research & experimenting
|
0

When you did var num = 1 you created a JavaScript object. It looks just like a number but you can think of everything in JavaScript as an object (simplification) and all these objects have different features. So a number has some features, a string has some other features, etc.

You mentioned one feature: toString. Another feature would be toLowerCase.

toString and toLowerCase are functions that come with JavaScript. These functions are then "put on" all of these objects for us to use.

I can have a string variable like

var text = 'MY TEXT'
var lowercaseText = text.toLowerCase()
console.log(lowercaseText) // my text

This code will work because it was decided that the toLowerCase function should work on strings

I can also have an array (list of items)

const list = ['A', 'B', 'C']

const answer = list.toLowerCase()
console.log(answer)

But this code won't work because toLowerCase doesn't work on arrays. So you get the following error message: list.toLowerCase is not a function.

Basically its saying: I don't know what toLowerCase means when used on this list variable (array).

In JavaScript this is called prototypes. Prototype is a way for JavaScript to get some feature from another. Basically: I have all kinds of functions, what object can use what functions. This is called the prototype chain.

In both cases you are using a function. addMe is a function you created and toString is a function in JavaScript that has been placed on objects through this prototype-chain.

Im not actually sure if my syntax is correct

Yes your syntax is correct. Your addMe function is the standard way to create a function in JavaScript.

But i want to know when to feed a variable as a parameter, like how i feed the variable num, to the addMe function.

Just like you did, you define a function and parameters like you did.

..and when to use the function .toString() by putting a period after the variable and typing out the function.

When you want to place your function on a object so that all instances of that object can you that object.

In most cases, espcially when you are starting out. You don't have to worry about these prototypes. The way you did.

function addMe(number) {
  return number+1 
}

const answer = addMe(1) //2

Is a standard way of defining a function and calling it.

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.