Javascript, SOAP, Execute, Variable and function call - javascript

Is this
var result = XrmServiceToolkit.Soap.Execute(setStateRequest);
just storing the function into the variable,
executing and storing the return value into the variable,
or doing both?
Unfortunately I wasn't able to find something useful in the internet. Looking at http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions
it looks like the function is executed but i am not sure.
I also tested it with a normal Javascript inside the chrome browser and got this result:
> function test(a){
console.log(a);
};
undefined
Calling the function normal
> test("asd");
asd
With a variable declaration
> var x = test("asd");
asd
But it looks like the variable does not contain any information
> console.log(x);
undefined
> x
undefined
Now I am completely confused. Why is the function called as variable when it is never stored? I am new to Javascript and need to understand what this is exactly doing.

It is storing the return value of the function into a variable.
The reason your test function is not working is because you don't return a value in test.
function test(num) {
return num * 2;
}
var doubled = test(2);
// doubled now contains 4
var doubleVariable = test;
// doubleVariable is now the same as test
doubleVariable(2)
// returns 4
This article may clarify things a bit more

Related

Is This Callback Referencing a Dereferenced Closure?

I have been dealing with issues in multiple pieces of code but it seems to boil down to what I’m showing in this demo. I think it is related to the ’s dereferencing of a closure:
function get_5(callback) {
var result = 5;
callback(result);
}
function get_self(x) {
return x;
}
get_5(console.log);
// 5
console.log(get_self(5));
// 5
In the first result, the first function ran as expected, sending its hidden variable into the input of the console.log function.
The second result also makes sense, as it really just proves the second function works: it takes what was fed in and returns it.
But things get strange when I try to combine the two functions:
var a = get_5(get_self);
console.log(a);
// Undefined!
This third result is undefined, strangely enough, and I am not sure why. Is the closure being dereferenced, maybe to the “sneakiness” of the get_self function? How can I fix this? As a bonus, is there a way to eliminate the get_self function entirely and be able to directly read the variable result, which isn’t modified, without specifying any particular callback?
get_5 has no return statement. It doesn't matter what you pass to get_5, it will always return undefined.
Perl will return the result of evaluating the last statement in a sub, but JavaScript will not.
If you want get_5 to return the result of calling the callback you pass to it, then you have to say so explicitly:
function get_5(callback) {
var result = 5;
return callback(result);
}

trying to understand the concept of being unable to mutate strings/numbers in javascript

In Javascript, you can reassign a variable like:
var x = 10;
x+=10;
console.log(x);
//prints 20 to the console
But if I take another example of a seemingly similar activity I get an unexpected result:
var originalVar = 1;
changeMyVar(originalVar);
function changeMyVar(myVar) {
myVar += 1000;
return myVar;
}
console.log(originalVar);
//prints 1 to the console
I see this as one in the same. I am passing my variable as an argument into a function. I'm reassigning the value within that function. And then I'm returning and printing that variable. Where is the mutation?
Primitives as function parameters are passed by value in javascript. Therefore myVar in changeMyVar function is not reference to originalVar but new variable with value of originalVar.
I hope it will solve your problem :
According to your question
Code :
var originalVar = 1;
changeMyVar(originalVar);
function changeMyVar(myVar) {
myVar += 1000;
return myVar;
}
console.log(originalVar);
Output :
1 // prints 1 to the console
Explanation :
If it was pure pass by reference, then everything would have changed. originalVar would be 1001.
In practical terms, this means that if you change the parameter itself (as with originalVar), that won't affect the item that was fed into the parameter. But if you change the INTERNALS of the parameter, that will propagate back up (as with objects properties).
The operator += reasssigns the variable. It does not reassign the number that the variable represents.
Let's say 'originalVar' is a box with one ball in it. Then calling changeMyVar(originalVar) calls the changeMyVar function with myVar equal to the value of originalVar, so myVar is a box with 1 ball in it. The line myVar += 1000 adds 1000 balls to the myVar box. It does not change the concept of 1 ball into the concept of 1001 balls. So now originalVar still equals 1, but myVar equals 1001.

assigning a function variable to another function

