Introduction
In JavaScript, you can easily join an array of words into a single string using the join() method. This method concatenates all the elements of an array into a string, separated by a specified delimiter (such as a space or comma). Joining arrays is a common task, especially when dealing with sentences or phrases.
Problem Statement
Create a JavaScript program that:
- Accepts an array of words.
- Joins the array elements into a single string, separated by spaces.
- Returns and displays the resulting string.
Example:
Input:
["Hello", "world", "this", "is", "JavaScript"]Output:
"Hello world this is JavaScript"Input:
["JavaScript", "is", "fun"]Output:
"JavaScript is fun"
Solution Steps
- Read the Input Array: Provide an array of words either as user input or directly in the code.
- Join the Array: Use the
join()method to concatenate the array elements, separated by a space. - Display the Result: Print the resulting string.
JavaScript Program
// JavaScript Program to Join an Array of Words into a String
// Author: https://www.javaguides.net/
function joinArrayIntoString(arr) {
// Step 1: Join the array into a string with space as a separator
let result = arr.join(' ');
// Step 2: Return the resulting string
return result;
}
// Example input
let wordsArray = ["Hello", "world", "this", "is", "JavaScript"];
let resultString = joinArrayIntoString(wordsArray);
console.log(`The joined string is: "${resultString}"`);
Output
The joined string is: "Hello world this is JavaScript"
Example with Different Input
let wordsArray = ["JavaScript", "is", "fun"];
let resultString = joinArrayIntoString(wordsArray);
console.log(`The joined string is: "${resultString}"`);
Output:
The joined string is: "JavaScript is fun"
Explanation
Step 1: Join the Array
- The
join()method concatenates all the elements of the array into a single string, with each word separated by a space (' '). You can customize the delimiter if needed (e.g., comma, hyphen).
Step 2: Return and Display the Result
- The resulting string is returned by the function and printed using
console.log().
Conclusion
This JavaScript program demonstrates how to join an array of words into a single string using the join() method. This approach is efficient and easy to use, allowing you to combine elements of an array into a readable string for various use cases such as constructing sentences, formatting output, or generating text dynamically.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment