Intro to JavaScript
The language of the web. Every website you've ever used runs JavaScript.
The language of the web. Every website you've ever used runs JavaScript.
Born in a rush, named as a trick, and now the most widely used programming language in the world. Here is how it happened.
Despite the name, JavaScript has almost nothing to do with Java. The naming was purely a marketing decision by Netscape to capitalize on Java's popularity in 1995.
Every programmer starts here. In JavaScript, you print to the console with console.log(). Let's also look at variables and template literals.
// Your first JavaScript program
console.log('Hello, World!');
// Variables: use const for values that don't change
const name = 'Alice';
const age = 14;
// Use let for values that can change
let score = 0;
score = score + 10;
// Template literals: embed variables inside strings with backticks
console.log(`Hi, I'm ${name} and I'm ${age} years old`);
console.log(`My score is ${score}`);// REPL: try these one at a time
> console.log('Hello, World!')
Hello, World!
> 2 + 2
4
> 'hello'.toUpperCase()
'HELLO'const declares a variable that cannot be reassigned. let declares one that can. Use const by default, let when you need to change the value.
Use backticks (`) instead of quotes and ${expression} to embed values directly in a string. Much cleaner than string concatenation.
Semicolons at the end of statements are optional in JavaScript (the engine inserts them automatically), but many developers include them for clarity.
JavaScript's two core data structures. Arrays hold ordered lists of values. Objects hold named key-value pairs. Together they can represent almost anything.
// Arrays: ordered lists
const colors = ['red', 'green', 'blue'];
console.log(colors[0]); // 'red' (arrays start at index 0)
console.log(colors.length); // 3
// Useful array methods
colors.push('yellow'); // add to end
colors.pop(); // remove last item
// map: transform every item
const upper = colors.map(c => c.toUpperCase());
// ['RED', 'GREEN', 'BLUE']
// filter: keep only items that pass a test
const short = colors.filter(c => c.length <= 4);
// ['red', 'blue']// Objects: named key-value pairs
const player = {
name: 'Alice',
health: 100,
inventory: ['sword', 'shield'],
isAlive: true
};
console.log(player.name); // 'Alice'
console.log(player.inventory[0]); // 'sword'
// JSON: JavaScript Object Notation
// Objects convert to JSON for storage and transmission
const json = JSON.stringify(player);
const parsed = JSON.parse(json);JSON (JavaScript Object Notation) was born from JavaScript objects, but it is now used by almost every programming language. APIs, config files, databases: JSON is everywhere. If you learn JavaScript objects, you already know JSON.
Creates a new array by transforming every element. The original array stays unchanged.
Creates a new array with only the elements that pass a condition. Returns true to keep, false to skip.
Functions are reusable blocks of code. JavaScript has two syntaxes for writing them, and both are used everywhere.
// Classic function declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 'Hello, Alice!'
// Arrow function (shorter syntax, same idea)
const greet2 = (name) => {
return `Hello, ${name}!`;
};
// Even shorter: one-line arrow functions
const double = (n) => n * 2;
const isEven = (n) => n % 2 === 0;
console.log(double(5)); // 10
console.log(isEven(4)); // true// Callbacks: passing functions as arguments
const numbers = [1, 2, 3, 4, 5];
// forEach: run a function on each item
numbers.forEach(n => console.log(n * 10));
// 10, 20, 30, 40, 50
// map + arrow function = very common pattern
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
// Chaining: combine operations
const result = numbers
.filter(n => n > 2)
.map(n => n * 10);
// [30, 40, 50]The original syntax. Hoisted to the top of their scope, so you can call them before they appear in the code.
Introduced in ES6. Shorter syntax, especially for one-liners. Perfect for callbacks and array methods.
A function passed as an argument to another function. This is the foundation of asynchronous JavaScript and event handling.
In JavaScript, functions are "first-class citizens." That means you can assign them to variables, pass them as arguments, and return them from other functions, just like any other value.
Plenty of languages can do variables, arrays, and functions. What sets JavaScript apart from every other language?
Browser, server (Node.js), mobile (React Native), desktop (Electron), embedded devices. No other language matches this reach.
JavaScript listens for events: clicks, key presses, network responses, timers. Your code reacts when things happen, instead of running line by line.
JavaScript can start a task (like fetching data), move on to other work, and come back when the data arrives. This makes it great for web apps.
npm (Node Package Manager) has over 2 million packages. Need a date library, a game engine, an image processor? Someone already built it.
JavaScript is the only programming language that every web browser can run natively. HTML and CSS handle structure and style. JavaScript handles behavior.
Instead of traditional classes (though JS has those too), objects can inherit directly from other objects. This is a flexible, powerful approach to code reuse.
// Event-driven: respond to user actions
document.querySelector('button').addEventListener('click', () => {
console.log('Button clicked!');
});
// Asynchronous: fetch data from an API
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);Every major tech company uses JavaScript extensively. Netflix, Uber, PayPal, LinkedIn, and NASA all run JavaScript in production. The language that was built in 10 days now powers most of the internet.
The best way to learn is by writing code. Here is how to get started with JavaScript in the terminal right now.
Install Node.js in the terminal. This lets you run JavaScript outside a browser.
Create a new file called app.js and open the text editor.
Run your JavaScript file. Output appears in the terminal.
Start the Node.js REPL. Type JavaScript expressions and see results instantly. Press Ctrl+C to exit.
Open the terminal, install Node, and create this file:
// greeting.js
const greetings = [
'Hello',
'Howdy',
'Hey there',
'Greetings',
'Yo'
];
const names = ['World', 'JavaScript', 'Developer'];
const randomPick = (arr) => arr[Math.floor(Math.random() * arr.length)];
for (let i = 0; i < 5; i++) {
console.log(`${randomPick(greetings)}, ${randomPick(names)}!`);
}# Run it:
$ node greeting.js
Hey there, Developer!
Yo, World!
Hello, JavaScript!
Greetings, Developer!
Howdy, World!Once you are comfortable with the basics, explore the DOM (Document Object Model) to make web pages interactive, or try building a simple server with Node.js. JavaScript opens doors to everything on the web.
You now know the fundamentals of JavaScript, the most widely used programming language on Earth. Variables, functions, arrays, objects: these are the building blocks of every web app, game, and server.
Use let and const to store values. const for things that never change, let for things that do.
Wrap logic in a function and call it by name. Arrow functions (=>) make this even shorter.
Arrays are ordered lists. Objects are named collections. Together they can model anything.
Browsers, servers, mobile apps, desktop apps, robots. No other language has this reach.
Put your new knowledge into practice!