Skip to main content

Type conversion and casting

@serverSerrverlesskiy

Type coercion (type coercion)#

It is an automatic or implicit conversion of values from one data type to another (for example, a string to a number). Type conversions are similar to type conversions because they both convert values from one data type to another, with one key difference - type conversion is implicit, while type conversion can be implicit or explicit.

transformation

Examples πŸ‘‡:

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

In the example above, JavaScript casts the number 9 into a string, and then concatenates the two 2️⃣ values together, resulting in the string 59. JavaScript had a choice between string or number and chose to use string.

The compiler could convert the string 5 to a number and return the sum of 14, but it did not. To get this result, you need to explicitly convert the string 5 to a number using the Number() πŸ‘‡ method:

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

Type conversion#

Transformation

Means the transfer of data from one data type to another. Implicit conversion occurs when the compiler automatically assigns (assigns) data types, but the source code may also explicitly require the conversion to complete.

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Links#

  1. MDN web docs - Typecasting
  2. Code for Teens: The Perfect Beginner's Guide to Programming, Volume 1: Javascript - Jeremy Moritz
  3. JavaScript.ru
  4. Integer arithmetic

Contributors ✨#

Thanks goes to these wonderful people (emoji key):


Dmitriy Vasilev

πŸ“–πŸ’΅

Resoner2005

πŸ› 🎨 πŸ–‹

Become a Patron!