Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function and variable with the same name

The following code-snippet is a test to see what happens when a function and a variable share the same name in the same scope. In Chrome it appears the variable definition has precedence in reference.

  1. Can the named function be executed, or is it completely obscured by the variable declaration?
  2. Is it the standard behavior in Javascript that variables take precedence over functions with the same name?

Sorry for the two part question, but it seemed wasteful to ask two separate questions.

Code:

<!DOCTYPE html>     <head>         <meta charset="utf-8">         <title></title>     </head>     <body>         <script>              var overlapping = function() { return 'this is a var holding an anonymous function' };              function overlapping()             {                 return 'this is a function definition';             }              output( overlapping, 'overlapping' );             output( overlapping(), 'overlapping()' );              function output( expression, description )             {                 document.writeln( '<li>' + ( description ? ('<i>' + description + '</i>: ') : '' ) + expression + '</li>' );             }         </script>     </body> </html> 
like image 561
Mark Fox Avatar asked Feb 24 '13 22:02

Mark Fox


People also ask

Can variable and function have the same name?

You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!

What is the preference given if a function and variable has same name?

If you use a function name as variable name , its value is replaced by function body .

Can function and variable name same in Python?

Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.

Can you name a variable a function?

Naming variablesMostly, you can name variables however you please. Variables are local to the program in which they appear, so one function can have a variable or argument named x and another function can have a variable or argument of the same name, and there is no confusion.


1 Answers

In JavaScript, function definitions are hoisted to the top of the current scope. Your example code therefore reads as:

var overlapping = function() { return 'this is a function definition' }; var overlapping = function() { return 'this is a var holding an anonymous function' }; 

This is some good read about this topic: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

like image 143
Niko Avatar answered Oct 09 '22 05:10

Niko