Object-Oriented JavaScript — Strings

Image for post
Image for post
Photo by Rajiv Perera on Unsplash

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at strings, which is one of the building blocks of objects.

Strings

A string is a sequence of characters to represent text.

Any values placed between single quotes, double quotes, or backticks are string.

If we have:

Then typeof s returns 'string' .

If we put nothing between the quotes, it’s still a string.

The + operator is used to concatenate 2 strings.

If we have:

Then we s is 'website' .

And typeof s would be 'string' .

This is a source of errors in the system.

To avoid errors, we should make sure that operators are strings.

This way, we won’t be adding anything by accident.

String Conversions

A string is converted to a number behind the scene if a number string is encountered.

For instance, if we have:

Then typeof s returns 'number' .

If we have:

Then s++ converts s to 'number' .

We can convert a number string to a number by multiplying y 1 or use parseInt .

For instance, we can write:

Now s is a string.

If the conversion fails, we get NaN .

There’re many strings with special meanings.

\ is the escape character.

We can use it to escape \, ' and " so that they can be in th string.

For instance, we can write:

and s is 1 \ 2 .

\n is the line end character.

If we have:

We get:

\r is the carriage return character.

If we have:

We get:

\t is the tab character. If we have:

We get:

\u is the character code that lets us use Unicode.

For instance, we can write:

and s is

String Template Literals

ES6 introduced the template literal.

They let us embed expressions within regular strings.

ES6 has template literals and tagged literals.

Template literals are single or multiline strings with embedded expressions.

For instance, we can write:

We have the level and message variables embedded into the template literals.

So we get:

logged.

Template literals are surrounded by backtick characters instead of quotes.

They’re concatenated into a single string.

We can have any expression int eh ${} .

For instance, we can write:

We embed the result of the function calls into the template literal.

And we get:

returned.

Image for post
Image for post
Photo by Amrit Sangar on Unsplash

Conclusion

Strings are a sequence of characters.

We can create strings and template literals, which can have expressions embedded in them.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store