JavaScript is a versatile programming language used to add interactivity to websites, develop server-side applications with Node.js, and even build mobile apps.
1. Basic “Hello World”
The simplest way to verify JavaScript is running is to print a message to the browser console.
javascript
// This prints a message to the developer console
console.log("Hello, World!");
You can practice this and other fundamentals using the W3Schools JavaScript Tutorial
.
2. Variables and Data Types
Modern JavaScript uses
let for variables that can change and const for values that stay the same.javascript
const name = "Alice"; // String
let age = 25; // Number
const isStudent = true; // Boolean
let hobbies = ["coding", "reading"]; // Array
age = 26; // let allows reassignment
Check more variable examples on MDN Web Docs.
3. Functions
Functions are reusable blocks of code. Arrow functions offer a concise modern syntax.
javascript
// Traditional function
function greet(user) {
return "Hello, " + user + "!";
}
// Modern Arrow Function
const addNumbers = (a, b) => a + b;
console.log(greet(name)); // "Hello, Alice!"
console.log(addNumbers(5, 10)); // 15
Explore more complex function logic at Programiz JavaScript Examples
.
4. DOM Manipulation (Interacting with HTML)
JavaScript can change the content or style of a webpage in real-time.
javascript
// Selects an HTML element with id="my-title"
const title = document.getElementById("my-title");
// Changes its text content
title.textContent = "Welcome to my updated site!";
// Changes its CSS style
title.style.color = "blue";
Learn how to build interactive websites with MDN’s Adding Interactivity guide
.
5. Asynchronous JavaScript (Promises)
Used for tasks that take time, such as fetching data from a server.
javascript
async function fetchData() {
try {
const response = await fetch('https://example.com');
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
Where to test this code?
- Browser Console: Press
F12(orCmd+Option+Ion Mac) in any browser and go to the “Console” tab. - Online Editors: Use tools like JSFiddle
or OneCompiler
to write and run code instantly.
- Local Development: Install Visual Studio Code
for a professional coding environment.
- JavaScript is a versatile programming language
- Never