DEV Community

Cover image for Datatypes in JavaScript
Denismacharia
Denismacharia

Posted on • Updated on

Datatypes in JavaScript

What are data types in Javascript?

In Javascript, a data type is a classification of data that determines the type of values a variable can hold. Being a dynamic language, the data type in a variable can change at any point in the execution of instructions. This article will improve your knowledge in javascript data types.

The datatypes include;

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Object

Number

In JavaScript, the Number data type is used to represent both integers and floating-point numbers. Numbers can be written with or without a decimal point. For example, both 3 and 3.0 are considered to be numbers in JavaScript.

JavaScript uses a 64-bit floating-point representation for numbers, which means that it can represent large and small numbers with high precision. However, it also means that JavaScript may not be able to represent some numbers exactly. For example, the number 0.1 cannot be represented exactly in 64-bit floating-point format, and may be approximated when used in calculations.

JavaScript also has several special numeric values that are considered to be of the Number type. These include:

  • NaN (not a number): represents the result of a undefined or unrepresentable mathematical operation.
  • Infinity: represents positive infinity and negative infinity.
  • Infinity: represents negative infinity.

JavaScript also has several built-in methods and properties for working with numbers. These include:

  • The Number.isInteger() method can be used to check if a value is an integer.
  • The Number.isSafeInteger() method can be used to check if a value is a safe integer (a number that can be exactly represented by the built-in 'Number' type).
  • The Number.isNaN() method can be used to check if a value is NaN.
  • The Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER properties can be used to get the largest and smallest safe integers, respectively.
  • The Number.parseInt() and Number.parseFloat() methods can be used to parse a string and return an integer or floating-point number, respectively.
  • The Number.toFixed() method can be used to convert a number to a string with a specified number of decimal places.

There are potential limitations and behavior of numbers in JavaScript when performing mathematical operations, especially with decimals, and when dealing with large numbers where there is a possibility for error due to poor precision, overflow and underflow, and type coercion.

String

In JavaScript, the String data type represents a sequence of characters. Strings can be written with single or double quotes, and can contain any combination of letters, numbers, and special characters. For example, the following are all valid strings in JavaScript:

'hello world'

"hello world"

"123"

"Special characters: !@#"

Enter fullscreen mode Exit fullscreen mode

JavaScript provides several built-in methods for working with strings. These include:

  • The length property can be used to get the number of characters in a string.
  • The charAt() method can be used to get a specific character from a string by its index.
  • The indexOf() method can be used to find the first occurrence of a specified string within another string.
  • The lastIndexOf() method can be used to find the last occurrence of a specified string within another string.
  • The substring() method can be used to extract a portion of a string.
  • The slice() method can be used to extract a portion of a string, similar to substring
  • The split() method can be used to split a string into an array of substrings.
  • The replace() method can be used to replace a specified string or regular expression with another string.
  • The toUpperCase() and toLowerCase() methods can be used to convert a string to uppercase or lowercase, respectively.

It is important to keep in mind that strings in JavaScript are immutable, which means that once a string is created, its value cannot be changed. Any operations that appear to change a string actually create a new string with the desired modifications.

JavaScript also has a built-in object called String, which provides additional functionality for working with strings. For example, the String.prototype.concat() can be used to concatenate two or more strings together.

Boolean

In JavaScript, the Boolean data type is used to represent true or false values. A Boolean value can be either true or false, and is commonly used in conditional statements to check if a certain condition is true or false.

JavaScript provides several ways to create Boolean values. The simplest way is to use the keywords true and false, like so:

let isTrue = true;
let isFalse = false;
Enter fullscreen mode Exit fullscreen mode

You can also use logical operators to create Boolean values by combining multiple conditions. For example:

let result = (2 > 1) && (3 < 4);  
// result = true
let result2 = (2 > 1) || (3 < 2);  
// result2 = true
Enter fullscreen mode Exit fullscreen mode

You can also use comparison operators to create Boolean values by comparing two values. For example:

let isEqual = (2 == 2);  
// isEqual = true
let isNotEqual = (2 != 3);  
// isNotEqual = true
Enter fullscreen mode Exit fullscreen mode

JavaScript also provides several built-in methods and properties for working with Boolean values. These include:

  • The Boolean() function can be used to convert a value to a Boolean.
  • The ! operator can be used to negate a Boolean value, turning true into false and vice versa.
  • The && operator can be used to perform a logical "and" operation between two Boolean values.
  • The || operator can be used to perform a logical "or" operation between two Boolean values.

