JavaScript Tutorial

JavaScript Examples

129 snippets you can run. Click Try it in JavaScript to open /javascript/try — a live page and a console.

129 copy-and-run snippets. Open one in Try JavaScript at /javascript/try, change a value, and run it again. Each language has its own shelf and its own editor.

Start

Case sensitive

let Name = "Ada";
let name = "Lin";
console.log(Name, name);
Related lesson →

Variables

Core

Function return

function greet(name) {
  return "Hello, " + name;
}
console.log(greet("Mira"));
Related lesson →

Function no args

function ping() {
  return "pong";
}
console.log(ping());
Related lesson →

Object literal

const person = { name: "Ada", year: 1815 };
console.log(person.name);
Related lesson →

Bracket key

const person = { name: "Ada" };
console.log(person["name"]);
Related lesson →

this in method

const cat = {
  name: "Miso",
  speak() { return this.name + " meows"; }
};
console.log(cat.speak());
Related lesson →

destructure

const { name } = { name: "Ada", year: 1815 };
console.log(name);
Related lesson →

default param

function greet(name = "friend") {
  return "Hi, " + name;
}
console.log(greet());
Related lesson →

Strings

Numbers

Arrays

Array literal

const fruits = ["apple", "pear", "fig"];
console.log(fruits[0]);
Related lesson →

for index

const xs = [10, 20];
for (let i = 0; i < xs.length; i++) {
  console.log(i, xs[i]);
}
Related lesson →

Flow

if else

const n = -1;
if (n >= 0) {
  console.log("plus");
} else {
  console.log("minus");
}
Related lesson →

else if

const n = 0;
if (n > 0) console.log("pos");
else if (n < 0) console.log("neg");
else console.log("zero");
Related lesson →

switch day

const day = "Mon";
switch (day) {
  case "Mon":
    console.log("start");
    break;
  default:
    console.log("other");
}
Related lesson →

break loop

for (let i = 0; i < 10; i++) {
  if (i === 3) break;
  console.log(i);
}
Related lesson →

continue even

for (let i = 0; i < 5; i++) {
  if (i % 2 === 0) continue;
  console.log(i);
}
Related lesson →

Types

Map set get

const m = new Map();
m.set("a", 1);
console.log(m.get("a"));
Related lesson →

try catch

try {
  throw new Error("nope");
} catch (e) {
  console.log(e.message);
}
Related lesson →

class instance

class Cat {
  constructor(name) { this.name = name; }
}
console.log(new Cat("Miso").name);
Related lesson →

Map keys

const m = new Map([["a", 1], ["b", 2]]);
console.log([...m.keys()]);
Related lesson →

class method

class Counter {
  constructor() { this.n = 0; }
  inc() { this.n += 1; return this.n; }
}
console.log(new Counter().inc());
Related lesson →

DOM

Change heading

<h1 id="title">Old</h1>
<script>
document.getElementById("title").textContent = "New";
console.log("updated");
</script>
Related lesson →

querySelector

<p class="note">Wait</p>
<script>
document.querySelector(".note").textContent = "Ready";
</script>
Related lesson →

querySelectorAll

<li>A</li><li>B</li>
<script>
console.log(document.querySelectorAll("li").length);
</script>
Related lesson →

createElement

<ul id="list"></ul>
<script>
const li = document.createElement("li");
li.textContent = "pear";
document.getElementById("list").appendChild(li);
</script>
Related lesson →

classList add

<p id="n">Hi</p>
<style>.on{color:teal}</style>
<script>
document.getElementById("n").classList.add("on");
</script>
Related lesson →

Click counter

<button id="go">+1</button>
<p id="out">0</p>
<script>
let n = 0;
document.getElementById("go").addEventListener("click", () => {
  n += 1;
  document.getElementById("out").textContent = n;
  console.log(n);
});
</script>
Related lesson →

Input greet

