How does JavaScript pass values to a function expression within a declaration? - javascript

I'm working through Head First JavaScript and have an example:
function addN(n) {
var adder = function(x) {
return n + x;
};
return adder;
}
var add2 = addN(2);
console.log(add2(10));
console.log(add2(100));
addN(2) gets assigned to add2, but nothing gets assigned to the x. However, upon running the code, the arguments 10 and 100 clearly get passed to the x. How does JavaScript know to pass the 10 and 100 to the x value?

When you do this:
var add2 = addN(2);
The variable add2 is now effectively this:
function(x) {
return 2 + x;
}
Because that function itself is the return value of addN(). (Note that in JavaScript a function is a value that can be assigned to a variable like any other value.)
So when you further do this:
add2(10);
You are passing 10 to that function, so x will be 10.

Related

javascript inline function - what are the results?

What does this function return? I'm not familiar with this nomenclature.
let x = 2;
let y = 8;
const a = function(b) { return function(c) { return x + y + Math.abs(b) + c; } };
// Statement will go here
const fn = a(x);
For the above function, I understand the x+y part, but what is the b and c referred to in the second half? Is a(x) calling const a?
The only thing I found that refers to similar nomenclature is function x y a b in javascript, but the discussion doesn't talk about how to find what is returned. Maybe I'm not searching for the right thing and that's why my search only returned one thing that is similar.
a is the result of a function that accepts an argument, b. That function returns another function that accepts an argument c and returns x + y + c plus absolute value of b.
let x = 2;
let y = 8;
const a = function(b) {
console.log({
b
});
return function(c) {
console.log({
c
});
return x + y + Math.abs(b) + c;
}
};
// Statement will go here
const fn = a(x);
fn(12) // will have b=2 and c=12
It seems like a function pointer. function(b) accepts the parameter x that was passed into the function pointer a, this function pointer references function(b) but unlike normal functions which immediately returns a value, function(b) returns another function function(c) which ofcourse accepts one parameter and that parameter should be filled out when const fn was invoked.
My theory is that when you call fn for example fn(3) then you will get a result equivalent to 2 + 8 + Math.abs(2) + 3;
Without const fn you could also invoke a like a(2)(3) which I believe will yeild the same result.
Hope this helps.
What you see here is called currying, something related, but different from partial application.
The point is to break down a function call taking multiple arguments into multiple function calls taking single arguments.
In this case, a is a function that returns a function that returns the result of adding x, y, the absolute of b (coming from the call to a) and c (coming from the call to the return value of a).

Javascript Sequence of Function Example

