Why does one variable change but the other does not? [duplicate] - javascript

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 8 years ago.
While some people are saying that this question has been answered before, its only the answer that has been given before to a different question with much more specifics (ie. asking specifically about call-by-reference / call-by-value, whereas this question does not presuppose knowledge of eiither)
The following code appears to be very confusing. We can logically deduce that the reason why z.id updates after the function is because it is an object. But why? What particular trait or characteristic of javascript is doing this?
function changea(a) {
a = 100; // does not change a
} // no return
function changez(z) {
z.id = 100; // does change z
} // no return
var a = 0; // a is zero
changea(a) // a variable
alert('variable a is equal to ' + a); // why does this stay at zero?
var z = {id: 0};
changez(z);
alert('variable z.id is equal to ' + z.id); // why does this change to 100
see the demo here: http://jsfiddle.net/u0pysgjy/7/

In the first case a is passed by value to the changea function and in the second case z is an object and it is passed by reference to the changez function.Whenever a function gets a variable which is passed to it by value, even if you change the value it will not reflect outside of the function which is the case of a. And if a function gets its parameter which is passed to it by reference if you change the value of its property it will be reflected outside of the function also.
There is a nice explanation here

Related

Shall we declare a variable with zero value in JS for later use? [duplicate]

This question already has answers here:
Redeclaring a javascript variable
(8 answers)
Best place to declare variables in a function [duplicate]
(3 answers)
Closed 4 months ago.
If I am going to use the below example, should I declare a variable (initialize it with zero value in JS) or just use it normally later?
// Currency Converter
var currencyOne = 100; // $
var currencyTwo = 0; // Shall we do this to use as below for printing the result out or no need in JS to declare it with zero value?
var exchangeRate = 19.66; // EGP for Example
function CurrencyConverter(amount, rate) {
return amount * rate;
}
var currencyTwo = CurrencyConverter(currencyOne, exchangeRate); //I mean to use it here without any declaration first
console.log(currencyTwo);
First, you should use let and const, never var.
As to where to declare variables, there is absolutely no point declaring variables earlier than needed, it just makes your code more complicated to understand.

Lifetime of local variables inside an Object Constructor Function [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 months ago.
In this example, taken from the W3Schools JS Tutorial, how is it possible for the variable n to still be used in the next function ?
// Home Made Iterable
function myNumbers() {
let n = 0;
return {
next: function() {
n += 10;
return {value:n, done:false};
}
};
}
// Create Iterable
const n = myNumbers();
n.next(); // Returns 10
n.next(); // Returns 20
n.next(); // Returns 30
I'm coming from a C/C++ background and the lifetime of this variable makes no sense to me. It seems to behave like a global static variable but it should have been deleted when exiting myNumbers(), especially when declared with the let keyword. How can, then, the next method uses it without raising a ReferenceError and keeping its value updated ?
Because of a closure feature of the JavaScript, keep the variable accessible even if the containing function died, whenever there is a child function still need to access it.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Javascript var reference. Could someone explains to me what's the difference between primitive and objs/array? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 8 years ago.
I'd like understand why this difference (I suppose works like Java, so it's stack and heap difference)
var a = 10;
console.log(a);//10
function ChangeVal(){ b=a; b++; }
console.log(a);//10
var a = {name:"MyName"};
console.log(a);//{name:"MyName"}
function ChangeVal(){ b=a; b.name = "YourName"; }
console.log(a);//{name:"YourName"}
Assigning the value of one variable to another always involves copying the value. Thus:
b = a;
assigns the value of variable "a" to the (global! you forgot var!) variable "b". That happens in both your examples.
In the first example, the value of "a" is the number 10. In the second, it's a reference to an object. After
b = a;
in both cases, the variable "b" has the same value — a copy of the same value — as "a".
Because one reference to a particular object is as good as another, in your second example it's perfectly natural that changing the value of the "name" property on that object can be done via the reference in either "a" or "b".

Do Javascript variable assignments work by reference? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?
To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.
Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();

Javascript's objects added to array is pass by value or reference? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript a pass-by-reference or pass-by-value language?
In this file I have an object this.objectA and this.allAs;
this.objectA contains a few attributes.
Everytime I got a new this.objectA, I add it to the array this.allAs.
I always reassign this.objectA when I get a new one.
Later I check my array this.allAs, I found that it correctly stores different this.objectA.
How come this.objectA gets overwritten, the objects inside this.allAs didn't get overwritten? (I expect all those stored objects to to pointing to the same this.objectA, but it didn't) Javascript is pass by value for objects???
You've got to get a lot more specific about what you're doing.
JavaScript passes by reference, but if you're saving local copies anywhere, and copying those values from return statements, then you're not working from reference anymore -- they're no longer pointers to the exact same object, necessarily.
Here's something to demonstrate passing references:
Bob = { name : "Bob", age : 32 };
function giveBobTo (obj, bobject) { obj.bob = bobject; }
Billy = {};
Jim = {};
giveBobTo(Billy, Bob);
giveBobTo(Jim, Bob);
Jim.bob.cars_on_lawn = 8;
Billy.bob.cars_on_lawn; // 8;
Bob.cars_on_lawn; // 8;
console.log( "Billy-Bob equals Jim-Bob equals Bob:",
Billy.bob === Jim.bob === Bob); // true

Categories

Resources