First up - n00b with Javascript here and I did try to search for something which represented similar concept as the one I have below but I couldn't find anything useful..sorry if my search skills are rather limited.
I'm going through the Eloquent Javascript and under the "Nested Scopes" section, there was some code showing how the scope of functions works; the following is the code (And a bit that I've added to experiment)
var landscape = function() {
var result = "";
var flat = function(size) {
for (var count = 0; count < size; count++)
result += "_";
};
var mountain = function(size) {
result += "/";
for (var count = 0; count < size; count++)
result += "'";
result += "\\";
};
// my nonsensical code -- begin
var myfunc = function(text) {
console.log("this is only a block of text -", text);
};
// my non sensical code -- end
flat(3);
mountain(4);
flat(6);
mountain(1);
flat(1);
// this is what I was trying to do and see what happens here..
mountain = myfunc("meh");
// end of my nonsense
return result;
};
console.log(landscape());
I understand that if within my function (myfunc) if I assign a value to result then when result is returned in the last line, it will get overwritten with whatever value is being assigned to it in myfunc
My question here I guess is what does it really mean to be able to assign one function variable to another (mountain = myfunc) and is there a real world usage to such a "feature"? If not, why does Javascript allow such an assignment?
This line:
mountain = myfunc("meh");
Assigns the return value of myfunc to mountain.
Since myfunc only logs something, it returns undefined (which is the default return value when no explicit return value is given).
Therefore, at the end of the example you've given mountain is undefined.
This is very useful, however, when you have functions that return other values. For example:
function add(a, b) {
return a + b;
}
function multiply(c, d) {
return c * d;
}
function divide(e, f) {
return e/f;
}
var multipliedThing = multiply(add(1,2), add(3,4));
var anotherMultipliedThing = multiply(add(5,6), add(7,8))
var result = divide(multiplied, anotherMultipliedThing);
// => 0.12727272727272726
The above is a bit contrived, but it shows a use case for assigning the return values of functions to variables.
The core concept of functions is general is to accept some value and return a value. With JavaScript (and many other languages) you get the "benefit" (I put that in quotes because it's debatable in some circumstances) of functions giving side effects (that is, mutating other values outside of the function). Therefore, if a function's purpose is for side effects, you might not need to return anything.
Look up "functional programming" if you're interested in a little bit of theory.
Here:
mountain = myfunc("meh");
you are calling myfunc with "meh" as parameter and assign its return value to mountain. The function logs a text and finishes. Since it does not have a return statement, it returns undefined and as a result, mountain will hold undefined at the end of the day. If, instead of that, you are doing this:
mountain = myfunc;
then the function named myfunc will be assigned to mountain, so, if you call mountain after this operation, it will execute myfunc.
My question here I guess is what does it really mean to be able to
assign one function variable to another (mountain = myfunc) and is
there a real world usage to such a "feature"? If not, why does
Javascript allow such an assignment?
The meaning of that is that you are able to store functions inside variables. It is a very useful feature, which you are using yourself when you define landscape, myfunc and mountain initially. Basically, a function can have properties, so there is literally an arsenal of possibilities you can do with a variable holding a function.

ID Element return when giving as parameter

I am making a website for school and we where working with function. Now i got a litle "problem"
i am using jquery to change the DOM and made a function where you can choose which location you are adding the element to.
Something like this:
function functioname(parameter){
console.log(parameter);
}
when i call this function like this:
functioname("#id");
i will return "#id";
But if i call it like this:
functioname (id);
I get return with the whole div and his children. How can this happen?
And why works this only with divs.
It isn't really a problem i was just wondering how this works.
Thanks in advance if somebody could explain what is happening here.
The window.id will find a DOM element whose id it matches. For example, window.mydiv will find:
<div id="mydiv"></div>
However, this not a recommended practice.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
In the first function you are passing the string and in the second example you are passing the window object. Same as we pass an object with "this"
<div onclick= " functionname(this); "> </div>
here we get the complete object inside the function.
In first line of code "#id" you are passing the string. it's return the string also as you says.
in second you pass object id that you have earlier in your code. This is maybe why you got the different result.
Let's take a look at the window object. The window is pretty cool in that it allows you to declare global variables from anywhere on the fly. Take the following code for example
//the following three lines of code do the same thing
//create a global variable and store a value in it
window.a = 1;
window["b"] = 2;
var c = 3; //this one is most used though
function g() {
//the following three lines of code do not do the same thing
window.d = 4; //global
window["e"] = 5; //global
var f = 6; //local
}
g();
console.log(a); //prints 1
console.log(b); //prints 2
console.log(c); //prints 3
console.log(d); //prints 4
console.log(e); //prints 5
try {
console.log(f); //ERROR
} catch (err) {
console.log(err);
}
console.log(window.a); //prints 1
console.log(window.b); //prints 2
console.log(window.c); //prints undefined
console.log(window.d); //prints 4
console.log(window.e); //prints 5
console.log(window.f); //prints undefined
console.log(window["a"]); //prints 1
console.log(window["b"]); //prints 2
console.log(window["c"]); //prints undefined
console.log(window["d"]); //prints 4
console.log(window["e"]); //prints 5
console.log(window["f"]); //prints undefined
It is important to know that obj.prop === obj["prop"] is always true in JavaScript. That is why the last two sets of tests have the same results. Also important is prop === window.prop unless you declared prop using var prop;. This is because JavaScript secretly uses the special keyword using on the window variable at all times unless otherwise specified.
All browsers make DOM elements available via id using document.getElementByID but some browsers are nice enough to set up some variables for you so you don't have to write all that code. Imagine that a browser runs this script before any of your scripts do
(function(context) {
var tags = document.getElementsByTagName("*");
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.id) {
context[tag.id] = tag;
}
}
}(window));
Which fills the window variable / global scope with tags that have ids.
Here are a bunch of examples. http://jsfiddle.net/Lk345zez/

