Reassigning objects within function [duplicate] - javascript

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);

Related

What exactly is the `in` keyword in JavaScript? [duplicate]

This question already has answers here:
What does the 'in' keyword in javascript mean?
(3 answers)
Closed 1 year ago.
Ok so I have seen the in keyword in many different codes but i have never understood what they do.
Here is an example
let duck = new Bird() // Bird is a constructor i made. Not important
function in keyword() {
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
}
Sooo, what does it do?
Please explain it to me
The in operator tests if the string on the left side of the operator is a property name in the object on the right side.
let obj = { a: 1 };
console.log("a" in obj); // true
console.log("b" in obj); // false
The in keyword also plays a role in the for ... in loop, which iterates through the properties (the enumerable properties) of an object:
let obj = { a: 1, b: 2 };
for (let x in obj) {
console.log(x);
}
That will log "a" and "b", because those are the enumerable properties of the object.

Why does a const constant assign an object, and a constant can modify the value of the object? [duplicate]

This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
Closed 4 years ago.
enter image description here
Why myVariable can be modified?
const obj = {
a: 'a'
}
const myVariable = obj;
try{
myVariable = { a: 'c' } //The const declaration creates a read-only reference to a value
}catch(e){
console.log(e);
}
myVariable.a = 'b';
console.log(myVariable); //{a: "b"}
This happens because your constant is actually storing a reference to the object. When you're adding to object you're not re-assigning or re-declaring the constant,you're just adding to the "list" that the constant points to.Refer more here : Why can I change value of a constant in javascript

Can the Object literal take values other than key value pair? [duplicate]

This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 5 years ago.
my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function
function a() {
return 'value b';
}
var result = {
'keya': 'valueA',
'keyb': a,
'keyc': function () {
console.log('some value');
}
};
till i read this block of code
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // Will return "test".
my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something
This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.
You would've had to have the key there in ES5 code.

No colon after property name in object declaration, is it valid? [duplicate]

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.

Can you evaluate a property name within a JS object? [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}

Categories