-2

In javascript, a = alert("why?") does the same thing as just alert("why?).

Why? And what is the name of that feature of the language?

2
  • 1
    Check if this SO post helps. stackoverflow.com/questions/12380382/… Commented Sep 2, 2013 at 5:32
  • thanks! the description in the answer of how the code is parsed helps clarify things. Commented Sep 2, 2013 at 6:12

3 Answers 3

5

You're calling a function, which does whatever the function is defined to do, and then assigning the return value of that function to the variable.

Practically every programming language works like this. You need to learn basic programming concepts.

This is called assigning the result of a function to a variable, and is a common way to use functions. If you just do:

alert("Foo");

that's called calling a function.

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

6 Comments

Thanks for your answer... re: "You need to learn basic programming concepts" Lol :) Yes, well, that's what I'm trying to do. More specifically what I am trying to do is acquire the vocabulary. To rephrase my question: "what do you call it when you use the alert function in conjunction with a variable, as opposed to 'on its own' ?" Of course that assuming there are in fact specific terms. In any event, once I identify the terminology, then it is much easier to search for explanations and learn those basic concepts!
There's nothing special about the alert function. a = alert(...) is no different from a = Math.random(). They both call a function, and assign the result to a variable.
sorry - not talking about the alert function in particular. It could be setTimeout or whatever... my question is regarding the terminology difference between using the function 'with a variable' rather than 'on its own'.
It's called "assigning the result of a function to a variable"
Gotcha. Thanks. In this case it would seem there is no generic 'handle' for that move.
|
2

Because you are calling a function when you pass in a parameter. For example, if you wanted a to actually be a variable that points to the alert function, then you would do something like this:

var a = alert;

Ideally, whenever you pass in the parameter, the function gets called. Then you could do something like:

a("Why?");

And it would get called.

Comments

1

The RHS of an assignment is an expression.

A function invocation is an expression. It is executed and then its return value is assigned to the identifier on the LHS.

<variable> = <exp>

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.