It is important to keep in mind that any value can be converted to a Boolean in JavaScript, even if it is not technically a Boolean value. For example, any number that is not 0 is considered to be true, and 0 is considered to be false.

Boolean values are commonly used in control flow statements such as if-else statements to represent true or false data.

Undefined

The undefined data type is used to represent the absence of an object or value.
In JavaScript, a variable can be declared without being assigned a value. In such cases, the variable is of type "undefined". For example:

let car;
console.log(typeof car);
 // Output: "undefined"
Enter fullscreen mode Exit fullscreen mode

It's also possible for a function to not return a value. In such cases, the return value of the function will be "undefined". For example:

function example() 
 // This function does not return a value
let result = example();
console.log(typeof result); 
// Output: "undefined"
Enter fullscreen mode Exit fullscreen mode

If you try to access the value of an undefined variable, a ReferenceError will be thrown. To avoid this, it's a good practice to check if a variable is undefined before attempting to access its value. You can use the typeof operator to check the data type of a variable, which will return "undefined" if the variable is of type "undefined". For example:

let car;
if (typeof car === "undefined") {console.log("car is undefined");
}
// Output: car is undefined
Enter fullscreen mode Exit fullscreen mode

It's important to note that undefined is a distinct value from null. null is used to represent an intentional non-value, while undefined is used to represent an absence of value or object.

Variables that have been declared but have not been assigned a value are of type undefined. To avoid errors, it's a good practice to check if a variable is undefined before accessing its value.

Null

The null datatype is used to represent intentional lack of a value. It can be assigned to a variable or used as the value of an object property.

let a = null;
console.log(typeof a); 
// Output: "object"
Enter fullscreen mode Exit fullscreen mode

It's important to note that, although typeof returns object for null, null is not an object. It is a special value that represents the absence of an object.

You can use the null value to explicitly set the value of an object property to an intentional non-value. For example:

let employee = {
  name: "Kendrick",
  age: 20,
  occupation: null
};
console.log(employee.occupation); 
// Output: null
Enter fullscreen mode Exit fullscreen mode

When checking for the absence of a value or object, it is recommended to use null instead of undefined. This is because undefined can have different meanings in different situations, such as:

  • When a variable has been declared but not assigned a value
  • When a function does not return a value
  • When an object property does not exist null always represents an intentional non-value, making it a more reliable and meaningful value to use when checking for the absence of a value or object.

Object

In JavaScript, the "object" data type is a collection of properties, each of which can hold a value of any data type, including primitive data types and other objects. An object is an instance of the Object class and can be created using the object literal notation or the Object constructor.

Object Literal Notation:

let employee = {
  name: "Kendrick",
  age: 20,
  occupation: "Developer"
};
Enter fullscreen mode Exit fullscreen mode

Object Constructor:

let employee = new Object();
employee.name = "Kendrick";
employee.age = 30;
employee.occupation = "Developer";
Enter fullscreen mode Exit fullscreen mode

In an object, properties are identified by keys, which are strings, and values, which can be of any data type. Properties can be added, modified, or removed using the dot notation or the square bracket notation.

Dot Notation:

employee.address = "1234 mstreet";
console.log(employee.address); 
// Output: "1234 mstreet"
Enter fullscreen mode Exit fullscreen mode

Square Bracket Notation:

employee["phoneNumber"] = "555-555-5555";
console.log(employee["phoneNumber"]); 
// Output: "555-555-5555"
Enter fullscreen mode Exit fullscreen mode

Objects can also have methods, which are functions that are properties of an object. For example:

let employee = {
  name: "Kendrick",
  age: 20,
  occupation: "Developer",
  sayHello: function() {
    console.log(`Hello, my name is ${this.name}.`)
;}
};

employee.sayHello(); 
// Output: "Hello, my name is John Doe."
Enter fullscreen mode Exit fullscreen mode

In JavaScript, objects can also be used as associative arrays, where the keys can be used as indices to access the values. This can be useful for storing collections of data where the keys are unique identifiers.

Javascript is an interesting language that has a lot of capabilities. Developers looking to perfect their javacript skills need to understand Javascript datatypes and make sure they avoid issues that are associated with each datatype for fast, reliable and easily debuggable code.

Top comments (1)

Collapse
 
ondiek profile image
Ondiek Elijah

Great piece 🚀🎊✨