var a = 3;
var b = 5;
example(a, b);
function example(b, a) {
var result = b - a;
alert(result);
}
My question is looking at this I though the result would be 2 but its negative 2 can someone explain why please?
You've inverted the arguments in your function definition.
While you are calling (a,b), you are receiving (b,a). This means that you are passing:
example(3,5)
and receiving:
(b=3, a=5)
You then return:
(b-a) or (3-5)
which is -2.
The actual names of the parameters in the function don't matter. You're getting confused because wherever you found the example- they cleverly reversed the order of b and a. However the names in the parameter are just used in the function scope and don't affect variables of the same name outside of it. For example:
var a = 3;
var b = 5;
example(a, b);
function example(bacon, eggs) {
var result = bacon - eggs;
alert(result);
}
Would also return -2 because the first parameter we pass through to example is a (3) and the second is b (5) and 3-5 = -2. Doesn't matter what the name of the parameters in example actually are named- its important to keep this in mind.
There is no problem with your code. The problem is with your lecture of the code. The result is in fact, -2. Debug your code in Chrome Debugger or similar
var a = 3; // a equals 3
var b = 5; // b equals 5
example(a, b); // Replacing variables this is the same as example(3,5)
// Changing variables names so you don't get mixed up
function example(c, d) {
// Since you called example(3,5) then c = 3 and d = 5
var result = c - d; // This results in -2
alert(result);
}
Don't be confused with the variable names because in js, it works by the order of your function argument not by variable name of functions. To get what you want as output i.e 2, try like this.
example(b = 5, a = 3);
function example(b, a) {
var result = b - a;
alert(result);
}
If you've any confusion go to http://www.pythontutor.com/javascript.html and see what is happening under the hood.
Related
I know typeof(my_number) is a primitive number, which makes functions receive a copy of my_number instead of my_number itself, which does't make it's value change at all. This is working as expected (I also know var is deprecated, that's probably not my issue here whatever).
What i don't know is why my_object_number isn't changed. I know i could have returned number + 1 and associated it to my_object_number, but I'm intentionally trying to code something similar to what a void(int*)function would have done in C.
var my_number = 3;
var my_object_number = new Number(3);
var my_object ={
number: 3
}
function increments_number(numero){
numero = numero + 1;
}
function increments_object(number){
number.number++;
}
increments_number(my_number);
increments_number(my_object_number);
increments_object(my_object);
console.log("primitive number = 3, which increased by a function = " + my_number);
console.log("object Number = 3 , which increased by a function = " + my_object_number)
console.log("prop number of a hardcoded object = 3, which increased by a function = " + my_object.number)
the code above prints.
primitive number = 3, which increased by a function = 3
object Number = 3 , which increased by a function = 3
prop number of a hardcoded object = 3, which increased by a function = 4
I'm not sure why my_object_number isn't incremented
I know typeof(my_number) is a primitive number, which makes functions receive a copy of my_number instead of my_number itself, which does't make it's value change at all.
There is no difference between primitives and objects in JavaScript in this respect. Actually, you can forget there’s a difference at all, for the most part – in strict mode, they’ll either behave the same in every situation or throw an error. Function calls aren’t related either. Instead, the difference is between mutating a value and reassigning something that contains a value, like a variable or a property, to contain a different value.
var a = {};
var b = a;
b = {foo: 'bar'};
console.log(a); // didn’t change, because assignment to `b` changes the variable `b`,
// not the value `{}`
var d = 5;
var e = d;
e = 6;
console.log(d); // didn’t change, because assignment to `e` changes the variable `e`,
// not the value `5`
'use strict';
var a = {};
var b = a;
b.foo = 'bar';
console.log(a); // the value {} changed; all variables stayed the same
var d = 5;
var e = d;
e.foo = 'bar'; // throws an error; a primitive is indistinguishable from…
var f = Object.freeze({});
var g = f;
g.foo = 'bar'; // … an immutable object.
++, like all math operators in JavaScript, is an operation on something that contains a value – it doesn’t mutate a value. ++x acts like x = x + 1.
What is the difference of accessing variables inside the function by as argument and without argument?
var a = 1;
var b = 2;
function x() {
var c = a + b;
console.log(c)
}
function y(a, b) {
var c = a + b;
console.log(c)
}
The key difference here is that y does not use anything other than the arguments provided to the function. As soon as you see the function call - say y(1, 2) - you know exactly what will happen. (Assuming at least that you are reasonably familiar with the function and what it does - but even if you aren't familiar with it, hopefully it has a name that makes it sufficiently clear.)
The contrast with x is that it reads from external (here global) variables a and b. In other words, it depends on inputs that are not explicitly provided to the function. This makes it much harder to understand what a call to x() will do, because it depends on the value of a and b - which may be assigned quite some distance away in the program. Indeed, perhaps their values can be changed, in different ways, and by other functions - in which case it is impossible to know exactly what x() will do without carefully studying the entirety of the program up until that call. Again, contrast that with y where we need only look at the call site, and nothing else.
While, in some practical situations, it is hard to avoid some sort of "global state", avoiding it as much as possible, and trying to keep the information that a function needs local to it - as in y - is unquestionably better design. It makes the code much easier to understand, and therefore much less likely to have bugs in it.
Within the scope of your second function, a and b refer to the arguments, not the global variables.
var a = 1
var b = 2
function exampleOne () {
console.log("example 1: ", a, b)
}
function exampleTwo (a, b) {
console.log("example 2: ", a, b)
}
exampleOne()
exampleTwo(3, 4)
exampleTwo()
The 3 cases have different purposes, some non exhaustive:
Inside a function:
Only if the variable have to be unloaded after the function call, unless it be returned
function helloworld() {
const words = ['hello', 'world'];
return words.join(' ');
}
As argument:
Every time you want to use an external value which change the result
function hello(name) {
return 'Hello ' + name;
}
From closure:
In others cases:
// inside a lambda
function upperThan(array, n) {
return array.filter(item => item > n);
}
// use a constant
const HELLO = 'Hi';
function sayHello(name) {
return HELLO + ' ' + name;
}
Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number).
If you modify variables inside the function that is passed as argument then it does not change the value of orignal variable(Pass by value).
var a = 1;
var b = 2;
function x() {
var c = a + b;
a = c;
console.log(c)
}
function y(a, b) {
var c = a + b;
var a = c;
console.log(c)
}
y(a, b)
console.log(a)
console.log(b)
x()
console.log(a)
console.log(b)
Sometimes in the internet I see a syntax that is strange to me. Something like:
console.log = console.error = console.info = console.debug = console.warn = console.trace = function() {}
How does this "equal" sequence work?
Thanks.
An assignment operator assigns a value to its left operand based on the value of its right operand.
Consider:
a = b = c = d = 5;
The expression is resolved right to left so:
d = 5 and c = d (which is 5), b = c (5) and so on.
In your example those console methods are all being (re)defined as an empty function.
See: MDN: Assignment Operators for more info.
With assignments, the operations are resolved from right to left. So the right most value will be populated into all the preceding variables.
What you describe can be easily explained by analogy using a simpler example:
// Normal variable assignment
var a, b;
a = 15;
b = 15;
console.log("a: "+a+" , b: "+b);
// Assing the same value to two variables
var c, d;
c = d = 15;
console.log("c: "+c+" , d: "+d);
// Assign the same value to two variables and make it a function
var e, f;
e = f = function(){ console.log("Hi!"); };
// Call both of the variables' functions
e(); f();
Starting from variables a and b, you then go to c and d that are given the same value. The takeaway here is that you can assign the same value to two variables and the expression will be evaluated from right to left, so in effect it's like assigning the two variables' values separately. However, this does not mean that chaning one will change the other as well.
Finally, see what happens with e and f. These are assigned a function instead of a value, so you can then call them as if they were functions.
Short version: Expression gets resolved from right to left. The assignment is by value, not by reference, meaning that changing one of the variables' value will not affect the others. Finally, if you assign a function to your variables, you can then use their names to call the function that is their value.
function swap(x,y){
var t=x;
x=y;
y=t;
}
This won't work. when you swap(a,b), variable a and b get copied into the function and whatever happens in that function doesn't affect the real value of a and b. I want something like this:
(function(){
a=1;
b=2;
function swap(){//something}
swap(a,b);
console.log(a) //2
console.log(b) //1
})()
How to do this?
If you are using the latest version of JavaScript (ES2015), then you can use the new language feature called "destructuring". You don't need a function. It looks like this:
let a = 1;
let b = 2;
// swap!
[b, a] = [a, b];
If you want a function, you can do it like this:
function swap(a, b) {
return [b, a]
}
[a, b] = swap(a, b);
Looking at this code, I kind of prefer the function, though it is a bit superfluous. I like how expressive it is. You aren't left puzzling over what the code does.
You can't. Arguments are passed by value, even in the case of objects. It's just that the value passed for them is a reference to the object.
Basically this means that any arguments you receive have no actual connection to the original variables you passed in except that they may share a reference.
Imagine you've written a and b on a piece of paper. In JS, the only way to share those values with a function is to copy them on to a different piece of paper and hand it to the function. So even if that function scratches out a on the new piece of paper and replaces it with b, it doesn't change what you have written on the original piece of paper.
In short, it is not possible to change the value of a variable which was used as an argument for a function.
As mentioned in the answers above, Arguments are only passed by value. If you really need to achieve the swap, you can use the 2 variables algorithm:
var a = 10, b = 20;
a = a + b;
b = a - b;
a = a - b;
console.log (a+" "+b); // 20 10
you can set a variable outside the scope of the function so you can use it inside the function, this is something you can do:
<head>
<script>var x=0, y=1;</script>
</head>
<script>
function swap()
{
var t = x;
x = y;
y = t;
}
</script>
or even this works
<script>
var x=0; y=1;
function swap(id1, id2)
{
var t = x;
x = y;
y = t;
}
console.log(x+" "+y);
</script>
I used this quite a lot and works fine. the x and y can be taken from any where and will work inside a function no problem.
you can also do
function(id1, id2)
{
x=document.getElementById(id1);
y=document.getElementById(id2);
var t = x.value;
x.value = y.value;
y.value = t;
}
function swap(value) {
value.first = value.first + value.second;
value.second = value.first - value.second;
value.first = value.first - value.second;
}
// declared an object named value which has two keys - first and second corresponding to the first and the second values respectively
var value = {
first: 1,
second: 2
}
console.log(value.first, value.second) // prints 1 2
swap(value);
console.log(value.first, value.second); // prints 2 1
Looking at var a=b=1; , I already know that both a and b has the same value.
But my question is :
Does the a gets its value from 1 or from b ?
I made a small test :
/*1*/ (function (){
/*2*/ var j = window.j = function (){ alert('3');};
/*3*/ window.j2 = j;
/*4*/ })();
/*5*/
/*6*/ window.j(); //3
/*7*/ window.j=null;
/*8*/ window.j2();//3
As you can see line #8 yields 3 so I persume that a is not having the value of b but the value of 1.
Am I right ?
visualize :
(function (){
var j = window.j = function (){ alert('3');};
|
| ^ ^
| | | //which one ?
+----------+--------+
})();
Assignment in javascript works from right to left. So you are getting your value from window.j. Re-setting window.j will not affect the result because Javascript variables always passes by value, exception is array or object.
Example of passing value by ref in JS object:
var obj = { x: 2 };
var anotherObj = obj;
anotherObj.x++;
alert(obj.x); //3
You can find more information here.
More useful examples available in this answer.
The "=" operator associates to the right so "a=b=1" is equivalent to "a=(b=1)". So 1 is assigned to b first with a result of 1, which is then assigned to a.
Assigment in JavaScript is right associative, so you are correct.
In
a = b = c;
a takes the value of b at time of assignment, so if b is later assigned to something else, a retains its value (which happens to be the same as c)
You are right technically but are confused with reference / value assignment i think. Technically a does get it's value from b but there is no reference to b therefore if your were to do b = null it would have no affect to a, which is what you're seeing in your example.
a inherits the value of b without relying on b still existing or having that same value later on when you refer back to a. The assignment happens right to left so actually reads a = ( b = 1)