All Articles

JavaScript Tricky Situations - 02

inner peace

Let’s consider below code.

setMyNames("Rasika", "Gayan");

function setMyNames(myName, myName) {
  console.log(myName);
}

Take a few seconds and think about what will be the outcome?

                                ...

Okay, let me explain this. This is totally legit code. Because we didn’t use the strict mode, JavaScript allows us to create duplicate variable names. First, it will create a myName variable inside the function scope and assign the value as Rasika and then check that is there any variable called myName. We already have a variable called myName and the 2nd variable value will be assigned to it as Gayan. Because of that the output will be Gayan.

We can easily avoid these situations using strict mode.

Try below code.

"use strict"

setMyNames("Rasika", "Gayan")

function setMyNames(myName, myName) {
  console.log(myName);
}

Once you run that code, you will get this error.

SyntaxError: Duplicate parameter name not allowed in this context

So, make sure to use strict mode to avoid this kind of scenarios.

If you have anything to ask regarding this please leave a comment there. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you.

That’s for today friends. See you soon. Thank you

Main image credit