Why is the following not valid JavaScript?
if (var foo = (true || false)) {
console.log(foo);
}
When you declare a variable in JavaScript the assignment will return the value of the new variable, so you can do something like this:
if (foo = (true||false)) console.log('Hello!');
> Hello!
Now if you call foo it will have a value of true:
console.log(foo);
> true
You cannot use the var private word, because if is a statement, not a function. If you want to be sure about the scope of your variable, then you have to declare it first:
var foo;
if (foo = (true||false)) console.log('Hello!');
> Hello!
Take a look here:
http://www.ecma-international.org/ecma-262/5.1/#sec-12.5
then here:
http://www.ecma-international.org/ecma-262/5.1/#sec-11
And conclude that the syntax isn't valid because of:
http://www.ecma-international.org/ecma-262/5.1/#sec-12.2
in relation (or rather lack thereof) to the above.
Try this :
var foo = true || false;
if (foo) {
console.log(foo);
}
Place the declaration first and then check for the condition.
You can do like this:
var foo;//declare the variable first
if (foo = (true || false)) { //then assign the value for foo
console.log(foo);
}
You cannot create variable declaration inside if statement.
Related
Is there a way in javascript to both assign and check for undefined (or null or whatever) in one line like this:
if (let myVar = DoSomethingAndReturnValue()) {
// DoSomethingAndReturnValue() returned a falsy value and so myVar is falsy
return
}
// myVar is now assigned with some value we can do something with it.
This creates a global variable but does it.
if (!(myVar = DoSomethingAndReturnValue())) {
console.log(2);
}
I have a variable and if that variable is a object I would like to call a method on that object, if not I want to do nothing.
I'm wondering if there is any reason why I shouldn't do it like this.
var foo = null;
////////////////////////////////////////////////
// some code that could change foo to a object
////////////////////////////////////////////////
foo && foo.bar();
With ES6, you can combine optional chaining operator with call:
foo?.bar?.call()
If you want to pass arguments, keep in mind that the first one in call assigns this in function call
var foo = {
bar: function(x) { return x; }
};
first.value = foo?.bar?.call(0,42); // 42
second.value = foo?.baz?.call(0,42); // undefined, no error
<input id="first">
<input id="second">
The quick answer is yes, foo && foo.bar() won't throw an exception if foo is null, and if foo is non-null, bar() will be evaluated, and it's value will be the value of the expression.
Longer answer is that any value can be interpreted as a boolean, in the sense that every value is either truthy or falsey, and that the boolean operators do short-circuit evaluation -- left to right, if we see a false && or a true ||, there's no reason to carry on evaluating.
One last fact is that the value of boolean expression is the value of the expression where the short-circuit happened.
You need to assign an object to foo and a property with a function.
var foo;
foo = {};
foo.bar = function () {
console.log('inside bar');
};
foo && foo.bar && foo.bar();
((typeof foo === 'object') && foo.bar())
or
(!(typeof foo == 'object') || foo.bar())
If foo is of type object then execute.
See my answer here javascript using or operator to iterate over list of strings aswell.
This is a "common" issue for unintended behavior, if some uses assignments inside such a sequence and forgets that evaluation stops in the || sequence after first true , or stops after first false in the && .
Is it possible to declare the variable within a conditional expression?
for example:
The code below return a syntax error (because I've declared the variable x within the conditional expression?).
var a = document.getElementById("userData");
var d = a.value;
function() {
(d.length>15)?(
alert("your input was too long")):(
var x = parseInt(d).toString(2),
a.value=x
);
}
obviously this can be fixed by simply adding var x; outside the statement, but is it possible for variables to be declared here?
Is it possible to declare the variable within a conditional expression?
No. var is a statement, and the operands to a conditional expression are expressions. The language grammar doesn't allow it. Thankfully.
You can do this with an immediately-invoked function:
(d.length>15)?(
alert("your input was too long")):
(function(){
var x = parseInt(d).toString(2);
a.value=x;
}())
);
But note that the x variable will not exist outside of the inner function. (I can't tell whether you want it to exist after the expression is evaluated or not.)
No. But you can initialize it with undefined
and set it with condition.
function Test()
{
d = 25.6654;
var x = (d.toString().length > 15) ? parseInt(d).toString() : undefined;
alert(typeof x === "undefined");
}
Then you can work with if(typeof x == "undefined") //do something
If I know the variable will be object later, I use:
var obj;
but it doesn't really matter if I initialize it as null or undefined:
var obj = null;
or
var obj = undefined;
For strings I personally use:
var str = '';
as later on I can do
str += 'some text';
and if I use null for example I get "nullsome text".
null, undefined, empty string or 0 are all falsy values so to check if they are defined. which is the correct way to initialize variables if my variable will be used as object, dom node, etc.. ?
It's initialized to undefined by default, just use that, you don't have to write it out:
var obj;
If it you want to concatenate to a string, use '', for counters use 0... Just use common sense.
In an ideal scenario, you'd just declare your variables at the top of the scope like so:
var foo, bar, obj, domNode;
All of these variables will be undefined, as in their value is undefined. If you know for a fact one of these variables will be used as a string in a loop, for example, rather thant writing foo = (foo === undefined ? '' : foo) + 'add this';, just write:
var foo = '', bar, obj, domNode;
If you're going to use the obj var as an object literal, just assign it {my: 'objec', vals: 'here'} when the time comes, or initialize it to {}, and add properties obj.as = 'you'; obj[foo] = 'go';. If you're going to assign a reference to a DOM element, keep it undefined, as any assignment will just generate pointless overhead.
Same goes for any type of reference (function objects, arrays, objects...). Just postpone the assignment, because it'll just overwrite any previous assignment.
As for numbers, undefined + 123 will get evaluate to NaN, so in that case, initializing to 0 makes sense. However, in case of loop counters:
var foo, i, obj, arr = [1,2,3];
for (i=0;i<arr.length;i++)
{
console.log(arr[i]);
}
is equivalent to:
var foo, i= 0, arr = [1,2,3];
for (;i<arr.length;i++)
{
console.log(arr[i]);
}
Only the latter almost looks wantonly complicated. Just use your common sense and you'll be all right.
Just know that variable declarations are hoisted to the top of the scope, but assignments aren't:
console.log(foo);//undefined
var foo = 123;
console.log(foo);//123
because it's translated into:
var foo;
console.log(foo);
foo = 123;
console.log(foo);
So why not write your code as it'll be interpreted by the engine?
I saw that line in some code
window.a = window.b = a;
How does it work?
Does the following always return true?
window.a == a
it means
window.b=a;
window.a=a;
OR You can say.
window.b=a;
window.a=window.b;
two assignments in a single statment
and
And one more thing
window.a==a right?
yes this is Right. It will return true
This assignment runs from right to left, so at first 'window.b' will be assigned with 'a' value then 'window.a' will be assigned with 'windows.b' value.
You can break this multiple assignment like this and get the same results:
window.b=a;
window.a=a;
You should be also aware of something like scoping.
If you run this code in global scope, eg simple script like this:
<script>
var a = 10;
window.a = window.b = a;
</script>
window.a==a is true, because 'a' and 'window.a' are the same variables. 'a' is really a property of 'window' object. All global variables are properties of 'window' object. Knowing that you can write you code like this, and this code will be corresponnding:
<script>
var a = 10;
a = b = a;
</script>
But if you put this code in a function, it runs in function scope, eg:
<script>
function ex() {
var a = 10; // this is local variable
window.a = window.b = a; // this time window.a != a
}
</script>
Same as:
window.b = a;
window.a = a;
And no, window.a and a is not always equal. Typically it is only equal on the global scope in a web browser JavaScript interpreter.
The a and b properties on the window are being assigned to the value of a. Yes, if this code is executed in the global scope, a and window.a are the same.
var a = "foo";
//window.a and a are the same variable
window.a = "bar";
a; //bar
function f(){
var a = "notfoo";
//window.a is a different variable from a, although they may take the same value
window.a = "baz";
a; //notfoo
}
It's the same like:
window.b=a;
window.a= window.b;
window.a == a will be true in this case, after the statements above. There are some cases that it will be false, for example: when a is a global variable.
And one more thing: please find more informative title for your question next time.
Actually, window.a==a can be false if a has the value Number.NaN. That's because Number.NaN is not equal to any value, including itself.