A Guide: Understanding JavaScript Data Types.

A Guide: Understanding JavaScript Data Types.

An article tailored for beginners, to deeply understand data types as in JavaScript. it's core concepts, and how JavaScript process and manages data.

Data types are the foundational blocks of any programming language upon which structures of codes are built. It’s practically impossible to erect a structure of codes without understanding the basic data types needed at the foundation for the structures.

This article explains in detail the various kinds of data types needed to construct codes in JavaScript.

Prerequisite

To be able to fully comprehend this article, you must have at least heard about HTML and CSS and looking to delve into JavaScript.

Understanding the Meaning of Data Types

A data type is a classification or categorization of data that determines the kind of values it can hold and the operations that can be performed on those values. It specifies the size, format, and range of values that can be stored in a variable.

Data types are essential in programming languages because they define how the computer interprets and manipulates data. They provide a structure and set of rules for storing and interacting with data, ensuring that operations are performed correctly and efficiently.

Different programming languages have their own sets of data types, Each data type has its own characteristics and behavior, including the kind of values it can hold, the operations that can be performed on it, and any restrictions or rules associated with it.

Importance of data types

Data types are important for ensuring data integrity, preventing type-related errors, and enabling efficient memory allocation and storage. By using appropriate data types, developers can accurately represent and manipulate data in their programs, leading to reliable and efficient code execution.

Understanding Data Types in JavaScript

In JavaScript, data types represent the kind of values that can be stored and manipulated in variables. JavaScript has several built-in data types, which can be categorized into two main categories: Primitive types and Reference types. Let's go through them one by one:

Primitive types and Reference types

Primitive types:

  1. Number: Represents numeric values. It can be integers or decimal numbers.

  2. String: Represents a sequence of characters enclosed in single quotes (' ') or double quotes (" ").

  3. Boolean: Represents a logical value, either true or false. They’re mostly used for evaluating conditions

  4. Null: Represents the intentional absence of any object value. To explicitly set a variable with no value.

  5. Undefined: Represents a variable that has been declared but has not been assigned a value.

  6. Symbol: Represents a unique identifier and is primarily used for creating unique property keys.

Reference types:

  1. Object: Represents a collection of key-value pairs, where values can be of any data type. Objects are created using curly braces {} and can be accessed using dot notation (.) or bracket notation ([]).

  2. Array: Represents an ordered list of values, which can be of any data type. Arrays are created using square brackets [] and can be accessed using numerical indices.

  3. Function: Represents reusable blocks of code that can be called with arguments to perform a specific task.

Numbers

Represents numeric values. It can be integers or decimal numbers.

Math Operator:

Operator

Name

Function

+

Plus

To add

-

Minus

To subtract

Asterisk

To multiply

/

Forward Slash

To divide

*

Double Asterisk

Power of

%

Percentage

Remainder

Note: This is Asterisk (*) and this is a double Asterisk (**), Don't know why it didn't display in the table.

Example 1:

let books = 10;
let pens = 15;
const result = books + pens;
console.log(result); output -> 25

Example 2:

let books = 10;
let result = books % 3;
console.log(result); output -> 1

Example3:

let radius = 10;
const pi = 3.14;
const result = pi * radius**2;
console.log(result) output -> 314

Increment and Decrement:

How to increase or decrease values.

Example 1:

let pens = 10;
pens++;
console.log(pens); output -> 11
//The value of pens increases by 1

Example 2:

let pens = 10;
pens11;
console.log(pens); output -> 9
//The value of pens decreases by 1

Example 3:

let likes = 10;
likes  += 10; console.log(likes) output -> 20 // 10 is added to the value of likes. 
likes  -= 10; console.log(likes) output ->  0 // 10 is subtracted to the value of likes. 
likes  *= 3; console.log(likes) output -> 30 // 3 multiplicities the value of likes. 
likes  /= 2; console.log(likes) output -> 5 // 2 divides the value of likes.

NaN - Not a Number:

JavaScript returns “NaN” when we attempt to perform mathematical operations on non-numeric values or invalid calculations.

For example: console.log(5 / ‘hello’);

String

A string is a data type used to represent a sequence of characters. It is commonly used to store and manipulate text-based data. Strings are enclosed in either single quotes (' ') or double quotes (" ") in JavaScript.

