You can parse it

JSON.parse('null') // null
JSON.parse('1')   //  1

so

var val = sessionStorage.getItem('key');
val = JSON.parse(val);

Close to cast

Alternative would be:

var val = sessionStorage.getItem('key');
val = val*1 || null;
Answer from kidwon on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › how-null-is-converted-to-string-in-javascript
How null is converted to String in JavaScript?
August 11, 2022 - We can use this technique to convert null to string. We use + operator to concatenate the null and empty string(""). Here is the example to convert null to string using this approach. ... In the below program we concatenate null with "" using + to convert null to string.
Top answer
1 of 2
9

You wrote:

document.getElementById("demo").innerHTML = String(null); //returns an empty string 
document.getElementById("demo").innerHTML = null.toString(); //returns "null" string

But both assertions are false, I am afraid.

String(null) never returns an empty string, rather a primitive of type string whose value is "null".

BTW, the form String(null) should never be used.

new String(null), on the other hand, returns an object, an instance of String (note the uppercase first letter) whose primitive value ([[PrimitiveValue]] internal property) is "null".

null.toString() raises an error in every JS engine I know. Even though null might be considered an object (due to a historical bug), it has no property, therefore no 'method' toString() (I quote the 'method' because there are no methods in JS, really).

Anyway, to be consistent, you could use this :

document.getElementById("demo").innerHTML = whateverVariable || '';

Should whateverVariable be falsy (null, undefined, 0, -0, '', NaN or false), empty string '' will be assigned to document.getElementById("demo").innerHTML.

2 of 2
4

I don't think there's a real convention here; Element.innerHTML is a property that tests the given value to determine what to do. In Safari it behaves like this:

if (value === null || value === '') {
    // remove all contents
} else {
    // parse string representation of value into the elements contents
}

So both "" (empty string) and null are considered the same and the assignment will just remove all contents; I couldn't find conclusive evidence that would suggest other browsers work this way, but it seems very likely that it should be considered an implementation detail that you shouldn't rely upon (see update).

That said, the documented way of clearing an element is by assigning the empty string to this property.

Update

I've found this (inconclusive) email thread about the subject, highlighting that this behaviour is not standardised:

For .innerHTML = null Opera and Internet Explorer act as if the literal string "null" was used. Firefox acts as if "" was used.

Top answer
1 of 4
41

After reviewing my previous answer, it seems a complete overhaul of my previous answer is necessary. I was way over complicating it, as the short answer is that these are standards-specified special cases.

The specification for String() (String used as a function):

15.5.1.1 String ( [ value ] )

Returns a String value (not a String object) computed by ToString(value). If value is not supplied, the empty String "" is returned.

The ToString function (that exists internally, not in userland) is defined as follows (9.8):

"The abstract operation ToString converts its argument to a value of type String according to Table 13"

Argument Type | Result
Null | "null"
Undefined | "undefined"

This means that String(null) and String(undefined) go into this special table of types and just return the string values valued "null" and "undefined".

A user-land pseudo-implementation looks something like this:

function MyString(val) {
    if (arguments.length === 0) {
        return "";
    } else if (typeof val === "undefined") {
        return "undefined";
    } else if (val === null) {
        return "null";
    } else if (typeof val === "boolean") {
        return val ? "true" : "false";
    } else if (typeof val === "number") {
        // super complex rules
    } else if (typeof val === "string") {
        return val;
    } else {
        // return MyString(ToPrimitive(val, prefer string))
    }
}

(Note that this example ignores the constructor case (new MyString()) and that it uses user-land concepts rather than engine-land.)


I got a bit carried away and found an example implementation (V8 to be specific):

string.js:

// Set the String function and constructor.
%SetCode($String, function(x) {
  var value = %_ArgumentsLength() == 0 ? '' : TO_STRING_INLINE(x);
  if (%_IsConstructCall()) {
    %_SetValueOf(this, value);
  } else {
    return value;
  }
});

macros.py:

macro TO_STRING_INLINE(arg) = (IS_STRING(%IS_VAR(arg)) ? arg : NonStringToString(arg));

runtime.js:

function NonStringToString(x) {
  if (IS_NUMBER(x)) return %_NumberToString(x);
  if (IS_BOOLEAN(x)) return x ? 'true' : 'false';
  if (IS_UNDEFINED(x)) return 'undefined';
  return (IS_NULL(x)) ? 'null' : %ToString(%DefaultString(x));
}

The NonStringToString (which is essentially what is of interest), is luckily defined in psuedo-JS-land. As you can see, there is indeed a special case for null/true/false/undefined.

2 of 4
2

There is probably just some extra checks and handling for special cases like null and undefined.

MDN says:

It's possible to use String as a "safer" toString alternative, as although it still normally calls the underlying toString, it also works for null and undefined.

Top answer
1 of 2
3

When you write +!service.getNullValue() ?? undefined, you're actually performing four steps.

  1. Call service.getNullValue().
  2. Logically negate (!) the result of (1).
  3. Use the unary plus operator (+) to convert the result of (2) into a number.
  4. Coalesce (??) the result of (3) and undefined.

The order is important. Also important is that TypeScript compiles to JavaScript which has the concept of truthiness. The behavior you are seeing is a direct result of the truthiness of the return values of your service's methods.


In the case of getNullValue(), the evaulation is:

  1. service.getNullValue() returns null.
  2. !null uses the fact that null is falsey to return true.
  3. +true converts true to 1.
  4. 1 ?? undefined returns 1.

Similarly, for getStringValue():

  1. service.getStringValue() returns "20".
  2. !"20" uses the fact that a non empty string is truthy to return false.
  3. +false converts false to 0.
  4. 0 ?? undefined returns 0.

