Preparation
πŸ’‘ ⏐ JavaScript Questions
2. Data types

JavaScript Data Types: Arrays, Objects, and Strings

Understanding data types in JavaScript, including arrays, objects, and strings, is fundamental for front-end and back-end development. Let's explore each of these data types:

1. Arrays:

  • Definition: Arrays are ordered collections of values, indexed by numeric positions starting from 0.
  • Declaration: Arrays can be declared using square brackets [].
  • Example:
    let numbers = [1, 2, 3, 4, 5]
    let fruits = ['apple', 'banana', 'orange']
  • Accessing Elements: Elements in an array can be accessed using square bracket notation and the index of the element.
    console.log(fruits[0]) // Output: 'apple'
  • Common Methods:
    • push(): Adds elements to the end of an array.
    • pop(): Removes the last element from an array.
    • slice(): Returns a shallow copy of a portion of an array.
    • forEach(): Executes a provided function once for each array element.

2. Objects:

  • Definition: Objects are collections of key-value pairs, where each key is unique.
  • Declaration: Objects can be declared using curly braces {}.
  • Example:
    let person = {
      name: 'John',
      age: 30,
      city: 'New York',
    }
  • Accessing Properties: Properties of an object can be accessed using dot notation or square bracket notation.
    console.log(person.name) // Output: 'John'
    console.log(person['age']) // Output: 30
  • Common Methods:
    • Object.keys(): Returns an array of a given object's own enumerable property names.
    • Object.values(): Returns an array of a given object's own enumerable property values.
    • Object.entries(): Returns an array of a given object's own enumerable property [key, value] pairs.

3. Strings:

  • Definition: Strings are sequences of characters enclosed in single or double quotes.
  • Example:
    let message = 'Hello, world!'
  • Accessing Characters: Individual characters in a string can be accessed using bracket notation and the index of the character.
    console.log(message[0]) // Output: 'H'
  • Common Methods:
    • toUpperCase(): Returns the string converted to uppercase.
    • toLowerCase(): Returns the string converted to lowercase.
    • split(): Splits a string into an array of substrings based on a specified separator.
    • substring(): Returns the part of the string between the start and end indexes.

Conclusion:

Understanding data types like arrays, objects, and strings is essential for manipulating and working with data in JavaScript. By mastering these data types, you'll be better equipped to write efficient and concise code for your web applications.