function makeMultiplier(multiplier) {
var myFunc = function (x) {
return multiplier * x;
};
return myFunc;
}
var multiplyBy3 = makeMultiplier(3);
console.log(multiplyBy3(10));
So I got this example from an online course, the console prints: 30
I don't exactly understand how the value 30 was obtained, below is what I think is how it is executed, but please do correct me if false.
I assume first that the value of multiplier becomes 3, then the function makeMultiplier returns 3 * X.
From here, by assigning var multiplyBy3 = makeMultiplier(3), essentially multiplyBy3 is now a function that returns 3 * X.
Therefore when 10 is plugged in, it returns 3 * 10 = 30.
Yes, you are correct, remember that functions can be passed around to and from variables and other functions.
makeMultiplier returns a reference to a function closure, it doesn't execute it yet.
var multiplyBy3 = makeMultiplier(3); Puts the value 3 into the closure function, and returns a reference to it (still doesn't execute it yet).
At this stage we have:
function multiplyBy3(x) {
return 3 * x;
}
console.log(multiplyBy3(10));
multiplyBy3(10) calls the reference to the closure function and passes in 10.
The example you posted is also referred to as "currying". Here's another javascript example of currying.
I do recommend that you get in the habit of using ES6 syntax. Your example rewritten in ES6:
const makeMultiplier = multiplier => x => multiplier * x;
const multiplyBy3 = makeMultiplier(3);
console.log( multiplyBy3(10) ); // 30
or
console.log( makeMultiplier(3)(10) ); //30
Correct. This is what is known as a 'closure' (a function that returns another function that has access to the scope of the parent function.

Modifying variables that are passed by reference in Javascript

I was watching a JavaScript talk, and the tutor said that if we pass a property of an object in a function it will actually change the real value, because we will be passing the variable by reference. Here is the slide:
but when I tried to practice the concept, that wasn't the case. Here is my code:
var obj = {val: 5};
function changeVal(x) {
x = x+5;
return x;
}
console.log(obj.val) // 5
console.log(changeVal(obj.val)) // 10
console.log(obj.val) // 5
I was expecting obj.val to change to 10.
Please tell me what's wrong here, and correct me if I am wrong. Thanks
You are passing not the object, but the primitive type. So when you pass the val of the obj, it is a number and is a primitive type.It copies the val and passes the copy to the object.
If you pass like this, it will work
var obj = {val: 5};
function changeVal( param ) {
param.val = param.val + 5;
return param.val ;
}
console.log(obj.val) // 5
console.log(changeVal(obj)) // 10
console.log(obj.val) // 10
You are not actually passing an object, just passing the value of property(val).
If you will pass obj in changeVal(), then it will actually change the value of the property of passed object.
For that you need to do like:
var obj = {val: 5};
function changeVal(x)
{
x = x+5;
return x;
}
console.log(obj.val); // 5
changeVal(obj); // Need to pass object instead of value of the property's value
console.log(obj.val); // 10
Primitive types (string, integer, boolean, etc...) are immutable, which means if you change one of the values inside a function, the callee (scope which calls your function) will not see the change.
function doSomething(a) {
a = a + 1;
}
var value = 2;
console.log(value); // result: 2
doSomething(value);
console.log(value); // result: 2
Pass-by-reference only works for objects. Like this:
function doSomething(obj) {
obj.attribute = obj.attribute + 1;
}
var myObject = {attribute: 2};
console.log(myObject.attribute); // result: 2
doSomething(myObject);
console.log(myObject.attribute); // result: 3
More reading about Javascript types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Say for instance you have an Iphone . Now lets say a manufacturing company calls you and asks to borrow your Iphone for a reference just so they can design an Iphone that is similar and sell it to customers . Your original Iphone still exists and is never gone , but every now and then the factory needs to use it for a reference , think of your function as the factory that just make a copy of obj.
//Original data
var obj = {val: 5};
Once your function returns something , it technically becomes a value
Example :
return 3; is a value of 3
so
function changeVal(x) {
x = x+5;
return x;
}
is a new value of x which in this case would be x + 5;
x is a copy of whatever you pass into the function .
Hope this helps.

javascript arguments for beginner

Why the following code does not increase the variable a for 1 ?
var a =5;
function abc(y){
y++;
}
abc(a);
//a is 5 not 6 why?
but this does
var a = 5;
function abc(){
a++;
}
abc();
//a is 6
Because primitive values are passed by value in JavaScript.
To get the value to be updated, you could put a on an object and take advantage of the fact that objects are passed by reference (well, mostly, really a copy of the reference is passed, but we won't worry about that):
var obj = { a: 5 };
function abc(o){
o.a++;
}
abc(obj);
it takes the argument, but doesn't return any values.
y is just an argument for this I suggest two ways to do this
var a = 10
function increase(){
a++
}
increase();
var a = 10;
function increase(a){
return a++;
}
a = increase(a);
For a beginner's sake,
In simple words, when you call function by abc(a), 'a' is not passed to function abc but its value is copied to 'y'. (Its called pass by value). Since only 'y' in increased, you dont see an updated value of 'a'.

Optimize custom Object Property in Array with Javascript

Look at the 3 lines of code within this Javascript function. Assume that y will always be a String:
function example(x, y) {
var s = {};
s[y] = x;
return s;
}
Bearing in mind the following:
Without wrapping it further within a function
Without using ;
Is it possible to condense the 3 lines of code into one?
Yes, with a little ugly code:
function example(x, y, s) {
return (s = {})[y] = x, s;
}
The extra parameter s is not passed into the function, it's only there to be declared as a variable, so you don't need the extra line var s;. (If you don't declare it locally it becomes a global variable, which is bad practice.)
The value of the assignment s = {} is what's assigned, so you can make the assignment and then continue using the value in the expression.
The comma operator returns the last value, e.g. (1,2) returns the value 2. That way you can add , s to the expression to make it return s.
Edit:
Another variation is using s as a variable in a for loop, and exit out of the loop:
function example(x, y) {
for(var s = {}; s[y] = x, true;) return s;
}
Is using function cheating? :)
function example(x, y) {
return new function () { this[y] = x; };
}
There is always evil eval:
function example(x, y) {
return eval('({' + y + ':"' + x + '"})');
}
But I still don't see the point in this.

Categories

Resources