NewBee on NodeJs or PhantomJS: Function names on Javascript

I am just learning NodeJS and/or PhantonJS.
As a programmer with a lot of C experience, I do not like the way NodeJs code is written and find it a bit messy/unreadable. (Sorry if I ruffled any feathers)
In spirit of cleaning up the code, I was trying to do this and found a block.
In C or C++, we should be able to pass a function by name but in NodeJS/PhantomJS it does not seem to work.
Am I doing somthing wrong ?
Can someone explain to me how this is looked at by the Javascript interpreter ?
var page = require('webpage').create();
var printS = function (s) {
console.log(s);
phantom.exit();
}
/* This works */
page.open('http://net.tutsplus.com', function (s) {
console.log(s);
phantom.exit();
});
/* This does not work
page.open('http://net.tutsplus.com', printS(status));
*/
/*But this works
page.open('http://net.tutsplus.com', function (s) { printS(s);} );
*/
page.open('http://net.tutsplus.com', printS(status));
fails because you're not passing the function but rather the result of invoking the function on status. If you want to pass the function, you'd do it this way
page.open('http://net.tutsplus.com', printS);
I thought it might be helpful to have a more extensive explanation. Let's start simple:
In JavaScript, we have values and variables. Variables are containers for values. Almost everywhere where we can use values, we can use variables.
In JavaScript source code, we express values through literals, e.g. the number literal 42. We can directly pass that value to a function:
f(42);
Additionally, instead of passing the value directly, we can pass a variable to the function:
var v = 42;
f(v);
That is, we can substitute values with variables.
Lets consider
var printS = function() { ... };
This clearly is a variable whose value is a function. If we'd directly pass that value to a function (i.e. we pass a function to a function), it would look like:
f(function() { ... }); // similar to f(42)
That's exactly what you have in your first case:
page.open('http://net.tutsplus.com', function (s) {
// ...
});
Since we know that we can replace values with variables, we can just substitute function() { ... } with printS:
var printS = function() { ... }; // similar to var v = 42;
f(printS); // similar to f(v)
So your example would become
page.open('http://net.tutsplus.com', printS);
What is wrong with
page.open('http://net.tutsplus.com', printS(status));
then?
Notice that you added additional characters after printS, namely (status). They don't appear in the your first example where you inlined the function:
page.open('http://net.tutsplus.com', function (s) {
// ...
});
There is no (status) here. Hence these two constructs cannot be not equivalent.
page.open accepts a function value as second argument, but printS(status) doesn't evaluate to the function printS, it calls the function printS and passes the return value to page.open.
Why does
page.open('http://net.tutsplus.com', function (s) { printS(s);} );
work?
Lets remove the content and the argument of the function, and it becomes:
page.open('http://net.tutsplus.com', function () { ... } );
That looks exactly like one of the examples above. function () { ... }, is a function literal, so to speak. It creates a function value. There are no (...) after it which would call the function.
This doesn't work as you hope because page.open wants a function as its second argument... this callback pattern is very common in JavaScript. In your doesn't-work example, printS is being called with status as its argument, and it returns undefined. As undefined is not a function, it doesn't behave as you wish.
In your browser console or the node repl:
> printS = function (s) { console.log(s); };
function (s) { console.log(s); }
> typeof printS('hi');
hi
"undefined"
> typeof function (s) { printS(s); };
"function"
Another thing to know about JavaScript is that its dynamic typing and fairly generous type coercion can result in baffling behavior with no helpful errors to point you towards the root cause of your problem. A debugger or copious use of console.log() is frequently helpful in understanding these sort of problems.

Categories