Creating a string:

Example:

let title = “book of influence”;

let author = ‘john doe’;

//the title variable hold a double quote string, while the author variable holds a single quote string. Both are valid strings in JavaScript.

String Concatenation:

String concatenation is a way of combining two or more strings together using the ‘+’ sign.

Example:

let title = “book of influence”;

let author = ‘john doe’;

console.log(“the author’s name is” + author + “the title of the book is” + title).

Template Strings:

Template strings are a way to directly inject variables into strings. It uses the backticks symbol (``) found below the “Esc” key on your keyboard and uses “${}” to enclose the variable being injected.

Example:

let title = “book of influence”;

let author = ‘john doe’;

let likes = 250;

console.log(`the blog called ${title} by the author named ${author} has ${likes} likes.`);

String methods:

JavaScript provides a variety of built-in methods to manipulate and work with strings. Some commonly used methods include:

  • toUpperCase(),

  • toLowercase(),

  • substring(),

  • split(),

  • indexOf(),

  • replace(), and much more

Example:

let text = "Hello, world!";

console.log(text.toUpperCase()); output -> "HELLO, WORLD!"

console.log(text.indexOf("world")); output -> 7

console.log(text.replace("world", "JavaScript")); output -> "Hello, JavaScript!"

Boolean

Boolean data type represents a logical value that can be either true or false. Booleans are primarily used for decision-making and controlling the flow of program execution based on conditions.

Boolean Values: The Boolean data type has two possible values: true and false. These values are not strings or numbers but reserved keywords in JavaScript.

Example:

let truthy = True;

let falsy = false;

Comparison Operators:

Operator

Name

==

 Equal to

!=

Not Equal to

Greater Than

Less Than

>=

Greater or Equal to

<=

Less or Equal to

Example:

let age = 25;
console.log(age == 25) output -> True
//result is true because age is equal to 25.

console.log(age != 20) output -> True
//result is true because the value age is not equal to 20.

console.log(age > 30) output -> False
//result is false because the value of age is not greater than 30.

console.log(age < 30) output -> true
//result is true because the value of age is less than to 30.

console.log(age >= 15) output -> True
//result is true because age is greater than 15.

console.log(age <= 15) output -> False
//result is false because age is neither less than or equal to 15.

They’re two types of comparison operators, namely: Abstract or Loose Comparison and Strict Comparison.

Abstract Comparison: This means a value’s type is not considered when comparison is performed on them.

Abstract Comparison Operators:

“==”: Equal to

“!=” Not Equal to

Example:

Let age = 55;

console.log(age == 55) output -> True // Same data type (number), it returns True

console.log(age == “55”)output -> True // Different data type(number and string) still returns true.

With abstract comparison, JavaScript converts the string 55 to a number type, thus making them the same type.

Strict Comparison: means a value’s type is strictly considered when performing comparison (different types cannot be equal).

Strict Comparison Operators:

“===”: Equal to

“!==” Not Equal to

Example

let games = 60;

console.log(games === 60) output -> True

// Same data type (number), JavaScript returns True

console.log(games === “60”) output -> False

// Different data type(number and string) returns false.

Strict Comparison will always consider type equivalent when comparing, thus, those two equations above are not the same.

Null

Null is a special value that represents the intentional absence of any object value. It is a primitive data type that signifies the absence of a value or the absence of an assigned object.

Example:

let myVar = null;

can be assigned on a Boolean.

let myOptions = null;

console.log(myOptions === null) output -> True.

To check the type of data type, we use the “ typeof ” operator.

let myOptions = null;

console.log(typeof myOptions) output -> null.

Null is often used to explicitly indicate that a variable or object property has no assigned value. It can be helpful when you want to clear a variable's value or represent the absence of data in your program logic.

Undefined

Undefined is a primitive value that represents the absence of a value or the absence of an assigned value to a variable. It is a built-in constant and data type used to indicate the absence of a meaningful value.

Example**:**

let myOptions;

console.log(myOptions) output -> undefined

//the variable wasn’t assign any value.

We can also use the typeof operator here.

let myOptions;

console.log(typeof myOptions) output -> undefined.

