Get up to 80 % extra points for free! More info:

Lesson 3 - Basic data types in JavaScript and its functions

In the previous lesson, Getting started with JavaScript - First scripts, we wrote some first scripts and learned how to work with variables. In today's tutorial, we'll look onto basic data types in more detail, specifically Strings, numbers, and booleans. Although the JavaScript manages the data types for of us, we cannot totally avoid them and we should know how they work.

Recapitulation

JavaScript is a dynamically typed language. It relieves us from the fact that a variable does some data type at all. But it has of course, it just doesn't seem like that. We can create a variable with a numeric value, then assign an object to it, and then a decimal number. The language will deal with it and automatically change the variable's type. Because we don't need to specify the variable types, beginner programmers might be happy. However, they'll learn through the time, that even this system has some disadvantages. Especially the automatic code validity check, which is reduced.

Basic data types are these: String (text), Number (number with/without decimal), Boolean (true/false), Object, and Null or Undefined.

We'll describe arrays and objects later and go through only the basic data types today.

String

String is a many characters saved in consecutive bytes in a memory. Maximal length is not exactly specified, it depends on the interpreter. In some variations it might be theoretically infinity and is limited only with the RAM size.

As we learnt before, strings may be declared using double quotes or even single quotes:

let s1 = "some text";
let s2 = 'some text';

Quotes can be combined even inside of the String. So if we e.g. want to write a single quote we insert the String into the double quotes.

let s1 = 'I like the " character, because I like how it looks.';
let s1 = "David, yes, that's me!";

If it's necessary to use the same quote in the text as is used to declare it, the quote needs to be escaped, so the interpreter won't understand it as an end of the string but just as an ordinary character. To do so we use the backslash (\):

let x = "I like the \" character, because I like how it looks.";

Characters prefixed with the backslash are called escape sequence. Besides quotes we may write down a few more special characters, using the backslash, which would be otherwise hard to write. There's a list of them:

  • \a - Beep
  • \b - Backspace
  • \f - Skip to another "page"
  • \n - New row
  • \r - Carriage return
  • \t - Horizontal tabulator
  • \v - Vertical tabulator
  • \\ - Back slash
  • \' - Single quote
  • \" - Double quote
  • \0 - Null character (also used to end Strings)

Notice that if we want to write the backslash we have to write it twice, otherwise JavaScript would think that we're about to write some special character.

Functions and properties of strings

Index

Using indexes we can access the individual characters in a String the same way as in arrays. We'll speak about the array later, so this is just an example ahead. The index is written between square brackets right after the name of the variable. It's zero-based, so beware, if you want the first character, it's 0.

let x = "text";
document.write(x[0]); // prints the first character of the string
document.write(x[3]); // prints the fourth character

Length

The property (as the name suggests) carries the length of the string in characters.

let s = "text";
document.write(s.length); // Prints 4

Trim()

If we read some text from the user, it may happen that they'll write a space before or after it. And there're often some another whitespace characters around the strings, e.g. end of line. The trim() function trims those whitespaces around the string so it doesn't complicate additional processing of the string. If they're inside of the string, they'll be kept.

let s = "  John Smith  ";
s = s.trim(); // Inside of s is now stored "John Smith"

Replace()

This function replaces the searched value inside of the string with another one.

let str = "PHP is the best!";
let s = str.replace("PHP", "JavaScript");

toUpperCase() and toLowerCase()

Changes all the letters in the string to the upper case or the lower case.

let s = "string";
s.toUpperCase(); // uppercase characters
s.toLowerCase(); // lowercase characters

Concat()

Joins two and more strings. This function is called automatically when we try to add a String using the + operator.

str1 = "Charles";
str2 = "John";
str3 = "Peter";

let joined = str1.concat(str2,str3);
let joined2 = str1 + str2 + str3;

The last 2 lines do the same, they join the strings into a longer ones.

Substring() and Substr()

Functions return selected part of the String, which is called substring. Both do basically the same, they just differ in their parameters.

s = "Tutorials at ICT.social";
substring1 = s.substr(2, 6); // Returns 6 characters from the second position so "torial"
substring2 = s.substring(2, 6); // Returns characters from the second to the 6th position, so "tori"
Split()

Splits the string into an array of strings using the specified character.

str.split("-"); // How-do-you-do == [0] How [1] do [2] you [3] do

Returns the position of the specified substring.

str.indexOf("hello"); // returns the first index
str.lastIndexOf("hello"); // returns the last index
str.search("hello"); // returns the index of the searched string or the REGEX expression. We'll speak about regex later

Match()

Returns the match with the expression in the string. It's being used mostly for regular expressions (Regex), see further lessons.

Numbers

Numbers can be written using two ways. First as usual:

let x = 10;

And the second using the scientific (exponential) notation:

let x = 10e5; // 10**5 = 100 000

We can do a lot of basic operations with numbers like summation, multiplication, division... There's also a remainder after an integer division (modulo) which we write using the % operator.

In JavaScript, all numbers are stored as a 64-bit double, with an accuracy of 15 digits.

Functions and properties of numbers

isNaN(value)

Checks whether the object in the function parameter is a number or not. "NaN" stands for a "Not a Number".

Returns true or false according to if the parameter is a number.

toPrecision(x)

Truncates the number to the specified precision.

i.toString()

Converts the number to a string, so the number becomes a full-featured string.

toExponential(x)

Converts the number to the exponential (scientific) notation. E.g. for a value of 100 it'll be 1e2.

Number.MAX_VALUE and Number.MIN_VALUE

Returns the largest / smallest possible number which can be stored in JavaScript.

Math library

The Math library is one of the basic libraries in JavaScript. It contains very useful functions and properties, e.g. the number Pi, max(), exponential functions... We'll show there a few of them.

We use the dot operator to access the functions and variables of libraries:

Math.PI             // the number PI
Math.E              // the Euler's number
Math.LN10           // Logarithm 10
Math.SQRT2          // contains the square root of 2
Math.max(1,10)          // Returns the larger number. Opposite is the min() function
Math.pow(4,3)           // 4^3 == 64
Math.sqrt(9)            // square root
Math.random()           // random number 0 - 1
Math.abs(x)         // absolute value of the number
Math.round(x)           // rounds using the usual rules
Math.ceil(x)            // rounds always up
Math.floor(x)           // rounds always down
Math.cos(x)             // cosine
Math.sin(x)         // sine
Math.log(x)             // natural logarithm (the base is the Euler's number)

Boolean

A logical data type, it can have only two values 0 or 1 (true or false). Its value is either true or false. It's being used to evaluate conditions and loops, we'll get to it in further lessons.

Null / Undefined

Both data types stand for an empty variable. However, there's a difference. Null is a non-created object, but Undefined is not an object at all.

And that's all for today. In the next lesson, Conditions in JavaScript, we'll look into conditions and our applications will get just a little bit more interesting :)


 

Previous article
Getting started with JavaScript - First scripts
All articles in this section
JavaScript Basic Constructs
Skip article
(not recommended)
Conditions in JavaScript
Article has been written for you by David Capka Hartinger
Avatar
User rating:
8 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities