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

  1. Pick an example from the sidebar or mobile menu
  2. Study the code and expected output
  3. Run it in our online JS compiler or browser console
  4. 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 Check if the Numbers Have Same Last Digit

Compare last digit.

Source Code
const a=27,b=57; console.log(a%10===b%10);
Expected Output

JavaScript Program To Print Hello World

Print a message to the console.

Source Code
console.log("Hello, World!");
Expected Output

JavaScript Program to Add Two Numbers

Add two numbers and print the sum.

Source Code
const a=5; const b=7; const sum=a+b; console.log(sum);
Expected Output

JavaScript Program to Calculate the Area of a Triangle

Use 1/2 * base * height.

Source Code
const base=10, height=5; const area=(base*height)/2; console.log(area);
Expected Output

JavaScript Program to Swap Two Variables

Swap using destructuring.

Source Code
let a=3,b=4; [a,b]=[b,a]; console.log(a,b);
Expected Output

JavaScript Program to Solve Quadratic Equation

Compute roots using the quadratic formula.

Source Code
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);
Expected Output

JavaScript Program to Convert Kilometers to Miles

Convert km to miles (1 km ≈ 0.621371 mi).

Source Code
const km=10; const miles=km*0.621371; console.log(miles);
Expected Output

Javascript Program to Convert Celsius to Fahrenheit

Use (C*9/5)+32.

Source Code
const c=25; const f=(c*9/5)+32; console.log(f);
Expected Output

Javascript Program to Generate a Random Number

Random integer in a range.

Source Code
function rand(min,max){return Math.floor(Math.random()*(max-min+1))+min;} console.log(rand(1,100));
Expected Output

Javascript Program to Check if a number is Positive, Negative, or Zero

Check sign of a number.

Source Code
const n=0; console.log(n>0?"positive":n<0?"negative":"zero");
Expected Output

Javascript Program to Check if a Number is Odd or Even

Use modulo % 2.

Source Code
function isEven(n){return n%2===0;} console.log(isEven(7));
Expected Output

JavaScript Program to Find the Largest Among Three Numbers

Find max among three numbers.

Source Code
const a=5,b=17,c=9; console.log(Math.max(a,b,c));
Expected Output

JavaScript Program to Make a Simple Calculator

Perform +, -, *, /.

Source Code
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,"*"));
Expected Output

JavaScript Program to Find the Factors of a Number

List all divisors.

Source Code
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));
Expected Output

JavaScript Program to Guess a Random Number

Simple guess demo.

Source Code
const target=Math.floor(Math.random()*10)+1; const guess=7; console.log(guess===target?"Correct":"Try again: "+target);
Expected Output

JavaScript Program to Shuffle Deck of Cards

Fisher–Yates shuffle.

Source Code
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));
Expected Output

JavaScript Program to Convert Decimal to Binary

Use toString(2).

Source Code
const n=42; console.log(n.toString(2));
Expected Output

JavaScript Program to Find ASCII Value of Character

Use charCodeAt.

Source Code
const ch="A"; console.log(ch.charCodeAt(0));
Expected Output

JavaScript Program to Sort Words in Alphabetical Order

Sort words.

Source Code
const s="banana apple cherry"; console.log(s.split(/\s+/).sort().join(" "));
Expected Output

JavaScript Program to Check the Number of Occurrences of a Character in the String

Count char occurrences.

Source Code
function count(s,ch){let c=0; for(const x of s){if(x===ch)c++;} return c;} console.log(count("hello","l"));
Expected Output

JavaScript Program to Check Whether a String Starts and Ends With Certain Characters

Use startsWith/endsWith.

Source Code
const s="JavaScript"; console.log(s.startsWith("Java"), s.endsWith("ipt"));
Expected Output

JavaScript Program to Format Numbers as Currency Strings

Use toLocaleString.

Source Code
const n=1234.56; console.log(n.toLocaleString("en-US",{style:"currency",currency:"USD"}));
Expected Output

JavaScript Program to Check if a String Starts With Another String

