logo
logo

Types Cheatsheet

Numbers

In JavaScript, numbers can be integers or floats. To identify the type of a number in JavaScript, use the
typeof
keyword followed by the number you want to check. Here's an example:
console.log(typeof 10); // Output: "number"
console.log(typeof 10.999); // Output: "number"
To perform basic arithmetic operations, you can use the standard math operators such as
+
,
-
,
*
,
/
, and
%
. Here's an example:
console.log(10 + 6); // Output: 16
console.log(10 - 6); // Output: 4
console.log(10 * 6); // Output: 60
console.log(10 / 6); // Output: 1.6666666666666667
console.log(10 % 6); // Output: 4
You can also use the built-in
Math
object to perform more complex mathematical operations. Here's an example:
console.log(Math.random()); // Output: a random number between 0 and 1
console.log(Math.PI); // Output: 3.141592653589793

Strings

In JavaScript, strings are sequences of Unicode characters and are enclosed in either single or double quotes. To identify the length of a string, use the built-in
length
property.
console.log("hello".length); // Output: 5
To concatenate strings, use the
+
operator.
console.log("hello" + " world"); // Output: "hello world"
To convert a string to uppercase, use the
toUpperCase()
method.
console.log("hello".toUpperCase()); // Output: "HELLO"
You can also access individual characters within a string using the
charAt()
method.
console.log("hello".charAt(0)); // Output: "h"

Booleans

In JavaScript, booleans can be either
true
or
false
. You can check whether a value is a boolean using the
typeof
keyword.
console.log(typeof true); // Output: "boolean"
You can also convert other data types to booleans using the
Boolean()
constructor.
console.log(Boolean(0)); // Output: false
console.log(Boolean("hello")); // Output: true

Falsy Values

When JavaScript expects a Boolean value, such as in an if statement or a while loop, certain values will be automatically converted to false. These are considered "falsy values".

The following are the falsy values:

  • false - The Boolean value of false is obviously falsy.

  • 0 - The number 0 is also falsy. This includes 0 as an integer or as a float.

  • nulll and undefined

  • NaN - The Not-a-Number (NaN) value is considered falsy. This occurs when you try to perform an operation that is not valid in JavaScript, such as dividing a string by a number.

  • "" (empty string) - An empty string is falsy, as it has no value.

Initializing objects with object literal syntax

Object literal syntax is a shorthand way to create an object with its name-value pairs. To initialize an object with object literal syntax, you can create an empty object and then add the name-value pairs in curly braces. Here's an example:

let myObject = {}; // create an empty object
myObject.key1 = 'value1'; // add a key-value pair
myObject.key2 = 'value2'; // add another key-value pair

Another way to create an object with object literal syntax is to create the object with its name-value pairs at the same time. Here's an example:

let myOtherObject = {
  key1: 'value1',
  key2: 'value2'
};

Adding key-value pairs to an object

To add a key-value pair to an object, you can use the dot notation or the square bracket notation. Here's an example using the dot notation:

myObject.key3 = 'value3'; // add another key-value pair using the dot notation

Here's an example using the square bracket notation:

myObject['key4'] = 'value4'; // add another key-value pair using the square bracket notation

Creating an object using the new keyword

You can also create an object using the new keyword, but this method is not recommended as it is more tedious. Here's an example:

let myObject = new Object(); // create an object using the new keyword
myObject.key1 = 'value1'; // add a key-value pair

Accessing values in an object

To access a value in an object, you can use the dot notation or the square bracket notation. Here's an example using the dot notation:

console.log(myObject.key1); // logs 'value1'

Here's an example using the square bracket notation:

console.log(myObject['key1']); // logs 'value1'

Using nested objects

You can also have objects inside other objects, which is known as nested objects. To access a nested value, you can chain the dot or square bracket notation. Here's an example:

let myObject = {
  name: 'John',
  contact: {
    email: '[email protected]',
    phone: '123-456-7890'
  }
};

console.log(myObject.contact.email); // logs '[email protected]'
console.log(myObject['contact']['phone']); // logs '123-456-7890'

Constructor Functions

Constructor functions are a way to create objects using a function. Here's an example of how you can create an object using a constructor function:

function Person(name, age, address) {
  this.name = name;
  this.age = age;
  this.address = address;
}

const johnDoe = new Person('John Doe', 30, {
  street: '123 Main St',
  city: 'Anytown',
  state: 'CA',
  zip: '12345'
});

console.log(johnDoe.name); // Output: John Doe
console.log(johnDoe.address.city); // Output: Anytown

In this example, we created a constructor function called "Person". This function takes three parameters: "name", "age", and "address". We used the "this" keyword to assign values to the object that we're creating. To create an object using this constructor function, we used the "new" keyword followed by the name of the function.

Declaring Functions Inside Objects

You can declare functions inside objects to create methods. Here's an example of how you can declare a function inside an object:

const calculator = {
  add: function(num1, num2) {
    return num1 + num2;
  },
  subtract: function(num1, num2) {
    return num1 - num2;
  }
};

console.log(calculator.add(2, 3)); // Output: 5
console.log(calculator.subtract(5, 3)); // Output: 2

In this example, we created an object called "calculator" with two methods: "add" and "subtract". We declared these methods as functions inside the object. To call these methods, we used dot notation followed by the name of the method and the arguments inside the parentheses.

Using the "this" Keyword

The "this" keyword refers to the current object, which is the object that the current code is executing inside of. The object is determined dynamically at runtime, based on the context of the function call.

When used inside an object, the "this" keyword allows you to access the object's properties and methods from within the object itself. This is particularly useful when you want to create methods that can be called on multiple instances of the same object, as it allows you to reference the specific instance that the method is being called on.

