JS Objects Literals and Math Object

Practice Questions

  • QS1. Write a JS program to delete all occurrences of element 'num' in a given array.

    • Example: if arr = [1, 2, 3, 4, 5, 6, 2, 3] & num = 2, the result should be arr = [1, 3, 4, 5, 6, 3]

  • QS2. Write a JS program to find the number of digits in a number.

    • Example: if number = 287152, count = 6

  • QS3. Write a JS program to find the sum of digits in a number.

    • Example: if number = 287152, sum = 25

  • QS4. Print the factorial of a number n.

    • [Factorial of a number n is the product of all positive integers less than or equal to a given positive integer and denoted by that integer.]

    • Example:

      • 7! (factorial of 7) = 1x2x3x4x5x6x7 = 5040

      • 5! (factorial of 5) = 1x2x3x4x5 = 120

      • 3! (factorial of 3) = 1x2x3 = 6

      • 0! Is always 1

  • QS5. Find the largest number in an array with only positive numbers.

JS Objects Literals

  • Used to store keyed collections and complex entities.

  • property => (key, value) pair

  • Objects are a collection of properties

  • Example:
    let student = { name: "Shradha", age: 23, marks: 94.4, city: "Delhi" };

Thread / Twitter Post Object

  • Create an object literal for the properties of a thread/twitter post which includes:

    • username

    • content

    • likes

    • reposts

    • tags

  • Example:
    const post = { username: "@shradhakhapra", content: "This is my #firstPost", likes: 150, reposts: 5, tags: ["@apnacollege", "@delta"] };

Getting Values from Objects

  • obj["key"]

  • student["name"]

  • student.name

JavaScript Object Key Conversion

  • JS automatically converts object keys to strings.

  • Even if a number is used as a key, it will be converted to a string.

  • Example:
    let obj = { 1: 'a', 2: 'b', true: 'c', null: 'd', undefined: 'e' };

Adding/Updating Values in Objects

  • Example:
    const student = { name: "shradha", age: 23, marks: 94.4, city: "Delhi" };

  • Change the city to "Mumbai":
    student.city = "Mumbai";

  • Add a new property, gender: "Female":
    student.gender = "female";

  • Change the marks to "A":
    student.marks = "A";

Deleting Properties from Objects

  • Example:
    delete student.marks; delete student.city;

Object of Objects

  • Storing information of multiple students.

  • Example:
    const classInfo = { aman: { grade: "A+", city: "Delhi" }, shradha: { grade: "A", city: "Pune" }, karan: { grade: "0", city: "Mumbai" } };

  • Accessing values:
    javascript classInfo.shradha.city // Returns "Pune"

Array of Objects

  • Storing information of multiple students.

  • Example:
    const classInfo = [ { name: "aman", grade: "A+", city: "Delhi" }, { name: "shradha", grade: "A", city: "Pune" }, { name: "karan", grade: "0", city: "Mumbai" } ];

  • Accessing values:
    classInfo[1].name // Returns "shradha"

Math Object

  • Properties:

    • Math.PI: Represents the ratio of a circle's circumference to its diameter, approximately 3.14159.

    • Math.E: Euler's number, the base of the natural logarithm, approximately 2.718.

  • Methods:

    • Math.abs(n): Returns the absolute value of a number.

    • Math.pow(a, b): Returns the base a to the exponent b.

    • a ** b: Another way to calculate a^b

    • Math.floor(n): Returns the largest integer less than or equal to n.

    • Math.ceil(n): Returns the smallest integer greater than or equal to n.

    • Math.random(): Returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1).

Random Integers

  • Generating random integers from 1 to 10:

    1. let num = Math.random(); // Generates a random number between 0 and 1

    2. num = num * 10; // Scales the number to be between 0 and 10

    3. num = Math.floor(num); // Rounds the number down to the nearest integer

    4. num = num + 1; // Shifts the range to be between 1 and 10

  • One-liner:
    let random = Math.floor(Math.random() * 10) + 1;

Generating Random Numbers

  • Generate a random number between 1 and 100:
    Math.floor(Math.random() * 100) + 1;

  • Generate a random number between 1 and 5:
    Math.floor(Math.random() * 5) + 1;

  • Generate a random number between 21 and 25:
    Math.floor(Math.random() * 5) + 21;

Guessing Game

  • User enters a max number and then tries to guess a randomly generated number between 1 and max.

  • Example:

    const max = prompt("enter the max number");
    const random = Math.floor(Math.random() * max) + 1;
    let guess = prompt("guess the number");
    
    while (true) {
        if (guess == "quit") {
            console.log("user quit");
            break;
        }if (guess == random) {
        console.log("you are right! congrats!! random number was", random);
        break;
    } else if (guess < random) {
        guess = prompt("your guess was too small. please try again");
    } else {
        guess = prompt("your guess was too large. please try again");
    }
    }
    
  • Hints:

    • Provide hints to the user if their guess is too small or too large.

Assignment Questions

  • Qs1. Create a program that generates a random number representing a dice roll. [The number should be between 1 and 6].

  • Qs2. Create an object representing a car that stores the following properties for the car: name, model, color. Print the car's name.

  • Qs3. Create an object Person with their name, age, and city. Edit their city's original value to change it to "New York". Add a new property country and set it to the United States.