JavaScript: Reverse the Words in a Sentence without Built-in Function

1. Introduction

Reversing the order of words in a sentence is a common problem in text processing and manipulation. This task can help in various applications like natural language processing and data preparation. In this tutorial, we will explore a method to reverse the words in a sentence using JavaScript without relying on the built-in reverse() method.

2. Program Overview

We will define a function called reverseWords. The function will break the sentence into words, and then construct a new sentence by placing the words in reverse order.

3. Code Program

// Function to reverse the order of words in a sentence
function reverseWords(sentence) {
    // Split the sentence into an array of words using space as a delimiter
    let words = sentence.split(' ');

    // Initialize an empty string to store the reversed sentence
    let reversedSentence = '';

    // Iterate over the words array from end to start
    for (let i = words.length - 1; i >= 0; i--) {
        reversedSentence += words[i] + (i !== 0 ? ' ' : '');
    }

    // Return the sentence with the order of words reversed
    return reversedSentence;
}

// Test the function
let testSentence = "This is a sample sentence";
let result = reverseWords(testSentence);  // Expected: 'sentence sample a is This'

console.log(result);

Output:

sentence sample a is This

4. Step By Step Explanation

1. Function Definition: We start by defining a function named reverseWords which accepts a sentence parameter.

2. Splitting Sentence into Words: Within the function, we use the split(' ') method to split the sentence into an array of words.

3. Reversing Logic: We initialize an empty string reversedSentence. We then iterate through the words in reverse order using a for loop, and for each word, we append it to our reversedSentence string.

4. Joining the Words: As we append each word, we also append a space, except for the last word to ensure our sentence is spaced correctly.

5. Return Result: The function returns the reversedSentence.

6. Test: We test the function with a sample sentence and output the result using console.log.

This approach allows us to reverse the words in a sentence, showcasing the power of string manipulation in JavaScript without relying on built-in methods.

Comments