Use startsWith.

Source Code
console.log("JavaScript".startsWith("Java"));
Expected Output

JavaScript Program to Check Leap Year

Check leap year rules.

Source Code
function isLeapYear(y){return (y%4===0 && y%100!==0) || y%400===0;} console.log(isLeapYear(2024));
Expected Output

JavaScript Program to Add Element to Start of an Array

Use unshift.

Source Code
const a=[2,3]; a.unshift(1); console.log(a);
Expected Output

JavaScript Program to Extract Given Property Values from Objects as Array

Map property values.

Source Code
const a=[{x:1},{x:2},{x:3}]; console.log(a.map(o=>o.x));
Expected Output

JavaScript Program To Check If A Variable Is undefined or null

Check variable state.

Source Code
const v=null; console.log(v==null);
Expected Output

JavaScript Program to Set a Default Parameter Value For a Function

Default parameter.

Source Code
function greet(name="Guest"){console.log("Hello, "+name);} greet();
Expected Output

JavaScript Program to Illustrate Different Set Operations

Union, intersection, difference.

Source Code
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);
Expected Output

Javascript Program to Generate a Random Number Between Two Numbers

Random in [min,max].

Source Code
function rand(min,max){return Math.floor(Math.random()*(max-min+1))+min;} console.log(rand(10,20));
Expected Output

JavaScript Program To Get The Current URL

Get current URL.

Source Code
console.log(window.location.href);
Expected Output

JavaScript Program to Check If a Variable is of Function Type

Use typeof.

Source Code
const fn=()=>{}; console.log(typeof fn==="function");
Expected Output

JavaScript Program To Work With Constants

Use const.

Source Code
const PI=3.14159; console.log(PI);
Expected Output

JavaScript Program to Generate a Range of Numbers and Characters

Generate ranges.

Source Code
const nums=Array.from({length:10},(_,i)=>i+1); const chars=Array.from({length:5},(_,i)=>String.fromCharCode(65+i)); console.log(nums,chars);
Expected Output

JavaScript Program to Perform Function Overloading

Handle different args.

Source Code
function add(){return [...arguments].reduce((a,b)=>a+b,0);} console.log(add(1,2,3));
Expected Output

JavaScript Program to Implement a Stack

Stack with push/pop.

Source Code
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());
Expected Output

JavaScript Program to Implement a Queue

Queue with enqueue/dequeue.

Source Code
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());
Expected Output

JavaScript Program to Check if a Number is Float or Integer

Use Number.isInteger.

Source Code
const n=3.14; console.log(Number.isInteger(n)?"integer":"float");
Expected Output

JavaScript Program to Pass a Function as Parameter

Pass functions around.

Source Code
function applyTwice(f,x){return f(f(x));} const inc=x=>x+1; console.log(applyTwice(inc,3));
Expected Output

JavaScript Program to Get the Dimensions of an Image

Read image width/height.

Source Code
const img=new Image(); img.onload=()=>console.log(img.width,img.height); img.src="https://via.placeholder.com/150";
Expected Output

JavaScript Program to Remove All Whitespaces From a Text

Remove all whitespace.

Source Code
const s=" a b \t c \n"; console.log(s.replace(/\s+/g,""));
Expected Output

JavaScript Program to Write to Console

Use console methods.

Source Code
console.log("log"); console.warn("warn"); console.error("error");
Expected Output

Keep Practicing

Use the online compiler to run examples and test variations. Reinforce learning by building small scripts for each topic.

FAQ

Yes, run them instantly. Copy the code into our online JS compiler or your browser console (F12 → Console). Output uses console.log.

ES6+ (modern JavaScript). All examples work in Chrome, Firefox, Safari, and Edge. Arrow functions, template literals, and destructuring are used where appropriate.

Yes, absolutely. All examples are free to copy, modify, and share. Experimentation is the fastest way to learn JavaScript.

Start with basics, then build up. Begin with Hello World → variables → arithmetic → control flow → functions → strings → arrays → objects.

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.