I know that var some = []; creates a new array and var someother = {} creates a new object. So what does the () do?
Specifically, in the following code :
var someVar = (1,2,3); //someVar equals 3
and
typeof (1,2,3) //returns "number"
So what does the () do in the above code?
See precedences of operators.
(1,2,3)
is just
3
because the comma operator returns the last value.
The parenthesis in
typeof (1,2,3)
just prevent it to be interpreted as
(typeof 1),2,3
because the typeof operator has a higher precedence than the comma operator.
That is a grouping operator.
It causes the contents to be evaluated as an expression in their own right. Effectively it changes precedence since otherwise the someVar = 1 would be evaluated first (instead of the result of (1,2,3) being evaluated and the result used in the someVar = ... expression.
That expression 1,2,3 uses a comma operator which evaluates as the right hand side, so it is 3.
Related
What does it mean when variable value in round brackets in js?
For example,
let a = (1,2,3);
What does it mean and why console.log(a) output is 3?
What is usage of comma operator in round brackets in variable initialization?
The parentheses are needed for grouping. In a let statement, commas are normally used to separate multiple variables that are being declared, e.g.
let a = 1, b = 2, c;
which is short for
let a = 1;
let b = 2;
let c;
If you write
let a = 1, 2, 3;
you'll get a syntax error, because after the comma it expects another variable declaration; it's equivalent to:
let a = 1;
let 2;
let 3;
The second and third declarations are clearly wrong, as 2 and 3 are not variable names.
The parentheses indicate that the whole expression 1, 2, 3 is being used to initialize one variable.
The expression 1, 2, 3 uses the Comma operator, which executes each of its subexpressions and returns the last one as its value. It's pretty useless when the subexpressions are all constants, so I assume your code was just a simplified example. Because the way it's written, it's really just equivalent to:
let a = 3;
What you have encountered is the comma operator.
Quoting the docs
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
Therefore in your case 1, 2 and 3 is evaluated and 3 is returned and thus assigned to the variable a.
This is not variable declaration-specific thing. You can write (1,2,3) anywhere in your JS code and it will always evaluate to 3. The thing is, JavaScript (like many other programming languages, e.g. C) has comma operator, which simply returns last element. The expression (1,2,3) basically looks just like (1+2+3) to JavaScript, except for comma operator is applied instead of addition.
It's call the comma operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
It's a very handy thing to use in JavaScript, because it allows you to run multiple statements as a single value for an arrow function.
Here is an example of a 10x10 identity matrix generated with one line of code. The last comma value is returned as the value.
const m = new Array(9).fill('000000000').map((v,i)=> (v=[...v],v[i]='1',v.join()));
console.log(m);
The same above code as a blocked function would take a lot more lines.
const m = new Array(9).fill('000000000').map((v,i)=> {
v = [...v];
v[i] = '1';
return v.join()
});
console.log(m);
I was wondering if its possible to access the value being considered when using the ternary conditional operator.
e.g.:
const dict = new Map<Foo, Bar>();
const x = dict.get("foo") !== undefined ? dict.get("foo") : new Bar();
Is there any way to get rid of the repeated dict.get("foo") in this ternary expression?
No, the ?: operator is evaluating expressions. You're giving it the expression dict.get("foo") !== undefined, which is a boolean expression. There's no way for the ?: operator to isolate just the dict.get("foo") within that expression to refer to later.
If you need the specific !== undefined test, then no, there's no other way. To avoid the repetitive method call you could only refactor that to:
let x = dict.get("foo");
if (x === undefined) {
x = new Bar();
}
However, if a truthy comparison will do instead of specifically the test for undefined, this is the common idiom:
const x = dict.get("foo") || new Bar();
To test if a regex matches and assign it to a variable if it does, or assign it to some default value if it doesn't,
I am currently doing the following:
var test = someString.match(/some_regex/gi);
var result = (test) ? test[0] : 'default_value';
I was wondering if there is any way to do the same thing in JS with one line of code.
Clarification:
I am not trying to make my code smaller, but rather make it cleaner in places where I am defining a number of variables like so:
var foo = 'bar',
foo2 = 'bar2',
foo_regex = %I want just one line here to test and assign a regex evaluation result%
You could use the OR operator (||):
var result = (someString.match(/some_regex/gi) || ['default_value'])[0];
This operator returns its first operand if that operand is truthy, else its second operand. So if someString.match(/some_regex/gi) is falsy (i.e. no match), it will use ['default_value'] instead.
This could get a little hacky though, if you want to extract the second capture group, for example. In that case, you can still do this cleanly while initializing multiple variables:
var foo = 'bar',
foo2 = 'bar2',
test = someString.match(/some_regex/gi),
result = test ? test[0] : 'default_value';
In C# you can do the following:
string y = null;
string x = y ?? "sup stallion"; //x = "sup stallion" since y is null.
Where The ?? operator is the null-coalescing operator.
And in Javascript I've seen something similar:
var headers;
var myHeader = headers || {'Content-type':'text/plain'}; //myHeaders = {'Content...
I've also seen: (The 2nd code snippet on the page)
var headers;
var myHeader = headers | {'Content-type':'text/plain'};
Is there a difference between the two? What is this pattern called...default parameter?
|| is a logical or. It returns the first truthy operand* (the last value evaluated). So
var myHeader = headers || {'Content-type':'text/plain'};
Returns "headers" if it's truthy (and if it's null or undefined, that value is coreced into "false"). If it's falsey, it returns the second operand. I don't believe this has a very specific name in javascript, just something general like "default argument value".
| is a bitwise or. It is a mathematical operation and does something completely different. That operator doesn't even make sense here (and it will generally just produce 0 as a result). Wherever you saw that, it was surely a typo, and they meant to use logical or.
So go with that first method (a = b || c).
* "Logical or" is also known as "logical disjunction" or "inclusive disjunction". Javascript, like all programming languages, evaluates logical statements using short-circuit evaluation. With logical-or expressions, it evaluates each operand for truthiness and stops on the first true one (and returns that value). If there are no truthy operands, it still had to go through all of them, so it returns the last operand, still the last one it evaluated. Logical and (&&) is similarly short-circuited by stopping on the first falsey operand.
Nullish coalescing operator is supported now by javascript(es2020)
As the mozilla doc says:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
The nullish coalescing operator (??) is a logical operator that
returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.
Contrary to the logical OR (||) operator, the left operand is returned
if it is a falsy value which is not null or undefined. In other words,
if you use || to provide some default value to another variable foo,
you may encounter unexpected behaviors if you consider some falsy
values as usable (eg. '' or 0). See below for more examples.
// Assigning a default value to a variable (old way but in some cases we need this)
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
// Assign default value when we want to skip undefined/null only
// in most cases we need this, because (0,"",false) are valid values to our programs
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
For more info read this example provided by kent c dods about fallback to default value in the past and now:
https://kentcdodds.com/blog/javascript-to-know-for-react#nullish-coalescing-operator
I am not familiar with the second pattern. The two patterns I am aware of:
1) Your first pattern is a basic logical or operator. If the first value is falsy then the second value is assigned.
2) The second pattern is called a ternary assignment, which is similar in logic to a basic if condition, but the syntax is slightly different.
var test = (typeof myTest === "string") ? firstValue : secondValue;
In this pattern the question mark separates the condition from the values and the colon separates the values. Tertiary assignments can be nested so that one of the values contains another tertiary.
Not really an expert to this but the || is a Logical Operator and | is a Bitwise Operator
ES2020 has brought nullish coalescing operator (??) to javascript.
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
alert(f); // 4
Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?
My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.
Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
This is made to assign a default value, in this case the value of y, if the x variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.
The following values are considered falsy in JavaScript.
false
null
"" (empty string)
0
Nan
undefined
Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
This question has already received several good answers.
In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.
Using this technique is not good practice for several reasons; however.
Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.
Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.
Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:
() ? value 1: Value 2.
Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = ( a ) ? a :
( b ) ? b :
( c ) ? c :
( d ) ? d :
e;
alert(f); // 4
Return output first true value.
If all are false return last false value.
Example:-
null || undefined || false || 0 || 'apple' // Return apple
It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.
For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:
function doSomething(data, callback) {
callback = callback || function() {};
// do stuff with data
callback(); // callback will always exist
}
Its called Short circuit operator.
Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.
It could also be used to set a default value for function argument.`
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar`
It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.
it's the same as
if(x)
z = x;
else
z = y;
It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.
It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.
var x = '';
var y = 'bob';
var z = x || y;
alert(z);
Will output 'bob';
According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)
He also suggests another use for it (quoted):
"lightweight normalization of cross-browser differences"
// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;