Bookmark this page
JavaScript PlayGround
Quick reference for JavaScript with practice options
Code Runner
You can practice by running code using our code runner.
Basics
Different data type
Understanding different data types in JavaScript.
// Example of different data types let str = 'Hello World'; // String let num = 42; // Number let bool = true; // Boolean let arr = [1, 2, 3]; // Array let obj = { name: 'John', age: 30 }; // Object let undef; // Undefined let nul = null; // Null let sym = Symbol('symbol'); // Symbol let bigInt = BigInt(9007199254740991); // BigInt console.log(typeof str, typeof num, typeof bool, typeof arr, typeof obj, typeof undef, typeof nul, typeof sym, typeof bigInt);
Type conversions: explicit vs implicit.
// Type conversions let a = 1; // Number let b = '2'; // String let sum = a + Number(b); // Explicit conversion let implicitConversion = a + b; // Implicit conversion console.log('Explicit:', sum); // Outputs: 3 console.log('Implicit:', implicitConversion); // Outputs: 12
Arithmetic and logical operations.
// Arithmetic and logical operations let x = 10; let y = 5; console.log(x + y); // Addition console.log(x - y); // Subtraction console.log(x * y); // Multiplication console.log(x / y); // Division console.log(x % y); // Modulus console.log(x ** y); // Exponentiation console.log(x > y && y > 2); // Logical AND console.log(x < y || y < 10); // Logical OR console.log(!(x == y)); // Logical NOT
Conditional statements (if-else).
// Conditional statements let age = 18; if (age < 18) { console.log('Minor'); } else if (age === 18) { console.log('Just turned adult'); } else { console.log('Adult'); }
Switch statement example.
// Switch statement let day = 'Monday'; switch (day) { case 'Monday': console.log('Work hard'); break; case 'Friday': console.log('Party time'); break; default: console.log('Relax'); }
Loops
Looping through collections with for, while, and do-while.
// For loop example for (let i = 0; i < 10; i++) { console.log(i); } // While loop example let j = 0; while (j < 5) { console.log(j); j++; } // Do-while loop example let k = 0; do { console.log(k); k++; } while (k < 3);
Functions
Function declarations and expressions.
// Function declaration function greet(name) { return 'Hello ' + name; } console.log(greet('Alice')); // Function expression const square = function (x) { return x * x; }; console.log(square(4)); // Arrow function const add = (a, b) => a + b; console.log(add(2, 3));
Higher-order functions: map, filter, reduce.
// Higher-order functions const numbers = [1, 2, 3, 4, 5]; // Using map const doubled = numbers.map(num => num * 2); console.log(doubled); // Using filter const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Using reduce const sum = numbers.reduce((total, num) => total + num, 0); console.log(sum);
Set and Maps
Working with Set and Map in JavaScript.
// Working with Set let uniqueNumbers = new Set([1, 2, 3, 4, 4, 5]); // Duplicate '4' will be removed uniqueNumbers.add(6); uniqueNumbers.delete(2); console.log(uniqueNumbers); // Outputs: Set { 1, 3, 4, 5, 6 } console.log(uniqueNumbers.has(3)); // Check if a value exists // Working with Map let personMap = new Map(); personMap.set('name', 'John'); personMap.set('age', 30); console.log(personMap.get('name')); // Outputs: 'John' console.log(personMap.size); // Outputs: 2 personMap.delete('age'); console.log(personMap); // Outputs: Map { 'name' => 'John' }
Objects and Arrays
Creating and manipulating objects.
// Object creation and manipulation let person = { name: 'Alice', age: 25, greet: function() { console.log('Hello, ' + this.name); } }; console.log(person.name); // Accessing property person.age = 30; // Modifying property person.greet(); // Calling method
Array methods and iteration.
// Array creation and methods let fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // Accessing element fruits.push('date'); // Adding element console.log(fruits.length); // Array length fruits.forEach(fruit => console.log(fruit)); // Iterating over array
Destructuring assignment in objects and arrays.
// Destructuring assignment let [first, second] = [10, 20]; console.log(first, second); let {name, age} = {name: 'John', age: 30}; console.log(name, age);
Asynchronous
Promise
//Basic promise const checkNum = new Promise((resolve,reject)=>{ setTimeout(()=>{ let ranmdomNum = Math.random(); console.log(ranmdomNum); if(ranmdomNum>1.0){ resolve('Random number is greater than 0.5'); }else{ reject('Random number is smalller than 0.5'); } }); }) checkNum.then((result)=>{ console.log(result); }).catch((error)=>{ console.log(error); })
Promise With Methods
//Promise.all() and Promise.allsettled():- const function1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve("Data from function 1"); },2000) }); const function2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve("Data from function 2"); },2000) }); const function3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(("Data from function 3")) },2000) }); const data1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject("Error occurred!!!"); },3000) }); Promise.all([function1,function2,function3]) .then((result)=>{ console.log(result); }); Promise.allSettled([function1,function2,function3,data1]) .then((newResult)=>{ newResult.forEach((k)=>{ if(k.status === 'fulfilled'){ console.log(k.value); }else{ console.log(k.reason) } }); });
Working with promises and async/await.
// Promises and async/await let promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Done!'), 1000); }); promise.then(result => console.log(result)); async function asyncFunction() { let result = await promise; console.log(result); } asyncFunction();
Understanding callbacks in JavaScript.
// Callbacks function fetchData(callback) { setTimeout(() => { callback('Data received'); }, 1000); } fetchData(data => console.log(data));
Basic understanding of callback (without using any async functions)
// Callback functions (without any async function):- function personData(name, personAge) { console.log("My name is:", name); personAge(25); // You can change the person age here for testing. } function calcAge(age) { if (age > 18) { console.log("You are an Adult!"); } else { console.log("You are a Minor"); } } // Calling the function personData("John", calcAge);
Async/Await in modern JavaScript.
// Async/Await function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function printMessage() { console.log('Start'); await delay(1000); console.log('End'); } printMessage();
Comparing callback vs promise vs async/await
function getPostCallbackApproach(callback) { setTimeout(() => callback({message: 'This is a post'}), 1000); } getPostCallbackApproach((data) => console.log(data)); let getPostPromise = new Promise((resolve, reject) => { setTimeout(() => resolve({message: 'This is a post'}), 1000); }); getPostPromise.then(data => console.log(data)); async function getPostAsync() { let post = await getPostPromise; console.log(post); } getPostAsync();
Advanced Concepts
Closures and lexical scope.
// Closures function outerFunction(outerVariable) { return function innerFunction(innerVariable) { console.log('Outer:', outerVariable); console.log('Inner:', innerVariable); }; } const closureExample = outerFunction('outside'); closureExample('inside');
Understanding the "this" keyword.
// The 'this' keyword let user = { name: 'Alice', greet: function() { console.log('Hello ' + this.name); } }; user.greet(); let greetFunc = user.greet; greetFunc(); // 'this' is undefined or window in non-strict mode
Prototypes and inheritance in JavaScript.
// Prototypes function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHello = function() { console.log('Hello, my name is ' + this.name); }; let person1 = new Person('John', 30); person1.sayHello();
Classes and inheritance in ES6.
// Classes and inheritance class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks'); } } let dog = new Dog('Rex'); dog.speak();
Modules: import and export.
// Modules (ES6) // math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; // main.js import { add, subtract } from './math.js'; console.log(add(2, 3)); console.log(subtract(5, 2));
Asynchronous functions with fetch.
// Asynchronous functions async function fetchData() { try { let response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); let data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData();
DOM Manipulation
Modifying the style of the element.
// Change style of an element document.getElementById('bookmark-page').style.color = 'blue';
Adding event listener.
//Adding event listener document.getElementById('playgroud-js').addEventListener('click', function(){ alert('Welcome to JS Playground!'); });
Changing text content of an element.
//Changing text content document.getElementsByClassName('section-title mb-2')[0].textContent = 'Run Your Code.'
Changing the background color
// Changing the background color of all elements with the specified classes const nodeList = document.querySelectorAll('.mx-auto.text-xl.font-semibold'); for(let i = 0; i < nodeList.length; i++) { nodeList[i].style.backgroundColor = 'red'; }