Why is this javascript expression evaluated to false? [duplicate] - javascript

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I have written a simple function that nullifies itself after its first call:
var nullify = function(){
nullify = null;
return 1;
};
If I call it two times, like this:
console.log(nullify());
console.log(nullify);
Then the 1st expression will return 1, and the other will evaluate to null. All clear up to this point.
If I however do it in a single expression and wrap it in a function:
var fun = function(f){
return f() && !f;
}
Then, for some reason:
console.log(fun(nullify));
evaluates to false, while I would expect it to be true, since 1st operand will return 1 and the other, as a negation of null, true.
The evaluation of the right-hand operand occurs when the nullify functiion has already called nullify = null, is that right? What am I missing?

What am I missing?
That your fun function is testing the variable f, which still is bound to the function you passed in, not the variable nullify (which has the value null indeed).

Related

How do JavaScript runtimes implement binding functions to objects? [duplicate]

This question already has answers here:
Why parenthesis are ignored in the expression (o.method)()
(2 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 25 days ago.
I'm implementing a JavaScript interpreter, and I can't figure out the details of binding functions to objects in JavaScript.
A rudimentary example:
const o = {
x: 1,
getX: function() {
return this.x;
}
};
o.getX(); // returns 1
The tricky part is what happens when you assign getX to a variable:
let gX = o.getX;
gX(); // returns undefined
My question is: how does the runtime know that o.getX() gets bound to o, but gX() should be unbound? I would assume gX and o.getX are pointing to the exact same function!
I first thought that maybe the presence of the . is what makes the difference. So, in the grammar, there's a production like <method-call> ::= <expr> '.' ID '(' <expr>* ')', and this expression is treated differently (the result of evaluating the first <expr> is bound to the function found under ID) than a "regular" call (without a .).
But the following expression seems to disprove this theory, because (o.getX)() also returns 1. However, in some magical way, (gX = o.getX)() returns undefined, even though it's clear to me the assignment expression returns its right-hand size, so o.getX in this case!
Is there a simple explanation of how these semantics are implemented? I can't figure out a way that my runtime is supposed to differentiate that o.getX is bound to o, but gX, even though it's pointing at o.getX, is not bound.

Javascript - succinct way to assign another value to variable if first value is not truthy [duplicate]

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 4 years ago.
I have a function that may return a value or may return null and I want to assign it to a variable. So at the moment I've got
someVar = (someFun())
? someFun()
: "foo";
Is there a shorterer way of doing it, where I don't have to call the function twice, or add an extra variable like:
funResult = someFun();
someVar = (funResult)
? funResult
: "foo";
Basically, something like:
someVar = someFun() | "foo"
The idiomatic way is
someVar = someFun() || "foo";
The || operator will yield the value of the left-hand expression if it's truthy. If not, it will move on to evaluate the right-hand side, and return its value.
For those unfamiliar with the term "truthy", in JavaScript it means values that are not considered by the language to be implicitly false. The implicitly false values are 0, NaN, false (of course), "", null, and undefined. Any reference to an object, even if it's completely empty, is considered to be "truthy".
In your specific example, the || approach is to be preferred because it means you only call someFun() once.

Difference between return ("abcd") and return "abcd"? [duplicate]

This question already has answers here:
Why use parentheses when returning in JavaScript?
(9 answers)
Closed 6 years ago.
I'm struggling with some JavaScript code that has examples that return a string in parens. Is there any difference between this:
var x = function() {
return "abcd";
}
And
var x = function() {
return ("abcd");
}
They are the same.
The parenthesis, i.e. grouping operator, here will just work as higher precedence, so that'll be evaluated first, and then the value will be returned.
There's no difference, at least in the way it is written.
Consider,
var x = 1 + 2;
vs
var x = (1 + 2);
Some prefer writing brackets around return statement but it is optional and often unnecessary. But I would advise stick to your existing code style.
In reference to this question the parenthesis do not have a specific meaning as a string is being returned. There is no expression evaluation involved so both the return statements work in the same way. In case we have an expression that needs to be evaluated, the parenthesis will provide a liberty to first evaluate the expression and then return the desired value according to the precedence rules.

What does "var app = app || {};" do? [duplicate]

This question already has answers here:
What does var x = x || {} ; [duplicate]
(6 answers)
Closed 9 years ago.
Im looking at some Backbone.js examples and they have var app = app || {}; at the top of all .js files. I understand the literal meaning of this, but what does it do in reference to everything else?
Edit: you guys are really really fast.
It will define the variable app to an empty object if it is not already defined.
This works because being undefined evaluates to false in Javascript.
If it is defined, it may still be re-defined as an empty object if it has a value which evalutes to false, such as an empty string.
The || operator in javascript will return the first operand if it is "truthy". If not, it will return the second operand. If app has not been assigned, it will be undefined, which is "falsey". Thus if it is not defined or is otherwise falsey, an empty object {} will be assigned to app.
This means "define app as an empty object if it's not already defined".
The OR operator in JavaScript does not necessarily yield a boolean. If the left-hand side of the expression yields false then the assignment takes the right-hand side of the expression.
If app is already defined, the it does nothing.
If app is not defined, then it's equivalent to var app = {};

What does || mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this construct mean?
I'm encountering this syntax for the first time and am not sure what it's doing:
self.name = _searchString(settings.dataBrowser) || "An unknown browser";
What does the or (double pipes) condition do? When would self.name be set to the second value?
This is the logical or operator.
It evaluates to its first "truthy" operand.
In particular, it will evaluate to the second operand if the first operand is "falsy" — null, false, undefined, 0, "", or NaN.
Crockford calls / called it a default operator
this is directly related to a question i have asked, you can read about it here
Short-circuit evaluation via the AND operator in PHP
so basically, it sets self.name to the value returned from the function, but if the function returns false, it sets itself to "An unknown browser";

Categories

Resources