Arguments and temporary variables in Javascript Functions - javascript

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?

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.

Related

Is it possible to write every function as "pure function" in Google Apps Script?

I am interested in functional programming, so I decided to try this approach on the scripting environment of my Google Sheets file, and you know that the scripting language is Google Apps Script, which is basically javascript. And it even supports some (if not all) ES6 syntax.
The problem is that I cannot directly run any code, for example:
let a = 4;
Logger.log(a);
I mean, I cannot run it globally, I need to define a function with any name, and then place the code inside that function, and I can run the function, so the function runs the code inside.
So, maybe you ask, "why this behavior makes a problem writing pure functional code?" well, because, as I know, two of the most important factors about pure functions are:
1) We must not use global variables/functions inside a function, instead we must pass as parameters (and then as arguments of course).
2) defining function inside a function is often not very good idea in terms of readability and organization of the code.
So, I want to define more functions (to do some stuff), not just one "main" function, and I could not find any way, any single way to write code (as a whole) without violating at least one of the two statements above.
So, I mean, I can not write anything without making at least one non-pure function.
As a user explained in the comments:
Your 1st assumption is partially incorrect. A function must not depend on global, mutable variables, but it may depend on global constants and global pure functions. However, often you rather want to pass a function dependency as an argument to obtain a more general higher order function. Your 2nd assumption is merely opinion based.
So you could, for example, define a main function to run your code as a whole while defining functions inside the main function to achieve functional programming with Apps Script.

variable assignment vs passing directly to a function

What are the advantages/disadvantages in terms of memory management of the following?
Assigning to a variable then passing it to a function
const a = {foo: 'bar'}; // won't be reused anywhere else, for readability
myFunc(a);
Passing directly to a function
myFunc({foo: 'bar'});
The first and second code have absolutely no difference between them (unless you also need to use a later in your code) in the way the variable is passed.
The are only 2 cases in which the first might be preferred over the second.
You need to use the variable elsewhere
The variable declaration is too long and you want to split it in two lines or you are using a complex algorithm and want to give a name to each step for readability.
It depends on the implementation of the JavaScript engine. One engine might allocate memory for the variable in the first example and not allocate memory in the directly-passed example, while another implementation might be smart enough to compile the code in such a way that it makes the first example not allocate memory for a variable and thus leaves the first example behaving as the directly-passed example.
I don't know enough about the specific engines to tell you what each one does specifically. You'd have to take a look at each JS engine (or ask authors of each) to get a more conclusive answer.

Should you use named functions when developing a JavaScript library?

