Uncaught SyntaxError: Unexpected token '?' - javascript

console.log(undefined ?? 'default');
Why am I getting an error Uncaught SyntaxError: Unexpected token '?'

Updated answer
The nullish-coalescing operator was added in ECMAScript 11.
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.
let x = undefined;
console.log(x ?? 'default');
x = null;
console.log(x ?? 'default');
Original answer
Currently, there is no ?? operator in javascript.
You can use the ternary operator:
let x = undefined;
console.log(x == undefined ? 'default' : x);
which will print 'default' if x is undefined, otherwise, it will print the value of x.
However, you've found the proposal for the nullish coalescing operator. This is currently a proposal in stage 3, but it looks like it will make it into a future version of the ECMAScript.

As mentioned in #Uncle's comment, that feature is only a proposal at this point and is not currently implemented in Javascript. To use it before it is implemented in modern browsers, you'll need to add this Babel plugin: #babel-plugin-proposal-nullish-coalescing-operator.

Related

Will the Logical nullish Assignment or nullish coalescing evaluate the assigned value in a non null case?

I want to understand if my use case will benefit from the logical nullish assignment operator.
I'm checking my database to see it some data exists, otherwise I fetch it from an API, however I don't want to fetch the data from the API if the data already exists in my database, I'm describing the scenario with some code below.
let myData = await Database.getData(); // will return null if the data doesn't exist
myData ??= await fetch("API"); // does this API call get executed even if myData is non null?
Just to clarify, I'm wondering if the API call is executed, even though it might return the database data.
Does using nullish coalescing instead make a difference, for such a scenario ?
I'm aware that I can use several methods including if-else for such a case, however I want to understand if these operators will for in such a scenario.
does this API call get executed even if myData is non-null?
No, it will not be executed.
myData ??= await fetch("API")
is equivalent to
myData ?? (myData = await fetch("API"))
So, only if the first expression myData is nullish, the second assignment part runs.
let value = "test"
value ??= null.toString() // doesn't throw error because it is not executed
console.log(value)
value = null
value ??= null.toString() // throws error
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.
The answer is no. details

Compilation fail when tried to execute [duplicate]

console.log(undefined ?? 'default');
Why am I getting an error Uncaught SyntaxError: Unexpected token '?'
Updated answer
The nullish-coalescing operator was added in ECMAScript 11.
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.
let x = undefined;
console.log(x ?? 'default');
x = null;
console.log(x ?? 'default');
Original answer
Currently, there is no ?? operator in javascript.
You can use the ternary operator:
let x = undefined;
console.log(x == undefined ? 'default' : x);
which will print 'default' if x is undefined, otherwise, it will print the value of x.
However, you've found the proposal for the nullish coalescing operator. This is currently a proposal in stage 3, but it looks like it will make it into a future version of the ECMAScript.
As mentioned in #Uncle's comment, that feature is only a proposal at this point and is not currently implemented in Javascript. To use it before it is implemented in modern browsers, you'll need to add this Babel plugin: #babel-plugin-proposal-nullish-coalescing-operator.

Is there a shorter syntax for returning the first element of an array or null?

I find this syntax lengthy. Is there a shorter syntax like inspiring from null coalescing ?
let a = [];
console.log(a.length>0?a[0]:null);
Better way using
Optional_chaining
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
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.
let a = [];
a.push("foo");
// long
console.log(a.length>0 ? a[0] : null);
// short
console.log(a[0] ?? null)

How to check if value is undefined and if it is, set it to null

value = value ? value : null;
I want to set value to null if it is undefined. Beside what I already have written, what else I can do with less repeating and more clean?
Nullish coalescing operator (??)
You can use the nullish coalescing operator, which 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":
value = value ?? null;
This best fits your requirements to assign null when value is undefined.
In combination with the assignment, this can be made even more concise by using the logical nullish assignment operator (??=):
value ??= null;
This should meet all your requirements, but let's also look at some possible alternatives:
Logical OR operator (||)
Another alternative could be the || operator:
value = value || null;
Or in its assignment form:
value ||= null;
The difference here is that null will be assigned for any falsy value, including 0, false, and ''.
Ternary operator (?:)
This is the original implementation from your question:
value = value ? value : null;
Essentially, this exhibits the same problem as the logical OR operator implementation in the sense that null will be assigned for any falsy value. In this case, however, this can be mitigated by including a stricter comparison in the ternary condition (making it even more verbose):
value = value != null ? value : null;
undefined, null, 0, Nan and '' are considered as a falsy statement, so if you want to make sure that you update your variable only if it holds an undefined value you should consider using an if statement like this
if(value==undefined) value =null;

Null-coalescing in Javascript?

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

Categories