2

Is there any data types of nothing available in javascript? I mean like not the null or undefined or 'empty string' but pure nothing. For example, i want to print a variable to console; console.log(variable) it should prints nothing. Is there something like that? Because i needed in do operations in array. Like [x === true ? "Script": `!this should be nothing not empty string but nothing!`] if i print that array i want to see just empty array not null or undefined in that array.

xKralTr
  • 101
  • 9
  • 1
    3 nothing types are `null`, `undefined` and `false` – Dean Van Greunen Nov 12 '22 at 14:34
  • 1
    this is somewhat available via typescript, [see more here](https://stackoverflow.com/questions/50977783/how-to-set-a-type-parameter-to-nothing-in-typescript) – Dean Van Greunen Nov 12 '22 at 14:35
  • 4
    @DeanVanGreunen `false` is not a type. And if you extend "nothing" to mean "falsy values", then why not also list `""`, `0`, `NaN` and `0n`? – Bergi Nov 12 '22 at 14:39
  • 4
    Javascript already has one notion too many for "nothing"... Let's not make things worse ;-) – trincot Nov 12 '22 at 14:41

2 Answers2

3

No, there is not. The undefined value comes closes to what you want, but an array with a value is still distinguishable from an array without a value.

You'll need to write

x === true ? ["Script"] : []

instead.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Based on your actual problem, you can use the spread operator (assuming you have multiple values):

To answer your question, however -- no, that does not exist. The closest you can get to that is undefined which exists when trying to access "undefined" JSON properties (try doing window.x in inspect element)

function printOutArrayOptionally(flag) {
  return [...(flag ? ["Value"] : [])]
}

console.log(printOutArrayOptionally(true))
console.log(printOutArrayOptionally(false))
LeoDog896
  • 3,472
  • 1
  • 15
  • 40