Are you tired of the same old "Hello World" examples in JavaScript? Look no further! In this post, I'll show you 26 different ways to display "Hello World" using various methods, expressions, operators, and more. From the classic console.log to the Fetch API and even environment variables, there's something here for everyone. Follow along and see which approach you like best!
Let's get started!
• Common way
console.log("Hello World")
• By variable
const hw = "Hello World";
console.log(hw)
• By Template Literal
const tl = "Hello World";
console.log(`${tl}`)
• By Ternary Operator
console.log(`${true ? "Hello World" : "Hello World"}`)
• By Symbol
let s = Symbol("Hello World")
console.log(s) // Kinda Works?
• By a Regular Function
function hwf(string) {
return string
}
console.log(hwf("Hello World"))
• By a Array
const arr = ["Hello World"]
console.log(arr, `${arr}`)
• By Expression
if(true) {
console.log("Hello World")
} else {
console.log("Hello World")
}
• By Object
const hwo = {
word: "Hello World"
}
console.log(hwo["world"])
• By Array Object, because why not
const hwoa = [
{
word: "Hello World"
}
]
console.log(hwoa[0])
• By .map() method
console.log(hwoa.map((v)=>{
return `${v.word}`
})
)
• by .forEach() method
hwoa.forEach(value => console.log(value))
• by Arrow Function
const hwa = (str1) => {
console.log(str1)
}
const hwa2 = (str2) => console.log(str2)
hwa("Hello World")
hwa2("Hello World")
• by for loop
for (let i = 0; i < 1; i++) {
console.log("Hello World")
}
• by for of loop
for (let i of "Hello World") {
console.log(i)
}
• by for in loop
let a = "Hello World"
for (let i in a) {
console.log(a)
}
• by while loop
let i = 1
while (i < 2) {
console.log("\n\nHello World")
i++
}
• by do while loop (18)
do {
console.log("Hello World")
} while (false);
• by class (19)
class HelloWorld {
constructor() {
console.log("Hello World");
}
}
const myHelloWorld = new HelloWorld();
• By environment variables (20)
// unfortunately include "or logical operator"
console.log(process.env["WORD"] || "Hello World") // i use "or logical operator" because if other user run my repl then user will not get hello world it get Error or undefined
• By .split() & .join() method (21)
const strArray = "H e l l o, W o r l d".split(" ");
const str = strArray.join("");
console.log(str);
• by .replace() method (22)
console.log("H_e_l_l_o W_o_r_l_d".replace(/_/g, ""));
• by .push() method (23)
const hwp = []
hwp.push("Hello World")
console.log(hwp)
• by .concat() method (24)
hwp.concat("Hello World")
console.log(hwp)
• by Fetch API (25)
fetch('https://api.quotable.io/random')
.then(response => response.json())
.then(data => console.log('Hello World'))
.catch(error => console.error(error)); // Sorry about that..
• by alert (26)
alert("Hello World")
Try on replit: Replit
Soon I will upload more ways!
Thanks for reading! Join my coding community
Top comments (0)