-1

I come from C and C++ language and I have a hard time understanding some thing about JavaScript : are variables (parameters) copied in JavaScript when entering a function?

In C/C++, arguments are duplicated for the function and can not be change within the function (of course you can pass pointers as arguments but they cant be change themselves). In JavaScript, it looks like (with closure for instance) you can declare variables inside a function, then use them afterwards. you can also change the parameters inside a function and they keep these modifications afterwards.

Am I right if I say there is only one context of execution in a JavaScript application?

Théophile Pace
  • 826
  • 5
  • 14
  • _In C/C++, arguments are duplicated for the function and can not be change within the function_, this is true in `C`, but in `C++` there is a pass by reference (using `&` before the argument), regarding your javascript question: [this](http://stackoverflow.com/a/7744623/1606345) can help. – David Ranieri Feb 22 '17 at 09:13
  • C, C++ and Javascript are all part of the curly-braces family of languages. That's as helpful as a comparison between them can be. I recommend you learn JS as a novice. Comparing it to C at every step will just make you more confused. – StoryTeller - Unslander Monica Feb 22 '17 at 09:17

1 Answers1

1

In C you can pass a structure either by value in which case it is copied into a function (and out of it if you return it), or you can pass a pointer to the structure in which case it is not copied and all the changes you make are visible to the caller. In C++ it is the same except you can also pass by reference which behind the scenes is like passing a pointer but the compiler hides it from you a bit.

Think of Javascript as getting all structures passed by reference. Nothing is every copied unless you explicitly copy it.

Also Javascript variables don't contain objects in the variable, they only contain references to the object. So in C/C++ terms all objects are heap based, there are none stored on the stack.

For simple types such as numbers there may be a copy made but as you can't tell it doesn't really matter what it does. Strings are probably passed by reference but as you can't modify an existing string there's no way to tell that either.

I say probably because it's the semantics of the call that matter, different Javascript runtimes could choose to implement things differently provided you can't tell the difference.

Duncan
  • 92,073
  • 11
  • 122
  • 156