loading...

re: I just learned: JavaScript tricks you into thinking it has keyword arguments. VIEW POST

FULL DISCUSSION
 

Those aren't keyword arguments, you are creating variables in the global scope and passing them to the function. a=1 is just saying window.a = 1 and then passing 1 to your function. a is now a variable in global scope.

 

Agreed. This is one of the few JavaScript quirks that I feel is extremely dangerous and very confusing for beginners.

As a follow up for OP to explain why this works, a JavaScript function accepts any argument that are valid expressions (ie. can be evaluated to a value). For example, try this:

console.log(a = 1) // 1
console.log(const a = 2) // error!

This is because a = 1 is an expression which evaluates to the value 1, while const a = 2 is not. As such, calling a function like func(a = 1) is perfectly valid JavaScript and is akin to calling func(1).

It is also perfectly valid JavaScript to declare variables without any of the keywords like var, let, or const. However, like Mike has said, whenever you do this, you are polluting your global scope with these variables, and this will lead to a myriad of problems. I will strongly recommend not to declare variables like this.

code of conduct - report abuse