Undefined is commonly used to indicate the absence or lack of a value. It can be useful for checking if a variable has been assigned a value, handling default values, and detecting uninitialized variables in your JavaScript code.

Objects

Objects are a fundamental data type used to store collections of key-value pairs. Objects allow you to represent complex entities, structures, and data models.

Object Literal: This is a basic composition or creation of objects enclosed in curly brasses {}.

Example:

const vehicle = {
type: “suv”,
make: “tesla”,
model: “roadster”,
year: 2020
}

Object Properties: Object Properties consist of a key (also known as a property name) and its corresponding value. The “key” is always a string and found at the left side of the colon, at the right side is the “value” and can be of any data type. That’s why objects are defined as “key-value pairs”.

Assessing Properties: We can access object properties with dot notation (.) or bracket notation ([]).

Example:

let person = {
name: “Johnson”,
age: 25,
occupation: “Teacher”
}
console.log( person.name ) output -> Johnson 
// the dot notation is used to access the name property.

console.log(person[occupation]) output -> Teacher
// the bracket notation is used to access the occupation property here.

Object Manipulation: Object properties can be modified, added, or deleted dynamically.

Example:

let person = {
name: “Johnson”,
age: 25,
occupation: “Teacher”
};

person.name = john;
console.log(person[name]) output -> john //name has been modified.

person.city = “Paris”;
console.log(person.city) output -> Paris  //a new property “city” has been added.

delete person.age;  // deleting the age property.

Methods: Object properties can also hold functions, known as methods. Methods allow objects to have behaviors or actions associated with them.

Example:

const vehicle = {
type: “SUV”,
make: “Tesla”,
model: “Roadster”,
year: 2020,
greet: function(){ //greet method
console.log(“Hello, congratulations on your ” + this.year + this.make + this.model+ “new car”);
   }
};

Vehicle.greet(); output -> Hello, congratulations on your 2020 Tesla Roadster new car

Objects are a powerful feature in JavaScript and are extensively used in the language. They allow for organizing and representing complex data structures and enable the creation of custom data models and behaviors. Objects are essential for building JavaScript applications, manipulating data, and working with APIs and libraries.

Arrays

Arrays are a special type of object used to store and manipulate a collection of elements. Arrays provide a way to organize and access multiple values using numerical indices.

Array Literal: This is a basic composition or creation of arrays enclosed in square brackets {}.

Example:

let stationeries = [“books”, “pens”, “rulers”, “pencils”];

// this is how to create a basic array.

Array Length: Arrays have a length property that represents the number of elements in the array. Elements in an array are stored at sequential numeric indices, starting from 0 for the first element. To get the length of an array we make use of the “length” keyword.

Example:

Let games = [“football”, “tennis”, “golf”, "race"];

console.log( games.length ) output -> 4

console.log( games[0]) output -> football.

Array Methods: JavaScript arrays come with a variety of built-in methods to perform common operations and to modify arrays dynamically, such as push(), pop(), shift(), unshift(), slice(), concat(), join(), sort(), and many more.

Examples:

let animals = [“goat”, “monkey”, ”tiger”, “rabbit”];

animals[2] = “leopard” //value of index[2] which is “tiger” has been modified to “leopard”.

.push: used for adding an element to the end of the array list

animals.push = (“cheetah”);

.pop: used for removing the last element on the list

animals.pop()

.unshift: used for adding an element at the beginning of the array list.

animals.unshift(“bear”)

.shift: used for removing the first element on the list

animals.shift()

.slice: to extract a portion of the array, providing the starting and end index values

let slicedAnimals = animals.slice(1, 3);

console.log( slicedAnimals ) output -> [“monkey”, ”tiger”, “rabbit”];

.join: to join arrays together into one using a given symbol. Converts arrays into string.

Let joinedAnimals = animals.join(“-”);

console.log(joinedAnimals) output -> = [“goat - monkey - tiger - rabbit”];

Arrays are widely used in JavaScript for storing and manipulating collections of data. They are versatile and offer a range of methods and operations to work with array elements efficiently. Arrays are essential for tasks such as data processing, iteration, filtering, sorting, and much more.

Functions

Functions in JavaScript are classified under the objects data types, they’re used to declare a block of code that is reuseable multiple times when the function is called or invoked.

