concat array of strings javascript code example

Example 1: javascript array to comma separated string

var colors = ["red", "blue", "green"];
var colorsCSV = colors.join(","); //"red,blue,green"

Example 2: javascript join array

var array = ["Joe", "Kevin", "Peter"];
array.join(); // "Joe,Kevin,Peter"
array.join("-"); // "Joe-Kevin-Peter"
array.join(""); // "JoeKevinPeter"
array.join(". "); // "Joe. Kevin. Peter"

Example 3: .join in javascript

const elements = ['Sun', 'Earth', 'Moon'];

console.log(elements.join());
// output: "Sun,Earth,Moon"

console.log(elements.join(''));
// output: "SunEarthMoon"

console.log(elements.join('-'));
// output: "Sun-Earth-Moon"

Example 4: javascript concat

let chocholates = ['Mars', 'BarOne', 'Tex'];
let chips = ['Doritos', 'Lays', 'Simba'];
let sweets = ['JellyTots'];

let snacks = [];
snacks.concat(chocholates);
// snacks will now be ['Mars', 'BarOne', 'Tex']
// Similarly if we left the snacks array empty and used the following
snacks.concat(chocolates, chips, sweets);
//This would return the snacks array with all other arrays combined together
// ['Mars', 'BarOne', 'Tex', 'Doritos', 'Lays', 'Simba', 'JellyTots']

Example 5: concat array javascript

const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

const newArray = letters.concat(numbers);
// newArrat is ['a', 'b', 'c', 1, 2, 3]

Example 6: es6 concat array

let fruits = ["apples", "bananas"];
let vegetables = ["corn", "carrots"];
let produce = [...fruits, ...vegetables];
//["apples","bananas","corn","carrots"]