JavaScript Code Templates

Hello World

Displays "Hello World" in the console.

Hello World Preview
console.log("Hello World");

Variables

Declare variables and print them.

Variables Preview
let x = 10;
let y = 5;
console.log(x + y);

If Statement

Simple if-else example in JavaScript.

If Statement Preview
let age = 18;
if(age >= 18){
  console.log("Adult");
}else{
  console.log("Minor");
}

For Loop

Loop through numbers 1 to 5.

For Loop Preview
for(let i = 1; i <= 5; i++){
  console.log(i);
}

While Loop

Execute while a condition is true.

While Loop Preview
let count = 0;
while(count < 5){
  console.log(count);
  count++;
}

Function

Define and call a function.

Function Preview
function greet(name){
  console.log("Hello " + name);
}
greet("Alice");

Array

Create an array and loop through it.

Array Preview
let fruits = ["apple","banana","cherry"];
fruits.forEach(fruit => console.log(fruit));

Object

Create a simple object and access properties.

Object Preview
let person = {name:"Alice", age:25};
console.log(person.name);

Random Number

Generate a random number between 1 and 10.

Random Number Preview
let rand = Math.floor(Math.random()*10)+1;
console.log(rand);

DOM Manipulation

Change content of an HTML element.

DOM Preview
document.getElementById("demo").innerText = "Hello!";