Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I able to define same function twice in javascript?

I have a javascript file in which I write a bunch of jquery functions. I have a function to return the angular scope. I found out that if I were to write the same function twice, the code still executes.

function getngScope()
{
    alert(2);
    return angular.element($('#data-area')).scope();
}

function getngScope()
{
    alert(1);
    return angular.element($('#data-area')).scope();
}

When I call getngScope() I get "1" alerted and the scope returned. Why does it have this behavior?

like image 216
Undefined Variable Avatar asked Jul 30 '26 12:07

Undefined Variable


2 Answers

The second definition of an Object overwrites the first one. In general the last definition of an object overwrites all previous definitions.

Functions in JavaScript are Objects:

(function () {}) instanceof Object === true

When you create a new global function f it's equivalent to creating a property in the window object and assigning the function definition to that variable, if you create a function:

function myFun() { console.log('my function') };

and then check the value of window.myFun you'll notice it is the same function as myFun:

window.myFun === myFun // true

You'll also notice that modifying window.myFun changes/overwrites myFun.

E.g.

function myFun() { console.log('myFun') };
myFun(); // Prints: 'myFun'

// Overwrite myFun
window.myFun = function () { console.log('NoFun') };
myFun(); // Prints: 'NoFun'

The second definition of the function takes precedence.

I recommend you read the chapter on Functions from JavaScript: the good parts by Crockford.

like image 77
pgpb.padilla Avatar answered Aug 01 '26 02:08

pgpb.padilla


functions are data in memory, so when you define another function with the same name, it overrides the previous one.

like image 44
Zohaib Ijaz Avatar answered Aug 01 '26 03:08

Zohaib Ijaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!