0

I've noticed in Javascript there are 2 different ways to use functions:

  1. Use the variable followed by a dot and then the function, like string.trim();
  2. Use the variable inside the function, like parseInt(string)

What are the differences?

Are the one in point #1 not functions? How are they called?

I know inside parenthesis you can have more variables, but why is str.trim() and not trim(str)?

2
  • 2
    Note that technically parseInt(string) is actually window.parseInt(string) - ie it's still a function on a "variable", that happens to take an argument. Commented Aug 13, 2015 at 10:26
  • 2
    Also, since parseInt is mentioned here without using one, "Always specify a radix to avoid this unreliable behavior" Commented Aug 13, 2015 at 10:27

1 Answer 1

2

They are both functions, but I believe the first example in your question is normally called a method.

I'd encourage you to read the really useful Functions chapter of Eloquent Javascript. Just a couple of extracts that seem relevant:

A function definition is just a regular variable definition where the value given to the variable happens to be a function.

and

A function is created by an expression that starts with the keyword function. Functions have a set of parameters (in this case, only x) and a body, which contains the statements that are to be executed when the function is called. The function body must always be wrapped in braces, even when it consists of only a single statement (as in the previous example).

A function can have multiple parameters or no parameters at all.

I would also keep in mind that in JS almost everything is an object, or as someone else put it:

Since functions are objects, they can be used like any other value. Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to functions, and functions can be returned from functions. Also, since functions are objects, functions can have methods

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

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.