<input id="name" value="Ada">
<button id="go">Greet</button>
<p id="out"></p>
<script>
document.getElementById("go").addEventListener("click", () => {
  const name = document.getElementById("name").value;
  document.getElementById("out").textContent = "Hello, " + name;
});
</script>
Related lesson →

Prevent submit

<form id="f"><button>Send</button></form>
<p id="out"></p>
<script>
document.getElementById("f").addEventListener("submit", (e) => {
  e.preventDefault();
  document.getElementById("out").textContent = "Stopped submit";
});
</script>
Related lesson →

setTimeout

<p id="out">wait</p>
<script>
setTimeout(() => {
  document.getElementById("out").textContent = "later";
  console.log("later");
}, 300);
</script>
Related lesson →

localStorage set

<p id="out"></p>
<script>
localStorage.setItem("theme", "dark");
document.getElementById("out").textContent = localStorage.getItem("theme");
</script>
Related lesson →

JSON in storage

<p id="out"></p>
<script>
localStorage.setItem("user", JSON.stringify({ name: "Ada" }));
const user = JSON.parse(localStorage.getItem("user"));
document.getElementById("out").textContent = user.name;
</script>
Related lesson →

Fetch json placeholder

<p id="out">loading</p>
<script>
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((r) => r.json())
  .then((data) => {
    document.getElementById("out").textContent = data.title;
    console.log(data.id);
  })
  .catch((err) => console.log(err.message));
</script>
Related lesson →

Change style

<p id="n">Paint me</p>
<script>
document.getElementById("n").style.color = "teal";
</script>
Related lesson →

innerHTML list

<div id="box"></div>
<script>
document.getElementById("box").innerHTML = "<strong>Hi</strong>";
</script>
Related lesson →

textContent vs html

<p id="n"></p>
<script>
document.getElementById("n").textContent = "<b>plain</b>";
</script>
Related lesson →

Date clock bits

const d = new Date();
console.log(d.getHours(), d.getMinutes());
Related lesson →

dataset

<button id="go" data-id="7">Go</button>
<script>
console.log(document.getElementById("go").dataset.id);
</script>
Related lesson →

toggle class

<button id="go">Toggle</button>
<p id="n" class="off">box</p>
<style>.on{font-weight:800}</style>
<script>
document.getElementById("go").addEventListener("click", () => {
  document.getElementById("n").classList.toggle("on");
});
</script>
Related lesson →

remove child

<ul id="list"><li id="gone">x</li></ul>
<script>
document.getElementById("gone").remove();
console.log(document.querySelectorAll("li").length);
</script>
Related lesson →

sessionStorage

<p id="out"></p>
<script>
sessionStorage.setItem("n", "1");
document.getElementById("out").textContent = sessionStorage.getItem("n");
</script>
Related lesson →

async await fetch

<p id="out"></p>
<script>
(async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const data = await res.json();
  document.getElementById("out").textContent = data.completed;
})();
</script>
Related lesson →

FAQ: JavaScript Examples

Common questions about this page.

What is the StudyGrid JavaScript tutorial?

The StudyGrid JavaScript tutorial is a full beginner track: variables, functions, arrays, if/else, the DOM, events, storage, and fetch. Each chapter has copy-and-run examples.

Should I run javascript examples examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn javascript examples in this JavaScript JavaScript lesson (JavaScript Examples).

Is the JavaScript editor the same as Try Python?

No. Try JavaScript is a live page plus a console at /javascript/try. Try Python stays at /try. JavaScript lessons never open the Python editor.

Do I need to install anything to learn JavaScript?

No. Open a chapter, click Try it in JavaScript, and the page and console update in the browser.

Where should I start the JavaScript tutorial?

Start at JavaScript Intro, then Where To, Output, and Syntax. After variables and functions, continue to the DOM and events. Use Next at the bottom of each chapter.

Is the JavaScript tutorial free?

Yes. The JavaScript studio on StudyGrid (studygrid.in) is free: dashboard, chapters, and the live editor.