1

In Javascript, why does this statement not equal '\b,\b'?

['\b', '\b'].join()
//=> ","

According to MDN docs on join:

If an element is undefined or null, it is converted to the empty string.

So why is \b being evaluated as undefined/null?

Additionally, the\b is dropped from any string prepended with it, e.g:

['\btest', '\btest2'].join()
//=> "test,test2"

Something crazy is going on.

ccnokes
  • 6,885
  • 5
  • 47
  • 54
  • 1
    type `"\b"` in your console, it will return an empty string – gurvinder372 Feb 23 '16 at 05:32
  • @gurvinder372 yeah it does, but why? `\a` returns 'a', which is strange too. What's this back slash character doing? – ccnokes Feb 23 '16 at 05:34
  • 1
    Its a special character. Try to use double backslash b - `\\b` – Dawid Pura Feb 23 '16 at 05:37
  • `\b` is defined right at the top of the [MDN page on strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notatio). –  Mar 19 '16 at 06:42

2 Answers2

2

So why is \b being evaluated as undefined/null?

As per the spec

In determining the sequence any occurrences of \ UnicodeEscapeSequence are first replaced with the code point represented by the UnicodeEscapeSequence and then the code points of the entire IdentifierName are converted to code units by UTF16Encoding (10.1.1) each code point.

Also read this part to understand which are escape character and which are not

CharacterEscapeSequence ::

SingleEscapeCharacter NonEscapeCharacter

SingleEscapeCharacter ::

one of ' " \ b f n r t v

NonEscapeCharacter

:: SourceCharacter but not one of EscapeCharacter or LineTerminator

EscapeCharacter ::

SingleEscapeCharacter

DecimalDigit x u

HexEscapeSequence ::

x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ HexDigits }

Which is why \b being a special character is removed while \a is still "a".

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • @ccnokes, check this answer for **why** this is happening. – gurvinder372 Feb 23 '16 at 05:52
  • You're quoting the wrong part of the spec. `b` is not a "UnicodeEscapeSequence", which is a hex number prefixed by `u`. You are looking for the production called "SingleEscapeCharacter". –  Mar 19 '16 at 06:39
  • @torazaburo updated the answer to include what is an escape character and what is not. – gurvinder372 Mar 21 '16 at 05:11
1

\b is a special character, which means backspace.

That is why it is being converted to the 'empty' string.

Reference:

Henrikh Kantuni
  • 901
  • 11
  • 14