Below are some popular JavaScript code samples that you can use to learn and practice your JavaScript skills.
1. Hello World
The classic "Hello World" example is a great way to start learning any programming language, including JavaScript.
console.log("Hello, World!");
2. Calculator
A simple calculator can help you understand basic arithmetic operations in JavaScript.
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b !== 0) {
return a / b;
} else {
return "Error: Division by zero";
}
}
3. DOM Manipulation
Manipulating the Document Object Model (DOM) is a fundamental skill in JavaScript.
function changeText() {
document.getElementById("myText").innerHTML = "Text changed!";
}
document.getElementById("myButton").addEventListener("click", changeText);
4. Fetch API
The Fetch API is a modern way to make HTTP requests in JavaScript.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
For more examples and tutorials, check out our JavaScript documentation.