Search⌘ K
AI Features

JavaScript Basics

Explore core JavaScript fundamentals including primitive and reference data types like strings, numbers, booleans, objects, arrays, functions, and dates. Understand type checking with typeof and explicit type conversions. This lesson equips you with foundational knowledge needed to build front-end applications with plain JavaScript.

Data types

JavaScript has three primitive datatypesstring, number, and boolean. There are five reference datatypesObject, Array, Function, Date, and RegExp. Arrays, functions, dates, and regular expressions are special types of objects, but conceptually, dates and regular expressions are primitive data values and happen to be implemented in the form of wrapper objects.

Below, we have an example of JS data types:

Javascript (babel-node)
let string = "Johnson"; // String
let number = 16; // Number
let bool = true; // Boolean
let object = {firstName:"John", lastName:"Doe"}; // Object
let array = ['Jim', 'Shawna']; // Array
function func() { return (5 * 19); } // Function
let date = new Date() // Date
console.log("String is: " + string)
console.log("Number is: " + number)
console.log("Object is: " + object.firstName + " " + object.lastName)
console.log("Array is: " + array)
console.log("Function is: " + func())
console.log("Date is: " + date.toUTCString())

String data

A string is a sequence of Unicode characters. String literals, like "Hello world!", 'A3F0', or the empty string "" are enclosed in single or double quotes. Two string expressions can be concatenated with the + operator and checked for equality with the triple equality operator.

The number of characters in a string can be obtained by applying the length attribute to a string. The following example will help us understand the use of the length attribute.

Javascript (babel-node)
let firstName = "James"
let lastName = "Bond"
if (firstName + lastName === "JamesBond")
console.log("The length of first name is: ", firstName.length)
else
console.log("Failed")

Numeric data

All numeric data values are represented in 64-bit floating-point format with an optional exponent (like in the numeric data literal 3.1e10). There’s no explicit type distinction between integers and floating-point numbers. If a numeric expression cannot be evaluated to a number, its value is set to NaN (not a number), which can be tested with the built-in predicate isNaN(expr).

Javascript (babel-node)
//checking NaN
function milliseconds(x) {
if (isNaN(x)) {
return 'Not a Number!';
}
return x * 1000;
}
console.log(milliseconds('100F'));
console.log(milliseconds('0.0314E+2'));

The built-in function, Number.isInteger, allows testing if a number is an integer. For making sure that a numeric value is an integer or that a string representing a number is converted into an integer, one has to apply the built-in function parseInt.

Similarly, a string representing a decimal number can be converted into a number with parseFloat. To convert the nn number into a string, the best method is using toString(n).

Javascript (babel-node)
//checking is integer
function check(x, y) {
if (Number.isInteger(y / x)) {
return 'Integer!';
}
return 'Not an integer!';
}
console.log(check(5, 10));
console.log(check(5, 11));
let a = parseInt(10.00) // Parsing float to int
let b = parseFloat('10') // Parsing string to float
let c = toString(15) // Parsing number to string
console.log("Type of a is: " + typeof a)
console.log("Type of b is: " + typeof b)
console.log("Type of c is: " + typeof c)

Boolean data

There are two predefined boolean data literals, true and false. The boolean operator symbols are the exclamation mark (!) for NOT, the double ampersand (&&) for AND, and the double bar (||) for OR.

When a non-boolean value is used in a condition or as an operand of a boolean expression, it’s implicitly converted into a boolean value according to the following rules:

  • The empty string, the numerical data literal of 0, as well as undefined and null are all mapped to false.
  • All other values are mapped to true.

This conversion can be performed explicitly with the help of the double negation operation, like in the equality test !!undefined === false, This equality test evaluates to true.

Javascript (babel-node)
function check() {
if (!!undefined === false) {
return 'true!';
}
return 'false!';
}
console.log(check());

Date and time

In addition to strings, numbers, and boolean values, calendar dates and times are also important types of primitive data values. These aren’t implemented as primitive values, but rather in the form of wrapper objects instantiating Date.

Notice that Date objects don’t, in fact, really represent dates, but rather date-time instants represented internally as the number of milliseconds since 1 January, 1970 UTC.

For converting the internal value of a Date object into a human-readable string, we have several options. The two most important options are using either the standard format of ISO date-time strings of the form 2015-01-27, or localized formats of date-time strings like "27.1.2015" (for simplicity, we have omitted the time part of the date-time strings in these examples).

When x is an instance of Date (x instanceof Date), then x.toISOString() provides the ISO date-time string, and x.toLocaleDateString() provides the localized date-time string. For any date string ds, ISO or localized, new Date(ds) creates a corresponding date object.

Javascript (babel-node)
let date = new Date() // Date
console.log("Date is: " + date)
console.log("Date is: " + date.toISOString())
console.log("Date is: " + date.toLocaleDateString())
console.log("Date is: " + date.toUTCString())

The typeof operator

We can use the typeof operator to test whether a variable v holds a specific type of value. For instance, using typeof v === "number", we can check whether v is of the type number. The types of variables, array elements, function parameters, and return values are not declared, and are usually not checked by JS engines. Type conversion (casting) is performed automatically.

The value of a variable may be any of these:

  • A data value that’s either a string, a number, or boolean.
  • An object reference that is either referencing an ordinary object or an array, function, date, or regular expression.
  • The special data value null is typically used as a default value for initializing an object variable.
  • The special data value undefined is the implicit initial value of all variables that have been declared but not initialized.

The following example will help us understand the typeof operator:

Javascript (babel-node)
// "string"
let a="Educative"
// "number"
let num=25
// "undefined"
let variable
//object
let object = {firstName:"John", lastName:"Doe"}
console.log(typeof a)
console.log(typeof num)
console.log(typeof variable)
console.log(typeof object)

Type conversions

We can perform explicit conversions between the different data types in the following ways:

Type conversion

Type

Convert to string

Convert string to type

Boolean

String(x)

Boolean(y)

Number (floating point) 

String(x)

parseFloat(y)

Integer

String(x)

parseInt(y)

Object

x.toString() or JSON.stringify(x)

JSON.parse(y)

Array

x.toString() or JSON.stringify(x)

y.split() or JSON.parse(y)

Function

x.toString()

new Function(y)

Date

x.toISOString()

new Date(y)

RegExp

x.toString()

new RegExp(y)