I found that there are these two ways that a variable property value can be updated on a function call
Example 1:
function bar( arg ) {
return arg + 1;
}
var foo = {
num: 1
};
foo.num = bar( foo.num );
console.log( foo.num );
Example 2:
function bar( arg ) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar( foo );
console.log( foo.num );
I want to know what are the proper naming convention for each of the method calls.
Also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
Primitive parameters (such as a number) are passed to functions by
value; the value is passed to the function, but if the function
changes the value of the parameter, this change is not reflected
globally or in the calling function.
If you pass an object (i.e. a non-primitive value, such as Array or a
user-defined object) as a parameter and the function changes the
object's properties, that change is visible outside the function.
Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Well in javascript objects are passed by reference so when you pass a object to a function you're passing it's memory reference not a copy.
So when you update value in the function it updates the value at reference.
function bar(arg) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar(foo);
console.log(foo.num);
When you pass a primitive value it is passed by value. It passes a copy of value so whatever changes you do in close function will not affect the original value.
function bar(arg) {
arg = arg + 1;
}
var foo = 1
bar(foo);
console.log(foo);
I want to know what are the proper naming convention for each of the methods.
There are no naming conventions for functions (I would only call them methods if they are directly associated to an object), except thar the name is camelCase. However there is a convention in functional programming that functions that return something are pure (they do not change anything, but just return something new, like your first function), and functions that return nothing are impure, they change something. Wether you strictly follow that pattern depends on your codingstyle, I follow that often but not always. It is also a bit harder in JS as JS is not typed.
also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
It is impossible. If you pass a number, it is passed as a value, you have no way to find out where that number belongs to. Thats a good thing as you can always keep track which function is able to mutate an object. bar(foo) is, bar(foo.num) is not.
Related
I would like to create a re-usable function that changes the boolean value of the variable that is passed in.
My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.
let editable = true;
function toggleEditMode (item){
item = !item;
}
toggleEditMode(editable);
Any help?
You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference
Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.
var i = { a:true }
function c(o){
o.a = !o.a
}
c(i)
console.log(i);
Here's the problem (called "Compose functions (T Combinator)" on codewars.com, in case you want to try it out in the original environment):
Let's make a function called compose that accepts a value as a parameter, as well as any number of functions as additional parameters.
The function will return the value that results from the first parameter being used as a parameter for all of the accepted function parameters in turn. If only a single parameter is passed in, return that parameter.
So:
var doubleTheValue = function(val) { return val * 2; }
var addOneToTheValue = function(val) { return val + 1; }
compose(5, doubleTheValue) // should === 10
compose(5, doubleTheValue, addOneToTheValue) // should === 11
Here was one of the possible solutions:
var compose = function(initialValue) {
var functions = Array.prototype.slice.call(arguments, 1);
return functions.reduce(function(previousResult, func){
return func.call(this, previousResult);
}, initialValue);
}
Why do we need to return func.call(this, previousResult) rather than just func(previousResult)? The latter only works in some cases. What will "this" default to without the call?
Why do we need to return func.call(this, previousResult) rather than just func(previousResult)?
We don't really. this is not the this value of the compose function (what the author probably intended), but of the reduce callback - where it is specified to be undefined.
What will "this" default to without the call?
undefined as well, see Why is "this" in an anonymous function undefined when using strict?.
In strict mode, this will be undefined since there is no calling context.
In non-strict Javascript it will be the global object (window in a browser).
Why do we need to return func.call(this, previousResult) rather than just func(previousResult)?
this defaults to our window.
Basically, we're giving it a secondary value in order to further our progression down the line.
If you were to call simply previousResult, the JS doesn't know where to look to find such a thing. Your are referencing the window if you don't call a prior parameter. This is very common in most OOP languages. You can't look for your value IN window without further defining that you want something IN window.
Essentially, we are just providing a bogus variable in order to get to the next step in the chain. You will see this a lot with Python and Ruby code.
The reason you set this is because this will equal the parent window, then you know you can find the next variable within that particular parameter.
Simple Example:
It's sort of like trying to call a variable in a different function. Just doesn't work without defining your scope first.
Quick question on Javascript to which I can't find a clear concise answer.
I'm building an app that's way ahead of anything I've done before and involves multiple classes being instantiated. These objects are then passed into a processing class that checks user inputs, draws onto canvas and updates the objects that it has been passed.
I am wondering, how does JavaScript handle passing objects to functions? Am I passing a copy of the object, or am I passing a reference to the object?
So if my controller class alters one of the objects variables, is that changed everywhere or just in the object that that controller sees?
Sorry for such a simple, possibly easily testable question but I'm not even sure if I'm making a class correctly at this point thanks to errors piling up.
When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.
function myfunction(x)
{
// x is equal to 4
x = 5;
// x is now equal to 5
}
var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4
Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function
function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6
As well described in https://stackoverflow.com/a/5314911/636348, in JavaScript it's always pass by value, but for objects the value of the variable is a reference.
So, it's not a pure pass by reference. Here's an example to understand this concept:
E.g.:
x = {member:"foo"}
If you change the object with another object inside a function, you won't get the new object outside the function scope because you just create another object. The original reference is still bound to the original object:
function changeObject(x) {
x = {member:"bar"};
}
changeObject(x);
alert(x.member)
output: foo
instead, if you alter a member inside a function, the object will be changed:
function changeMember(x) {
x.member = "bar";
}
changeMember(x);
alert(x.member)
output: bar
If you pass in a variable which is pointing to an object, it passes a reference to the object. If you pass in an object literal, then obviously no other class or function will be able to change that object.
I'm just trying to get a better understanding/confirmation of function arguments
In the function seen here:
function newFunction(data, status){
would the function apply specifically to data and status variables?
I don't quite understand how the arguments work.
Basic Scenario
When a function is defined, the () area is used for inputs. These inputs are mapped to what data is sent in.
function newFunction(data, status){
}
newFunction(1,2);
In this scenario, data will be assigned the value of 1, and status will be assigned the value of 2 for the scope of newFunction.
Missmatched inputs
However, it does not always directly map. If fewer arguments are sent, then the unassigned input variables become undefined.
function newFunction(data, status){
}
newFunction(1);
In this scenario, data will be assigned the value of 1, and status will be assigned the value of undefined for the scope of newFunction.
arguments object
Inside of the scope of newFunction, there is also access to the array like object called arguments.
function newFunction(data, status)
{
var args = arguments;
}
newFunction(1);
In this scenario, the variable args will hold the arguments object. There you can check args.length to see that only 1 argument was sent. args[0] will give you that argument value, being 1 in this case.
Function object
A function can be made into an object with the new keyword. By using the new keyword on a function, a Function object is made. Once the Function object is made, this may be used to refer to the current Function object instead of the global window.
function newFunction(data,status){
if( this instanceof newFunction ){
//use as a Function object
this.data = data;
}else{
//use as a normal function
}
}
var myNewFunction = new newFunction(1);
In this scenario, myNewFunction now holds a reference to a Function object, and can be accessed as an object through dot notation or indexing. myNewFunction["data"] and myNewFunction.data now both hold the value of 1.
This means that the function accepts both data and status parameters. The programmer calling the funciton (you) is required for providing the parameters when calling the function (also known as arguments.)
Let's look at a simplified example:
function add(x, y) {
return x + y;
}
The function here takes two numbers, adds them together, and returns the result. Now, as a programmer, you have the benefit of adding two numbers whenever you want without having to duplicate the functionality or copy/paste whenever you need your application to perform the same functionality.
Best of all, another programmer you work with can add two numbers together without worrying about how to do it, they can just call your function.
EDIT: Calling the function works as follows
var num1 = 10;
var num2 = 15;
var z = add(num1, num2); //z = 25
function newFunction(data, status){ ... function code ... }
This is the Javascript definition of a function called newFunction.
You can pass arguments to a function. These are variables, either numbers or strings, with which the function is supposed to do something.
Of course the function behaviour/output depends on the arguments you give it.
http://www.quirksmode.org/js/function.html
My programing background is that I learned a little Java in school. JavaScript syntax tends to confuse me for some reason. The JavaScript code below is a pattern of syntax that I don't know what to make of:
foo.ready = function(variable){... var whatever = variable.bar();
One of my main points of confusion is the parameter. For a contrasting example, in Java, if I call a method with one parameter, the call sends one parameter. I don't see how the parameter named 'variable' is ever set.
The variable is assigned when foo.ready is invoked, and passed some value (presumably a function).
var foo = {}; // 1. Create an object named "foo"
// 2. Assign a function to the "ready" property of "foo"
foo.ready = function(variable) {
// 4. "foo.ready" has been invoked, and received a function to its
// "variable" parameter, which it then invokes.
// The return value is assigned to "whatever"
var whatever = variable();
alert( whatever ); // 5. alert the value returned from the function
};
// 3. Invoke "foo.ready" passing a function as the argument.
// The function merely returns a string
foo.ready( function() { return "Hello world"; } );
Here's a working example: http://jsfiddle.net/69grz/
variable can be much more than a real variable, it can also be a function or a handler/object. In this case you call the function bar() on the object variable
foo.ready refers to an entire function. You can call foo.ready(), with any number of arguments, too. This is a typical call-back pattern: Whoever is in charge of the foo object wants to call you back when she's ready, so you pass this function to her.
You can't really control how many variables (of any type!) will be passed to your function, but presumably the documentation will have told you that you'll receive at least one.
Here is some code that makes that work:
// foo is an object
var foo = {};
// Create a function and assign to the ready property
foo.ready = function(variable){
var whatever = variable.bar();
};
// Create an object that contains a function named bar
var x = {
bar: function(){ return 42; }
};
// Call the function in foo with the object as parameter
foo.ready(x);
The expression variable.bar() will call the function in the object x which returns the value 42, which is then assigned to the variable whatever.