+ 7
"use strict" + arguments[i]
This is paraphrased question from a timed JavaScript Challenge. This one had two topics I haven't seen yet which are "use strict" and the keyword arguments[i]. What is the output? function foo(str) { arguments[0] = "Hello"; return str; } function bar(str) { "use strict"; arguments[0] = "Planet"; return str; } console.log(foo("Pizza") + " " + bar("World")); The output is "Hello World" I think this happens because "use strict" will not allow you to reassign arguments[i] because it can cause errors or poses security issues(?). Maybe both? What insights do you have? Thank you!
12 odpowiedzi
+ 2
Hi DumbledoresAmy,
Thanks for tagging me, I just learned this myself right now. Very nice question.
Regarding strict mode:
Its an ES5 feature, previous JS versions (mostly ES3) were very forgiving (they throw very less errors).
strict mode tries to resolve this by enforcing stricter rules and throwing error for many forgiving cases.
Regarding this problem :
In bar( ), with strict mode "arguments" behaves more like a keyword and only stores the original value passed to it, when the function was called.
Trying to modify "arguments" in strict mode will have no effect on it, so doing
arguments[0] = "Planet" ;
is useless, as "arguments" cant be modified in strict mode.
https://developer.mozilla.org/en-US/docs/Web/Javascript/Reference/Strict_mode#Making_eval_and_arguments_simpler
+ 5
DumbledoresAmy
I couldnt say much on this as I have yet to do Professional development specially to target old browsers.
But since I always use ES6+ features and follow good practices, I never used strict mode. Many browsers by default use strict mode now, so I see no reasons to use strict mode.
strict mode is a feature to help Developer, so using it during development will be definitely helpful and not much harm.
I ll look into this more
+ 2
jay I tried the same code commenting out "use strict" and then arguments reassigns and works the way I would have guessed. When I Googled "use strict" MDN says use strict won't allow reassignment of arguments. I'm curious about the why. Does reassignment lead to errors or security issues? Also, I have never used "use strict" or "arguments[i]" before this challenge question so these are both new topics for me.
+ 1
Use strict does alows reassign there is a error in your code that's why its not reassigning
+ 1
Morpheus What can you tell me about "use strict"?
+ 1
Could be that strict is preventing that. Did u try to run the code in browser or node. Check the console, it would interesting to see
+ 1
This is interesting. Does "use strict" come up often in professional JS development? Thanks!
0
Tyler Schum I hope your around 😎
0
Joel Obot Welcome! I created a "Introduce yourself" post and tagged you if you feel like connecting that way. Good luck with all your coding adventures!
- 1
Am kinda new here....
- 2
hello