Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  32] [ 1]  / answers: 1 / hits: 18956  / 12 Years ago, sun, february 24, 2013, 12:00:00

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>

More From » syntax

 Answers
101

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


[#80028] Friday, February 22, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skyler

Total Points: 646
Total Questions: 119
Total Answers: 96

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
skyler questions
;