This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
I've noticed things like this work:
let x = { a: 1 };
function reassignProperty(obj, key, newValue) {
obj[key] = newValue;
}
reassignProperty(x, "a", "hello");
console.log(x.a); //prints hello
But this doesn't:
function reassignObject(obj) {
obj = { a: "some new value" };
}
reassignObject(x);
console.log(x.a); //still prints hello
It seems you can reassign properties of an object (pointers within an object), even if the values are reference types themselves. i.e. we could do things like reassignProperty(x, "a", { inner: 55 }), and it will still be the same outside the function scope. But reassigning the reference to the object itself doesn't?
I've seen people argue javascript passes variables into functions by value, but not by reference. Why then does it seem to able to reassign the properties inside the object, and have access to the changes outside the function scope? This doesn't seem to me to be strictly "pass by value"
In the second case use dot notation instead of object literal
let x = {
a: 1
};
function reassignObject(obj) {
console.log("Passed from function call ", obj);
if (obj.hasOwnProperty('a')) {
obj.a = "some new value"
}
console.log("After reassinging value ", obj)
}
reassignObject(x);
console.log(x.a);
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:
var x = { a (b) {} };
console.log(x);
x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b".
How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand).
With ES6:
const obj = {
a(b) {
// Shorthand method
// `this` context is `obj`
},
c
};
is equal to
var obj = {
a: function a(b) {
},
c: c
};
In JavaScript, when you write:
var x = { a (b) {} };
It will consider it as:
var x = {
a: function (b) {
}
}
For example, you can check this and it will clear your doubt:
var x = { a (b) { console.info('function called') } };
x.a();
This will call the function which is assigned to property a of object x.
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I'm curious about the following two methods of declaring functions within a variable in Javascript. What's the difference between the two function declarations below? Both seem to work. Are there any drawbacks to using one over the other? They seem to be constructed slightly differently when looking at the debugger.
In addition, I'm fairly certain the first method is called 'object literal notation'. Is there a formal name for the second method?
var myVar = {
testProperty: 'testProperty',
// Object literal notation?
testFunc: function()
{
console.log('testFunc called');
},
// What's this called? 'Named function declaration'?
testFunc2()
{
console.log('testFunc2 called');
}
}
// Both work...
myVar.testFunc();
myVar.testFunc2();
There are multiple ways to define properties (PropertyDefinition) in an object initializer (ObjectLiteral):
A "simple" PropertyDefinition
PropertyName[?Yield] : AssignmentExpression[In, ?Yield]
For example:
var obj = {a: 1};
obj.a; // 1
Method definitions
This includes getters and setters, added by ECMAScript 5
get PropertyName[?Yield] ( ) { FunctionBody }
set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }
For example:
var obj = {n: 0, get a() { return ++obj.n; }};
obj.a; // 1
obj.a; // 2
And also methods and generator methods, added by ECMAScript 6
PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }
* PropertyName[?Yield] ( StrictFormalParameters[?Yield] ) { GeneratorBody }
For example:
var obj = {a(n) { return 2*n; }};
obj.a(1); // 2
obj.a(2); // 4
PropertyDefinition using computed property names, added by ECMAScript 6
[ AssignmentExpression[In, ?Yield] ] : AssignmentExpression[In, ?Yield]
For example:
var prop = "a",
obj = {[prop]: 1};
obj.a; // 1
"Shorthand" PropertyDefinition, added by ES6
IdentifierReference
For example:
var a = 1,
obj = {a};
obj.a; // 1
They have different syntax and provide different functionalities, but the result is always the creation of a property in the resulting object. In your case, a method definition is basically the same as a "simple" PropertyDefinition where the AssignmentExpression is a function expression. However, with the later you can specify a custom name to the function.
Also see
ECMAScript 5 - Object Initialiser
ECMAScript 6 - Object Initialiser
MDN - Object initializer
if you declare a function inside an object, that function is called the method of the object, but there are still called function, you should probably use the first method rather than using the second one
This question already exists:
What is `var { comma, separated, list } = name;` in JavaScript? [duplicate]
Closed 7 years ago.
Does anyone know what this syntax means in JavaScript?
var { variable } = value;
I found it in some code examples and I've never seen this before. Is this JavaScript 6? I tried googling variable syntax and es6 but no examples came up with this syntax.
Here's the full example:
var { Tab } = require('app-dev-kit/tab');
var tab = Tab({ properties });
Weirdest part is if I drop parens from { Tab } then it doesn't work (it says Tab is not a function in that case):
var Tab = require('app-dev-kit/tab');
var tab = Tab({ properties });
This doesn't work: Error: Tab is not a function.
This is an ES6 feature known as destructuring assignment that works for arrays (array destructuring) and objects (object destructuring)
The destructuring assignment syntax is a JavaScript expression that
makes it possible to extract data from arrays or objects using a
syntax that mirrors the construction of array and object literals.
Say you have a function
function foo() {
return { bar: 1, baz: 2 };
}
And you want to assign the properties of that functions returned value to local variables. Traditionally, you would do something like
var f = foo();
var bar = f.bar;
var baz = f.baz;
console.log(bar); // 1
console.log(baz); // 2
With destructuring assignment, you can do this
var {bar, baz} = foo();
console.log(bar); // 1
console.log(baz); // 2
This question already has answers here:
Why isn't this object being passed by reference when assigning something else to it?
(4 answers)
Closed 8 years ago.
In the below code we are passing an object. So, according to javascript we are passing a reference and manipulating.
var a = new Number(10);
x(a);
alert(a);
function x(n) {
n = n + 2;
}
But 10 is alerted instead of 12. Why?
n is local to x and first it is set to the same reference as global a. The right hand side n + 2 is then evaluated to be a number (primitive).
The left hand side of the assignment, n, is never evaluated, it is just an identifier there. So our local variable is now set to the primitive value of the right hand side. The value referenced by a is never actually modified. See
var a = new Number(10);
x(a);
alert(a); // 10
function x(n) {
alert(typeof n); // object
n = n + 2;
alert(typeof n); // number
}
When you compute
n + 2
this results in a new "native number" even if n is indeed a Number object instance.
Assigning to n then just changes what the local variable n is referencing and doesn't change the Number object instance. You can see that with
n = new Number(10);
console.log(typeof n); // ---> "object"
console.log(n + 2); // ---> 12
console.log(typeof (n+2)); // ---> "number"
n = n + 2;
console.log(typeof n); // ---> "number"
In Javascript (or Python or Lisp) there's no way to pass the "address" of a variable so that the called function mutates it. The only thing you can do is passing a setter function... for example:
function foo(setter) {
setter(42);
}
funciton bar() {
var x = 12;
foo(function(newx){x = newx;});
console.log(x); // ---> 42
}
Let me try to answer it with examples:
function modify(obj) {
// modifying the object itself
// though the object was passed as reference
// it behaves as pass by value
obj = {c:3};
}
var a = {b:2}
modify(a);
console.log(a)
// Object {b: 2}
function increment(obj) {
// modifying the value of an attribute
// working on the same reference
obj.b = obj.b + 1;
}
var a = {b:2}
increment(a);
console.log(a)
// Object {b: 3}
function augument(obj) {
// augument an attribute
// working on the same reference
obj.c = 3;
}
var a = {b:2}
augument(a);
console.log(a)
// Object {b: 2, c: 3}
Please refer the JSFiddle for working demo.
The answer is rather simple: because ECMAScript is pass-by-value and not pass-by-reference, and your code proves that. (More precisely, it is call-by-sharing, which is a specific kind of pass-by-value.)
See Is JavaScript a pass-by-reference or pass-by-value language? for some additional insight.
ECMAScript uses pass-by-value, or more precisely, a special case of pass-by-value where the value being passed is always a pointer. This special case is also sometimes known as call-by-sharing, call-by-object-sharing or call-by-object.
It's the same convention that is used by Java (for objects), C# (by default for reference types), Smalltalk, Python, Ruby and more or less every object-oriented language ever created.
Note: some types (e.g.) Numbers are actually passed directly by value and not with an intermediary pointer. However, since those are immutable, there is no observable behavioral difference between pass-by-value and call-by-object-sharing in this case, so you can greatly simplify your mental model by simply treating everything as call-by-object-sharing. Just interpret these special cases as internal compiler optimizations that you don't need to worry about.
Here's a simple example you can run to determine the argument passing convention of ECMAScript (or any other language, after you translate it):
function isEcmascriptPassByValue(foo) {
foo.push('More precisely, it is call-by-object-sharing!');
foo = 'No, ECMAScript is pass-by-reference.';
return;
}
var bar = ['Yes, of course, ECMAScript *is* pass-by-value!'];
isEcmascriptPassByValue(bar);
console.log(bar);
// Yes, of course, ECMAScript *is* pass-by-value!,
// More precisely, it is call-by-object-sharing!
If you are familiar with C#, it is a very good way to understand the differences between pass-by-value and pass-by-reference for value types and reference types, because C# supports all 4 combinations: pass-by-value for value types ("traditional pass-by-value"), pass-by-value for reference types (call-by-sharing, call-by-object, call-by-object-sharing as in ECMAScript), pass-by-reference for reference types, and pass-by-reference for value types.
(Actually, even if you don't know C#, this isn't too hard to follow.)
struct MutableCell
{
public string value;
}
class Program
{
static void IsCSharpPassByValue(string[] foo, MutableCell bar, ref string baz, ref MutableCell qux)
{
foo[0] = "More precisely, for reference types it is call-by-object-sharing, which is a special case of pass-by-value.";
foo = new string[] { "C# is not pass-by-reference." };
bar.value = "For value types, it is *not* call-by-sharing.";
bar = new MutableCell { value = "And also not pass-by-reference." };
baz = "It also supports pass-by-reference if explicitly requested.";
qux = new MutableCell { value = "Pass-by-reference is supported for value types as well." };
}
static void Main(string[] args)
{
var quux = new string[] { "Yes, of course, C# *is* pass-by-value!" };
var corge = new MutableCell { value = "For value types it is pure pass-by-value." };
var grault = "This string will vanish because of pass-by-reference.";
var garply = new MutableCell { value = "This string will vanish because of pass-by-reference." };
IsCSharpPassByValue(quux, corge, ref grault, ref garply);
Console.WriteLine(quux[0]);
// More precisely, for reference types it is call-by-object-sharing, which is a special case of pass-by-value.
Console.WriteLine(corge.value);
// For value types it is pure pass-by-value.
Console.WriteLine(grault);
// It also supports pass-by-reference if explicitly requested.
Console.WriteLine(garply.value);
// Pass-by-reference is supported for value types as well.
}
}
var a = new Number(10);
x(a);
alert(a);
function x(n) {
n = n + 2; // NOT VALID as this would essentially mean 10 = 10 + 2 since you are passing the 'value' of a and not 'a' itself
}
You need to write the following in order to get it working
var a = new Number(10);
x(a);
alert(a);
function x(n) {
a = n + 2; // reassign value of 'a' equal to the value passed into the function plus 2
}
JavaScript parameter passing works similar to that of Java. Single values are passed by value, but object attributes are passed by reference via their pointer values. A value itself will not be modified in a function, but attributes of an object would be modified.
Consider the following code:
function doThis(param1, param2) {
param1++;
if(param2 && param2.value) {
param2.value++;
}
}
var initialValue = 2;
var initialObject = {value: 2};
doThis(initialValue, initialObject);
alert(initialValue); //2
alert(initialObject.value); //3
http://jsfiddle.net/bfm01b4x/