JavaScript Basics Examples
Key takeaway: Practice JavaScript with 102+ runnable code examples — variables, arrays, strings, objects, math, dates, and DOM — all with expected output to verify instantly.
JavaScript is a programming language that makes web pages interactive. These examples are for front-end developers, bootcamp students, self-taught coders, and anyone preparing for JS interviews.
Last updated: October 2026 · 102 examples
Quick Start
- Pick an example from the sidebar or mobile menu
- Study the code and expected output
- Run it in our online JS compiler or browser console
- Modify the code to experiment
Who is this for: Front-end developers, bootcamp students, interview candidates, and self-taught coders building JavaScript skills. Use this when: you need quick reference code, want to practice for interviews, or learn JS concepts hands-on.
Related:JS Projects · JS Tutorial · JS Compiler · TypeScript Examples · Python Examples · MDN JavaScript Docs
JavaScript Program to Extract Given Property Values from Objects as Array
Map property values.
const a=[{x:1},{x:2},{x:3}]; console.log(a.map(o=>o.x));JavaScript Program To Print Hello World
Print a message to the console.
console.log("Hello, World!");JavaScript Program to Add Two Numbers
Add two numbers and print the sum.
const a=5; const b=7; const sum=a+b; console.log(sum);
JavaScript Program to Calculate the Area of a Triangle
Use 1/2 * base * height.
const base=10, height=5; const area=(base*height)/2; console.log(area);
JavaScript Program to Swap Two Variables
Swap using destructuring.
let a=3,b=4; [a,b]=[b,a]; console.log(a,b);
JavaScript Program to Solve Quadratic Equation
Compute roots using the quadratic formula.
const a=1,b=-3,c=2; const d=b*b-4*a*c; const r1=(-b+Math.sqrt(d))/(2*a); const r2=(-b-Math.sqrt(d))/(2*a); console.log(r1,r2);
JavaScript Program to Convert Kilometers to Miles
Convert km to miles (1 km ≈ 0.621371 mi).
const km=10; const miles=km*0.621371; console.log(miles);
Javascript Program to Convert Celsius to Fahrenheit
Use (C*9/5)+32.
const c=25; const f=(c*9/5)+32; console.log(f);
Javascript Program to Generate a Random Number
Random integer in a range.
function rand(min,max){return Math.floor(Math.random()*(max-min+1))+min;} console.log(rand(1,100));Javascript Program to Check if a number is Positive, Negative, or Zero
Check sign of a number.
const n=0; console.log(n>0?"positive":n<0?"negative":"zero");
Javascript Program to Check if a Number is Odd or Even
Use modulo % 2.
function isEven(n){return n%2===0;} console.log(isEven(7));JavaScript Program to Find the Largest Among Three Numbers
Find max among three numbers.
const a=5,b=17,c=9; console.log(Math.max(a,b,c));
JavaScript Program to Make a Simple Calculator
Perform +, -, *, /.
function calc(a,b,op){switch(op){case "+":return a+b;case "-":return a-b;case "*":return a*b;case "/":return b? a/b: NaN; default:return NaN;}} console.log(calc(6,3,"*"));JavaScript Program to Check if the Numbers Have Same Last Digit
Compare last digit.
const a=27,b=57; console.log(a%10===b%10);
JavaScript Program to Find the Factors of a Number
List all divisors.
function factors(n){const f=[]; for(let i=1;i<=n;i++){if(n%i===0)f.push(i);} return f;} console.log(factors(28));JavaScript Program to Guess a Random Number
Simple guess demo.
const target=Math.floor(Math.random()*10)+1; const guess=7; console.log(guess===target?"Correct":"Try again: "+target);
JavaScript Program to Shuffle Deck of Cards
Fisher–Yates shuffle.
const cards=[]; const suits=["H","D","C","S"], ranks=["A","2","3","4","5","6","7","8","9","10","J","Q","K"]; for(const s of suits){for(const r of ranks){cards.push(r+s);}} for(let i=cards.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1)); [cards[i],cards[j]]=[cards[j],cards[i]];} console.log(cards.slice(0,10));JavaScript Program to Convert Decimal to Binary
Use toString(2).
const n=42; console.log(n.toString(2));
JavaScript Program to Find ASCII Value of Character
Use charCodeAt.
const ch="A"; console.log(ch.charCodeAt(0));
JavaScript Program to Sort Words in Alphabetical Order
Sort words.
const s="banana apple cherry"; console.log(s.split(/\s+/).sort().join(" "));JavaScript Program to Check the Number of Occurrences of a Character in the String
Count char occurrences.
function count(s,ch){let c=0; for(const x of s){if(x===ch)c++;} return c;} console.log(count("hello","l"));JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
Use startsWith/endsWith.
const s="JavaScript"; console.log(s.startsWith("Java"), s.endsWith("ipt"));JavaScript Program to Format Numbers as Currency Strings
Use toLocaleString.
const n=1234.56; console.log(n.toLocaleString("en-US",{style:"currency",currency:"USD"}));JavaScript Program to Check if a String Starts With Another String
Use startsWith.
console.log("JavaScript".startsWith("Java"));JavaScript Program to Check Leap Year
Check leap year rules.
function isLeapYear(y){return (y%4===0 && y%100!==0) || y%400===0;} console.log(isLeapYear(2024));JavaScript Program to Add Element to Start of an Array
Use unshift.
const a=[2,3]; a.unshift(1); console.log(a);
JavaScript Program To Check If A Variable Is undefined or null
Check variable state.
const v=null; console.log(v==null);
JavaScript Program to Set a Default Parameter Value For a Function
Default parameter.
function greet(name="Guest"){console.log("Hello, "+name);} greet();JavaScript Program to Illustrate Different Set Operations
Union, intersection, difference.
const A=new Set([1,2,3]), B=new Set([2,3,4]); const union=new Set([...A,...B]); const inter=new Set([...A].filter(x=>B.has(x))); const diff=new Set([...A].filter(x=>!B.has(x))); console.log(union,inter,diff);
Javascript Program to Generate a Random Number Between Two Numbers
Random in [min,max].
function rand(min,max){return Math.floor(Math.random()*(max-min+1))+min;} console.log(rand(10,20));JavaScript Program To Get The Current URL
Get current URL.
console.log(window.location.href);
JavaScript Program to Check If a Variable is of Function Type
Use typeof.
const fn=()=>{}; console.log(typeof fn==="function");JavaScript Program To Work With Constants
Use const.
const PI=3.14159; console.log(PI);
JavaScript Program to Generate a Range of Numbers and Characters
Generate ranges.
const nums=Array.from({length:10},(_,i)=>i+1); const chars=Array.from({length:5},(_,i)=>String.fromCharCode(65+i)); console.log(nums,chars);JavaScript Program to Perform Function Overloading
Handle different args.
function add(){return [...arguments].reduce((a,b)=>a+b,0);} console.log(add(1,2,3));JavaScript Program to Implement a Stack
Stack with push/pop.
class Stack{constructor(){this.a=[];} push(x){this.a.push(x);} pop(){return this.a.pop();} peek(){return this.a[this.a.length-1];}} const s=new Stack(); s.push(1); s.push(2); console.log(s.pop());JavaScript Program to Implement a Queue
Queue with enqueue/dequeue.
class Queue{constructor(){this.a=[];} enqueue(x){this.a.push(x);} dequeue(){return this.a.shift();} front(){return this.a[0];}} const q=new Queue(); q.enqueue(1); q.enqueue(2); console.log(q.dequeue());JavaScript Program to Check if a Number is Float or Integer
Use Number.isInteger.
const n=3.14; console.log(Number.isInteger(n)?"integer":"float");
JavaScript Program to Pass a Function as Parameter
Pass functions around.
function applyTwice(f,x){return f(f(x));} const inc=x=>x+1; console.log(applyTwice(inc,3));JavaScript Program to Get the Dimensions of an Image
Read image width/height.
const img=new Image(); img.onload=()=>console.log(img.width,img.height); img.src="https://via.placeholder.com/150";
JavaScript Program to Remove All Whitespaces From a Text
Remove all whitespace.
const s=" a b \t c \n"; console.log(s.replace(/\s+/g,""));
JavaScript Program to Write to Console
Use console methods.
console.log("log"); console.warn("warn"); console.error("error");Keep Practicing
Use the online compiler to run examples and test variations. Reinforce learning by building small scripts for each topic.
FAQ
Learn JavaScript by Practicing Examples
Hands-on practice is the fastest way to understand JavaScript. Each example above focuses on a single concept—from strings, arrays, and objects to math utilities, dates, loops, and functions. Try editing variables, adding conditions, or refactoring logic, then observe the output changes instantly.
Use our tools to deepen your learning: JavaScript Compiler to run snippets, and the JavaScript Tutorial for guided theory and practice.
Beginner-Friendly
Start with variables, operators, and control flow. Build confidence with simple, readable programs.
Practical Patterns
Practice common tasks like formatting strings, manipulating arrays, and working with dates.
Grow Skills
Advance to objects, classes, and asynchronous patterns such as promises and async/await.