How does instanceof operator actually work in JS? [duplicate] - javascript

This question already has answers here:
Why is 4 not an instance of Number?
(5 answers)
Closed 8 months ago.
I've searched the site for this question and got the following answer:
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
It's from https://stackoverflow.com/a/9220317/12974414.
But I tested the following code, found something weird:
console.log( (10).__proto__ === Number.prototype ) // true
console.log( instance_of(10, Number ) ) // true
console.log( 10 instanceof Number ) // false
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
How to explain this and how does instanceof operator actually work in JS ?

JavaScript has a feature called autoboxing which converts primitives to Objects when you try to access properties on them.
instanceof doesn't autobox and a primitive number is not an instance of the Number class.
You can see, in the specification:
If Type(O) is not Object, return false.

Related

Comparing 3 identical values for equality using Javascript [duplicate]

This question already has answers here:
Javascript compare 3 values
(7 answers)
Closed 2 years ago.
I am working on studying for an entry test, and being self learned I have been working a lot of functions problems. this one has stumped me,
I a to write a function testing to see if 3 values are equal. The code i have tired is:
Function equal(a,b,c){
return a==b==c;
}
as well as:
function equal(a,b,c){
let newEqual=a==b;
return newEqual===c
}
I feel like I am missing something rather simple but have not been able to put my finger on it.
thank you in advance for any insight
a == b == c will be evaluated as :
a == b then checks the result ( true ) and compares it with c => true == c which is false :
const a = 5;
const b = 5;
const c = 5;
const result = a == b == c ;
console.log(result); // false
const a1 = 5;
const b1 = 5;
const c1 = true;
const result1 = a1 == b1 == c1 ;
console.log(result1); // true
You should compare them separately :
const a = 5;
const b = 5;
const c = 5;
const result = a == b && b == c ;
console.log(result);
To check whether all three variables are equal or not, use && operator to add on queries.
&& returns true if all conditions are true.
function equal(a,b,c){
return a == b && b == c;
}
As mentioned by #mplungjan, for strict comparison use === instead of ==.
Try this.
function equal(a,b,c){
return a==b && b==c;
}
You can check it by doing the following:
function equal(a,b,c){
return (a==b) && (b==c)
}
That way you are checking if a == b is true, and b == c is true then all three are equal. In other words, true && true = true

What happens when you return a value with or "||" operator? [duplicate]

This question already has answers here:
How does this recursion work?
(11 answers)
Closed 2 years ago.
I'm not trying to get or want anything from this code. I just have a confusion with a part of the following code. The author has returned a value with or || operator. my question is which value will be returned and when?
function findSolution (target) {
function find (current, history) {
if (current == target) {
return history
}else if (current > target) {
return null
} else {
return find (current + 5, `${history} + 5)`) ||
find(current * 3, `(${history} * 3)`)
}
}
return find(1, '1')
}
console.log(findSolution(24))
here is the part of the code is bothering me
return find (current + 5, `${history} + 5)`) ||
find(current * 3, `(${history} * 3)`)
can anyone please tell me, which value when return? and why?
From MDN:
If expr1 can be converted to true, returns expr1; else, returns expr2.
in other words, you can see it as a function like this:
const or = (fel, sel) =>{
if(fel) return fel;
return sel;
}
That's why this happens:
const x = 0 || 1; // x == 1
// same as:
//
// const or = (fel, sel) =>{
// if(fel) return fel;
// return sel;
// }
// const x = or(0,1)

Chained logical OR comparison [duplicate]

This question already has answers here:
Javascript if statement with multiple permissible conditions [duplicate]
(4 answers)
Closed 5 years ago.
Why doesn't this work:
if (x != (a || b || c)) {
doStuff();
}
It's meant to check whether x is NOT equal to a OR b OR c.
EDIT: How would I achieve a check for whether x is NOT equal to a OR b OR c?
EDIT: Ok, it's a duplicate. What do I do now, take minus points even after realizing my mistake? :P
To use multiples values like you wanna just:
var x = 'x';
var a = 'a';
var b = 'b';
var c = 'c';
function doStuff() {
console.log(1)
}
// exemple 1
if(x == a || x == b || x == c) {
doStuff();
}
function isSameValue(element, index, array) {
return element === x;
}
// exemple 2
if([a, b, c].some(isSameValue)) {
doStuff();
}
// exemple 3
[a, b, c].includes(x);

javascript if (a.b.v.c.d.e === true) [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
What's an easy way to check
if (a.b.v.c.d.e === true) {}
and return false if any of b or c or v is undefined?
Coffeescript handles it easily but what is a comparable solution in vanilla javascript? Is there a library that has this common issue taken cared of?
Javascript does not have a pretty feature to do this (without using any helper functions). You can use && operator to do this:
if (a && a.b && a.b.v && a.b.v.c && a.b.v.c.d && a.b.v.c.d.e === true) {}
You can use the short-circuiting behavior of && to express the chained dependencies.
if (a && a.b && a.b.v && a.b.v.c && a.b.v.c.d && a.b.v.c.d.e === true)
Write a function and call it like this:
if (ignoreNulls(a, 'b', 'v', 'c', 'd', 'e') == true) {
// ...
}
function ignoreNulls() {
var args = Array.prototype.slice.call(arguments);
var subj = args.shift();
while (prop = args.shift()) {
var v = subj[prop];
if (v !== null && v != undefined) {
subj = v
} else {
return null;
}
}
return subj;
}

Change object property depending on integer value in javascript [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 7 years ago.
I have an object, Player, which has different properties for different rounds for example round_1, round_2, .. , round_7. I would like to give them values depending on the integer, round value.
What i thought would work would be with a function:
//voor = round in Estonian
function valiVoor(player, r){
if (r == 1){
return player.voor_1;
}
else if (r == 2){
return player.voor_2;
}
else if (r == 3){
return player.voor_3;
}
else if (r == 4){
return player.voor_4;
}
else if (r == 5){
return player.voor_5;
}
else if (r == 6){
return player.voor_6;
}
else if (r == 7){
return player.voor_7;
}
}
Although calling out function:
valiVoor(player_one,1) = "asd";
Will not change the property player_one.voor_1 = "asd". Should i work with arrays or is there any other option to resolve the issue?
You could use the Bracket notation:
player['voor_' + r] = 'asd'; //Equivalent to player.voor_# where # is the number r
If you want to check if the property exists before assigning (otherwise if r goes crazy it takes your player object in its madness):
if(player.hasOwnProperty('voor_' + r)) {
//Do stuff
}
See this MDN link for Object.prototype.hasOwnProperty.
function valiVoor(player, r){
return player['voor_'+r];
}
And a setter:
function setValiVoor(player, r, value){
player['voor_'+r] = value;
}
You can also access Object properties with the squared brackets just like Arrays.
function getValiVoor(player, r){
return player['voor_' + r];
}
If you want to assign a value, you could pass the value to the function:
function setValiVoor(player, r, val){
player['voor_' + r] = val;
}

Categories