I cannot think of a good way to inline the check for null and the conversion to a number in the same coalesce statement.

For JavaScript, you can use the fact that parseInt returns NaN for null (among other values) to check whether the result of calling service.getNullValue()/service.getStringValue() was null.

function getStringValue() { return "20"; }
function getNullValue() { return null; }

var value = parseInt(getStringValue());
console.log(isNaN(value) ? undefined : value);

value = parseInt(getNullValue());
console.log(isNaN(value) ? undefined : value);

Since TypeScript checks the type of the parameter for parseInt(:string), I think your best bet is just moving to an explicit null check.

let value = this.service.getStringValue();
console.log(value
    ? parseInt(value as string)
    : undefined);

value = this.service.getNullValue();
console.log(value
    ? parseInt(value as string)
    : undefined);
2 of 2
1

You can simply use like that

(Number(YourNullableString) || null)
🌐
php.cn
m.php.cn › home › web front-end › front-end q&a › how to convert null to empty string in javascript
How to convert null to empty string in JavaScript-Front-end Q&A-php.cn
April 6, 2023 - The following code demonstrates how to use the double pipe (||) operator to convert null to an empty string. ... In JavaScript, the null type does not have a toString() method, so it cannot be directly converted to an empty string.
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-convert-null-to-zero
Convert NULL/Undefined/NaN to 0 using JavaScript | bobbyhadz
Use the logical nullish assignment operator to convert `null` or `undefined` to `0`, e.g. `val ??= 0;`.
🌐
CodingTechRoom
codingtechroom.com › question › convert-null-object-to-string-javascript
How to Convert a Null Object to a String in JavaScript? - CodingTechRoom
This is particularly useful when you want to safely handle null values without throwing errors. ... const nullValue = null; const stringValue = String(nullValue); // converts to 'null' // Example with template literals: const greeting = `The value is: ${String(nullValue)}`; // Outputs: The ...
🌐
Experts Exchange
experts-exchange.com › questions › 24389249 › Javascript-converting-null-to-string.html
Solved: Javascript converting "null" to string | Experts Exchange
May 6, 2012 - Bugada probably has the most efficient solution, but I guess that having to check every variable for being null before I use it is just something I'm going to have to get used to in Javascript. ... Still I noticed the following: new String() initializes an empty string new String(null) initializes the character string "null" new String(undefined) initializes the character string "undefined" delete c; new String(c); throws a ReferenceError because c is not defined There doesn't seem like a lot of logic to this behavior.
🌐
TutorialsPoint
tutorialspoint.com › How-null-is-converted-to-Number-in-JavaScript
How null is converted to Number in JavaScript?
The Number() method in JavaScript is used to convert a value into a number. If the value is not convertible, then it will return NaN. To convert the null into a Number we pass the "null" as an argument to the Number() method.
🌐
DEV Community
dev.to › manikbajaj › avoid-tostring-fatal-error-string-casting-in-javascript-2mn6
Avoid toString() Fatal Error [String Casting in JavaScript] - DEV Community
December 7, 2020 - Now, this is a normal practice in JavaScript and you will use toSting method quite often to convert values to strings. But, there is a problem here. Let us suppose that the value of the variable is of the type null or undefined. This might happen in case of a function not returning a value ...
🌐
Java2s
java2s.com › Tutorials › Javascript › Data_Type › String › Convert_null_to_string_with_String_in_JavaScript.htm
Convert null to string with String() in JavaScript
The following code shows how to convert null to string with String(). <!DOCTYPE html> <html> <head> <script type="text/javascript"> var value3 = null;<!-- ww w . j a va 2 s .
🌐
GitHub
github.com › redux-form › redux-form › issues › 2062
Can we not convert null to empty string? · Issue #2062 · redux-form/redux-form
November 1, 2016 - Can we not do this? https://github.com/erikras/redux-form/blob/b531cbeb72f97b85771845664ac68bf2da8360c7/src/createFieldProps.js#L53 When I pass null, I expect null, not an empty string.
Author: redux-form
🌐
Retool
community.retool.com › 💬 app building
Replace empty string to null in form submit, and JS limitation in Changeset Object - 💬 App Building - Retool Forum
December 18, 2023 - I might be asking trivial questions but I really couldn't figure them out In a very simple pgsql form submit, some of foreign key need to be null instead of "" otherwise I get below error My first thought is to use inline js to replace "" with null inside Changeset -> Object -> {{form.data}}, but immediately I get run into a error object.keys() is not a function shown in below screenshot.
🌐
GitHub
github.com › colinhacks › zod › issues › 1721
How to transform empty strings into null? `z.emptyStringToNull()` · Issue #1721 · colinhacks/zod
December 18, 2022 - import { afterAll, beforeAll } from 'vitest'; import { z } from 'zod'; describe('Test zod validations', () => { it('should correctly handles a valid ISO date-string', () => { const valid_from = '2022-12-14T22:07:10.430805+00:00'; const valid_to = undefined; <-- this works const valid_to = null; <-- this works const valid_to =""; <-- this is not working const schema = z.string().datetime({ offset: true }).nullish(); expect(schema.parse(valid_from)).toStrictEqual(valid_from); expect(schema.parse(valid_to)).toStrictEqual(valid_to); }); });
Author: colinhacks
🌐
Pine
pineco.de › snippets › casting-null-values-string
Casting Null Values to String - Pine
July 5, 2021 - // Cast null to string // Then you can perform any "string" action (value || '').toString(); // Chain the methods after this