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.
Related
This question already has answers here:
typeof something return object instead of array
(7 answers)
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 2 years ago.
Either we check type of array or object it always print object in JavaScript. Why so?
let arr=[1,3,4];
let obj={1:"44",num:44};
console.log(typeof(arr)) //object
console.log(typeof(obj)) //object
Is there any way to see typeof(array) as array?
Try using the instanceof operator
const arr = [];
console.log(arr instanceof Array); // true
const obj = {};
console.log(obj instanceof Array); // false
Because an array is technically a type of object - just with certain abilities and behaviors, for instance additional methods like Array.prototype.push() and Array.prototype.unshift(). Arrays are regular objects where there is a particular relationship between integer-key-ed properties and the length property.
To determine whether you have an array specifically, you can use Array.isArray().
In JavaScript, almost everything is an Object.
It uses prototype chain to achieve inheritance.
you can just console.log( [] ) and see the prototype part to see that it inherit from objects.
Here is a simple way to make an your own Array.
function MyArray(){
Object.defineProperty(this, 'length', {
value: 0,
enumerable: false,
writable: true,
})
}
MyArray.prototype.push = function(elem){
this[this.length] = elem
this.length++
return this.length
}
MyArray.prototype.isMyArray = function(instance){
return instance instanceof MyArray
}
var arr = new MyArray()
arr.push(1)
arr.push(2)
arr.push(3)
console.log('instance', MyArray.prototype.isMyArray( arr ))
// instance true
console.log('object', typeof arr)
// object object
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 to avoid 'cannot read property of undefined' errors?
(18 answers)
Closed 5 years ago.
I am running into an issue where in I have a object as below
a = {
b: {
c: 10
}
};
Now this is a dynamic object and can be empty on runtime, like this a = {}, I am trying to read c in ES6 shorthand notation like const {b: {c}} = a;. But getting error every time object is empty. Is there a way I can still use this notation for empty object, like get undefined for c in that case.
I know I can do something like (a.b ? a.b.c : undefined), but i just wanted to know shothand way of doing it.
You can do = {} for inner objects:
const a = {
b: {
c: 10
}
};
const f = ({b: {c} = {}}) => console.log(c)
f(a)
f({})
In this case c becomes undefined if the object is empty
you can do
let a = {
b: {
c: 10
}
};
let result = a && a.b && a.b.c;
console.log(result);
it would return the property if it is present, otherwise it would return undefined
You might want a general approach, which isn't really terse for shallow structures but saves you compiling out a static sequence of conditionals.
function dive (obj, pz) {
return pz.reduce((acc, p) => {
return obj && p in acc ? acc[p] : undefined;
}, obj);
}
You can use this with arbirary depth
console.log(dive({a:{b:{c:[10,11,12]}}}, ['a', 'b', 'c', 1]))
c.f. this demo
Give lodash a shot:
lodash.get(a, 'b.c', FALLBACK_DEFAULT_VALUE);
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:
What does ':' (colon) do in JavaScript?
(11 answers)
Closed 7 years ago.
I'm seeing : used in JavaScript a good bit and I can not figure out what exactly what its doing. Is it naming something? For example is the function being named onSave? Example is below.
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom",
properties);
console.log(request);
this.makeRequest(request);enter code here
There are, as far as I know, four uses of : in JavaScript. The ternary operator, switch statements, labels, and part of JavaScript object creation.
// if a, then f is b. Otherwise it is C.
var f = a? b: c;
// This creates an object. You can now look at the object's `name` property.
var obj = {name: val}
switch(foo)
{
case 1:
// this only happens if foo === 1
break;
}
top: // this is a label
for (i = 0; items.length; i++)
for (j = 0; j < tests.length; i++)
if (!tests[j].pass(items[i])){
allPass = false;
break top; // breaks the outermost loop.
}
You'll see this also in JSON, which is JavaScript object notation:
{
"foo": 1,
"bar": [2,3],
"baz": {
"bat": 4
}
}
That is an object where
obj.foo === 1
obj.bar[0] === 2
obj.bar[1] === 3
obj.baz.bat === 4
The most common use, and certainly what most people expect when they see the above code, is that an object is being created with a property "onStart" which is a function defined as above.
: is used as an = in an object - separating the object property from its value. Objects can also have functions as values. So what you're seeing is:
var obj = {
onSave: function(){}
}
could also be obj.onSave = function(){}