0

I am writing code to execute two functions with the same name. I am using two different approaches:

Method1: with storing function in var

<!DOCTYPE html>
<html>
<body>
 <div id="demo1">I am div1.</div>
 <div id="demo2">I am div2.</div>
    <script>
  let x;
  var fun1 = function(val1, val2){
   x = val1 + val2;
   document.getElementById('demo1').innerHTML = x;
  }
  fun1(2, 2);
  
  var fun1 = function(val1, val2){
   x = val1 + val2;
   document.getElementById('demo2').innerHTML = x;
  }  
  fun1(1, 1);
    </script>
</body>
</html>

Method2: using simple function

<!DOCTYPE html>
<html>
<body>
 <div id="demo1">I am div1.</div>
 <div id="demo2">I am div2.</div>
    <script>
  let x;
  function fun1(val1, val2){
   x = val1 + val2;
   document.getElementById('demo1').innerHTML = x;
  }
  fun1(2, 2);
  
  function fun1(val1, val2){
   x = val1 + val2;
   document.getElementById('demo2').innerHTML = x;
  }  
  fun1(1, 1);
    </script>
</body>
</html>

Why does method1 execute both functions while method2 does not.

Elliot B.
  • 17,060
  • 10
  • 80
  • 101
Tushar Acharekar
  • 880
  • 7
  • 21

1 Answers1

2

In JavaScript, functions are defined with the function keyword.

To define a function, you can either use a function declaration (your method 2) or a function expression (your method 1).

Function declarations hoist the definition. You can use the function before you declare it:

fun1(); // logs "bar"

function fun1() {
  console.log('foo');
}

// Both function declarations are hoisted to the top
// The second declaration 'overrides' the first declaration
function fun1() {
  console.log('bar');
}

This also means that the second declaration of fun1 overrides the first declaration because they are both hoisted.

However, function expressions (method 1) are not hoisted:

fun1(); // TypeError: fun1 is not a function

var fun1 = function() {
   console.log('foo');
}

fun1(); // logs 'foo'. the variable fun1 is hoisted, but the function is not.

var fun1 = function() {
    console.log('bar');
}

fun1(); // logs 'bar' because fun1 is now assigned to a different function.
Elliot B.
  • 17,060
  • 10
  • 80
  • 101