For example:
module.exports = {
myLibraryFunction: function myLibraryFunction() {
...
}
}
The disadvantage is obvious. It's not very DRY, which means it can easily become out-of-sync if you're not careful. It also makes your code a little more verbose.
So what are the advantages? Is the tradeoff worth it?
I use this approach when writing JS libraries. The largest advantage is that tools like the Chrome debugger will have a definite name for your function as opposed to either "anonymous" or some name composed of the function path based on the variable names containing the function. If, however, you don't care about having method names when debugging, then it really comes down to a matter of taste. If you were to minify the resulting JS code, naming elements like that would get stripped out anyway.
As far as to how DRY this approach is, consider that the repeated names occur right next to each other. A quick copy & paste is all it takes to keep them in sync. It would be nice if a JS included a feature that causes a function to be named according to the variable it has been assigned to at the point of creation (or at least the ability to dynamically re-assign the function's name). Sadly, however, this is the only way JS allows for us to name these otherwise anonymous functions.

Understanding Object Chaining

I am learning about object/method chaining in JavaScript and I would like make sure I understand it correctly.
If the following code is an example of JavaScript without object chaining:
var people = helper.getPeople();
var bob = people.find("bob");
var email = bob.getEmail();
and the code below is after applying object chaining:
var email = helper.getPeople().find("bob").getEmail();
Am I to consider object chaining as simply a way to "drill down" into an object, reaching "sub-objects" or properties/methods etc...?
If these two examples of code are supposed to do the same thing, why is a var declaration not required in the object-chained example? I do not understand how the chained statement is the same if no new variables are declared in the process.
I can see the value of saving space and writing the code on one line, and all my research online has shown that this is considered an intuitive, simplified way to write. However, I feel that I am able to read the first example (without object chaining) better. That may just be because I am new to JavaScript, but which example would be considered good coding practice?
Additionally, is the purpose of object chaining merely to reach objects that are not defined in the global scope? A way of reaching local objects?
Thank you for your help!
Am I to consider object chaining as simply a way to "drill down" into an object, reaching "sub-objects" or properties/methods etc...? Is the purpose of object chaining merely to reach objects that are not defined in the global scope? A way of reaching local objects?
It could be. Every of these methods does return another object with methods, that's the secret of chaining. "Drilling down" might be an appropriate wording for some uses, like the one you've shown, where different objects are returned.
However, whether these returned objects are hidden, local "sub-objects", accessible through other means or just created on the fly by that method, or even the original object that returns itself, is dependent on the methods and API design. All options make valid chaining, though.
If these two examples of code are supposed to do the same thing, why is a var declaration not required in the object-chained example? I do not understand how the chained statement is the same if no new variables are declared in the process.
Returning objects that are immediately accessed does not require them to be assigned to any variable. They of course are held in memory somewhere, but don't have an explicit identifier attached to them.
That may just be because I am new to JavaScript, but which example would be considered good coding practice?
Depends. Usually, a good practise is not to create variables if you don't need them. If you are only interested in the email and won't access all the people and bob again, there's no reason to create variables for them.
The readability can be increased by putting each method call on a new line, which is common in JS for chaining:
var email = helper.getPeople()
.find("bob")
.getEmail();
(with various styles of indentation for the subsequent lines)

Javascript Function Scope

This is perhaps a dumb question, but I am new to Javascript and desperate for help.
If the Javascript engine will look for global variables outside of a function, then what is the point of passing parameters to it? What do you gain?
I understand that global variables are generally frowned upon, but I still don't understand the purpose of passing variables. Does it have something to do with data encapsulation?
There's a few magic words that are used by programmers to describe different kinds of functions. Here's a few:
Re-entrant
ThreadSafe
Referentially Transparent
Idempotent
Pure
Side-Effects
You can look some of them up if you want a headache. The point is that Computer science and engineering progress has always been about reducing complexity. We have spent quite a lot of time thinking about the best way to write a function to achieve that goal. Hopefully, you can stuff tiny bits of your program into your head at a time, and understand those bits, without having to also understand the overall functioning of the entire program simultaneously, or the detailed implementation of the insides of all the other functions. A function that uses global variables can't do that very well because:
You can't guarantee that the global variables exist
You can't guarantee that the global variables are what you think they are
You can't guarantee that other parts of the program haven't modified those variables in a way you didn't expect.
You can't easily generalise to use the function multiple times on multiple sets of variables.
You can't easily verify that the function works as advertised without first setting up the function's external environment and its dependencies.
If the global variables have changed in a way you didn't expect, it's really hard to track down which part of the program is the culprit. It could be any of 500 different functions that write to that variable!
On the other hand, if you explicitly pass in all the data a function needs to operate, and explicitly return all the results:
If something goes wrong with any of those variables, it's easy to find the source of the problem
It's easier to add code to verify the "domain" of your inputs. Is it really a string? Is it over a certain length, is it under a certain length? Is it a positive number? is it whole, or fractional? All these assumptions that your code needs to operate correctly can be explicit at the start of the function, instead of just crossing your fingers and hoping nothing goes wrong.
It's easier to guess what a particular function will actually do, if its output depends only on its input.
a function's parameters are not dependant on the naming of any external variables.
And other advantages.
if you were only going to use global variables that the functions worked on then you'd always have to know the inner workings of the functions and what your global variable names had to be for them to work.
also, something like Math.abs(n) would be hard to call twice in one line if using global variables.
Functions are reusable components of your code, that executes a particular snippet on the provided variable exhibiting varying behavior.
Encapsulation comes from being Object Oriented. Functions are more for giving structure to your program.
Also, you shouldn't undermine the execution time of a method, if the variable it access exists in the context rather than being global.
If you don't need parameters to be passed to functions, then, you really don't need functions.
Functions are usually (and should be) used to provide code re-use -- use the same function on different variables. If a function accesses global variables, then every time I use it it will perform the same action. If I pass parameters, I can make it perform a different action (based on those different parameters) every time I use it.
One of the main benefits is that it keeps all the information the function needs, nearby. It becomes possible to look at just the function itself and understand what its input is, what it does, and what its output will be. If you are using global variables instead of passing arguments to the function, you’ll have to look all over your code to locate the data on which the function operates.
That’s just one benefit, of many, but an easy one to understand.
Global variables (in any language) can sometimes become stale. If there is a chance of this it is good to declare, initialise and use them locally. You have to be able to trust what you are using.
Similarly, if something/someone can update your global variables then you have to be able to trust the outcome of what will happen whenyou use them.
Global variables are not always needed by everything so why keep them hanging around?
That said, variables global to a namesapce can be useful especially if you are using something like jquery selectors and you want to cache for performance sake.
Is this really a javascript question? I haven't encountered a language that doesn't have some form of global variables yet.

Categories