Practice Exercises for Mastering "Good Strings" in JavaScript

Anmol singhAnmol singh
3 min read

Practice Qs Understanding "Good Strings" in JavaScript

In programming, string manipulations are among the most common tasks. Let's dive into an interesting problem statement: identifying whether a string is a "good string" based on specific criteria. This blog will explore the concept, explain the conditions, and implement the solution using JavaScript.


What Is a "Good String"?

A "good string" is defined as:

  1. A string that starts with the letter 'a' (in lowercase).

  2. A string with a length greater than 3.

If a string satisfies both these conditions, it is a "good string." Otherwise, it is not.


Breaking Down the Problem

Condition 1: Starts with 'a'

The first character of the string must be 'a' (in lowercase). You can access the first character of a string using indexing:

str[0] === 'a';

Examples:

  • "apple" starts with 'a' – True.

  • "snake" does not start with 'a' – False.


Condition 2: Length Greater Than 3

The length of the string must be greater than 3. You can find the length of a string using:

str.length > 3;

Examples:

  • "apple" has a length of 5 – True.

  • "app" has a length of 3 – False.

  • Apple = 5 Good string

    Am = 3 Bad string


Combining the Conditions

To determine whether a string is "good," both conditions must be true. This is where the logical && (AND) operator comes into play:

if ((str[0] === 'a') && (str.length > 3)) {
    console.log("Good String");
} else {
    console.log("Not a Good String");
}

Implementing the Solution

Example 1: String = "apple"

let str = "apple";

if ((str[0] === 'a') && (str.length > 3)) {
    console.log("Good String");
} else {
    console.log("Not a Good String");
}

Output:

Good String

Example 2: String = "app"

let str = "app";

if ((str[0] === 'a') && (str.length > 3)) {
    console.log("Good String");
} else {
    console.log("Not a Good String");
}

Output:

Not a Good String

Example 3: String = "snake"

let str = "snake";

if ((str[0] === 'a') && (str.length > 3)) {
    console.log("Good String");
} else {
    console.log("Not a Good String");
}

Output:

Not a Good String

Practice Question

Predict the output of the following code:

let num = 12;

if ((num % 3 === 0) && ((num + 1 === 15) || (num - 1 === 11))) {
    console.log("Safe");
} else {
    console.log("Unsafe");
}

Explanation

  1. num % 3 === 0 evaluates to true (12 is divisible by 3).

  2. (num + 1 === 15) evaluates to false (12 + 1 = 13, not 15).

  3. (num - 1 === 11) evaluates to true (12 - 1 = 11).

  4. The overall condition true && (false || true) simplifies to true.

Output:

Safe

0
Subscribe to my newsletter

Read articles from Anmol singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anmol singh
Anmol singh