Function Declaration: This is the act of declaring a function directly with the “function” keyword.

Example:

Function greet() {

console.log(“Hello World”) }

greet() //this is how a function is called or invoked.

Function Expression: This is the act of storing a function inside a constant variable.

Example:

const speak = function() {

console.log(“Good Day”) };

speak(); //invoking the function.

Arguments and Parameters: Arguments and parameters are the values passed into the function’s body. Parameters are passed while declaring a function, while arguments are the values passed when invoking the function.

Example:

Function vehicle(make){

console.log(“Hello the type of car is:” + make) }

vehicle(“Mercedes Benz”); output -> Hello the type of car is: Mercedes Benz

Return Statement: Functions can return values using the return statement. When a function encounters a return statement, it stops executing and returns the specified value.

Example:

function add(x, y) {

return x + y;

}

let result = add(2, 6);

console.log(result); output -> 8

Arrow Functions: Arrow functions provide a shorter syntax for declaring functions. They are anonymous functions that use the => arrow operator.

Example:

const calcArea = (radius) => {

return 3.14 radius*2

}

const result = calcArea(10);

console.log(result);

//while using the arrow function the “return” statement can be omitted, likewise the parameter’s brackets if it contains only one parameter, alongside the curly braces. The above code can be shorten further to

const calcArea = radius => 3.14 radius*2

const result = calcArea(10);

console.log(result);

Hoisting: functions are primarily declared before invocation takes place, but the act of invoking a function before declaring it, is called “hoisting”. Hoisting only works with function declaration (using the function keyword initially), it’s not allowed with function expression and arrow functions.

Example:

greet() // invoking the function before declaring it below.

Function greet() {

console.log(“Hello World”)

}

Callback Function: A callback function is a function that is passed as an argument to another function and is executed at a later point in time. The primary purpose of a callback function is to ensure that certain code executes only after a specific task or event has been completed.

Example:

const callbackFn = () => {

console.log(“my clothing accessories” + )

}

const clothing = function(callback) {

console.log(“callback executed”)

}

clothing(callbackFn)

In situations like event handling, asynchronous operations, and when interacting with functions that depend on the completion of an external job, callback functions are frequently employed. By passing a callback function, you can ensure that specific code runs only after the desired task is complete, allowing for flexibility and efficiency.

JavaScript Data Types Management

How JavaScript manages data types storage refers to the management of computer memory allocated to JavaScript programs, particularly the allocation and de-allocation of memory resources used by objects and variables during program execution.

Primitive types store their data in a stack while reference types stores their data in the heap memory. The space allocated to the stack is limited and data allocation is faster, the heap’s space is larger but it process is slower.

Stack and Heap

JavaScript dynamically allocates memory resources from a large region called the stack and the heap. This is where objects and variables reside during program execution. Objects are allocated on the heap and can reference other objects or variables.

When primitive type stores its data in the stack, it maintains the value in it, even if there exists a copy of that particular value. When a change is made, it only affects the original value.

Example:

let age = 25;

let newAge = age;

console.log(age, newAge); output -> 25, 25;

Both variables “age” and “newAge” holds the same value in the stack.

If “age” is modified to 35. The stack will only update “age” and “newAge” remains 25.

Example:

age = 35;

console.log(age, newAge); output -> 35, 25

When a reference type like an object is created, it stores its data in the heap and created a pointer to the stack holding the data.

Example:

const newUser = {name: john, age: 25}

If we say:

const newUser = userOne;

this creates a copy of the object into the stack. Whenever any of the values in the variable “newUser” or “userOne” is updated, it affects both variables as they’re pointing to the same object in the heap.

If we say:

newuser.age = 35;

both “newUser” and “userOne” will be updated to 35.

Conclusion

Understanding JavaScript data types intrinsically will help ground you a solid foundation in your web or software career, it’s very essential to understand data types to be able to code well in JavaScript and practically any programming language, understanding data types fully will give you an edge to mastering core fundamentals in coding.

Getting the hang of how JavaScript manages data is also imperative as it will shape how you code and formulate your solution to problems.

References

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management

https://www.digitalocean.com/community/tutorials/understanding-data-types-in-javascript