For example, if you have an object that represents a person and has properties such as name, age, and gender, you can define a method on that object to greet the person by name. Here's an example:

const person = {
  name: "John",
  age: 30,
  gender: "male",
  greet: function() {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet(); // outputs: "Hello, my name is John"

In this example, the "greet" method is defined on the "person" object, and uses the "this" keyword to access the person's name property. When the "greet" method is called, it outputs a message that includes the person's name.

What is an array in JavaScript?

An array is a special type of object in JavaScript that allows you to store a collection of values. The values in an array can be of any data type, including numbers, strings, booleans, and even other arrays. You can think of an array as a container that holds a group of related values.

Accessing elements in an array using indexing

In JavaScript, arrays are indexed starting from 0. This means that the first element in an array has an index of 0, the second element has an index of 1, and so on. To access an element in an array, you can use square brackets with the index of the element you want to access. For example, if you have an array called
myArray
and you want to access the second element, you can do
myArray[1]
(remember, arrays are 0-indexed).

Finding the length of an array

You can find the length of an array in JavaScript using the
length
property. The
length
property returns the number of elements in the array. For example, if you have an array called
myArray
, you can find its length by using
myArray.length
.

Declaring an array

There are two ways to declare an array in JavaScript. The first way is to use the array literal notation, which is a pair of square brackets with the elements inside, separated by commas. For example:

const myArray = [1, 2, 3, 4, 5];
The second way to declare an array is to use the
Array()
constructor function. For example:
const myArray = new Array(1, 2, 3, 4, 5);

However, using the array literal notation is generally preferred.

Adding and removing elements

You can add elements to an array in JavaScript using the
push()
method. The
push()
method adds one or more elements to the end of an array. For example:
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
You can also remove elements from an array using the
pop()
method. The
pop()
method removes the last element from an array and returns that element. For example:
const myArray = [1, 2, 3, 4];
const lastElement = myArray.pop();
console.log(lastElement); // Output: 4
console.log(myArray); // Output: [1, 2, 3]

Sorting arrays

You can sort an array in JavaScript using the
sort()
method. The
sort()
method sorts the elements of an array in place and returns the sorted array. By default, the
sort()
method sorts elements alphabetically. For example:
const myArray = ['banana', 'apple', 'orange'];
myArray.sort();
console.log(myArray); // Output: ['apple', 'banana', 'orange']

Concatenating arrays

We can concatenate two or more arrays together using the
concat
method. For example:
const namesArray = ["Jake", "Amy", "Kimi"];
const otherNames = ["Pete", "Mary Jane"];
const concatenatedArray = namesArray.concat(otherNames);
console.log(concatenatedArray); // ["Jake", "Amy", "Kimi", "Pete", "Mary Jane"]

Slicing an array

We can create a subarray from an existing array using the
slice
method. The
slice
method takes two arguments: the starting index and the ending index (not inclusive). For example:
const myArray = ["apple", "banana", "orange", "grape"];
const slicedArray = myArray.slice(1, 3);
console.log(slicedArray); // ["banana", "orange"]

Joining array elements

We can turn an array into a string using the
join
method. The
join
method takes a separator as an argument. For example:
const myArray = ["apple", "banana", "orange", "grape"];
const joinedArray = myArray.join(", ");
console.log(joinedArray); // "apple, banana, orange, grape"

Reversing arrays

Another useful method available to arrays is
Array.prototype.reverse()
. This method reverses the order of the elements in an array, which can be useful in certain situations. For example:
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers);
This will output
[5, 4, 3, 2, 1]
, which is the reversed order of the original array.
It's important to note that the
reverse()
method actually modifies the original array, so if we try to access the original array after calling
reverse()
, it will be in its reversed state.

Using arrays with objects

A common use case for arrays and objects together is in creating dynamic user interfaces, such as those found in web applications. For example, suppose we have a web page that displays a list of articles. Each article consists of several pieces of data, including the article title, author, date published, and content. We can represent this data using an array of objects:

const articles = [
  {
    title: "Article 1",
    author: "John Doe",
    date: "2023-02-21",
    content: "Lorem ipsum dolor sit amet...",
  },
  {
    title: "Article 2",
    author: "Jane Smith",
    date: "2023-02-20",
    content: "Sed ut perspiciatis unde omnis iste natus error...",
  },
  {
    title: "Article 3",
    author: "Bob Johnson",
    date: "2023-02-19",
    content: "At vero eos et accusamus et iusto odio dignissimos...",
  },
];
Here, we have an array called
articles
that contains three objects, each representing an article. By iterating over this array, we can generate HTML elements that display the article title, author, date, and content. We can also use JavaScript to add or remove articles from the array, allowing us to create a dynamic and interactive user interface.

Complex Data Sets

Another use case for arrays and objects together is in handling complex data sets, such as those found in APIs or database queries. For example, suppose we have an API that returns a list of customer orders. Each order consists of several pieces of data, including the customer's name, the order ID, the order date, the products ordered, and the total price. We can represent this data using an object that contains arrays for the products and the order details:

const order = {
  customerName: "John Doe",
  orderID: 123456,
  orderDate: "2023-02-22",
  products: [
    { name: "Product 1", price: 9.99 },
    { name: "Product 2", price: 19.99 },
    { name: "Product 3", price: 29.99 },
  ],
  totalPrice: 59.97,
};
Here, we have an object called
order
that contains several properties, including
customerName
,
orderID
,
orderDate
,
products
, and
totalPrice
. The
products
property is an array that contains three objects, each representing a product in the order. By structuring our data in this way, we can easily access and manipulate individual pieces of information, such as the customer's name or the price of a specific product.