← Back to Tutorials Chapter 1

Getting Started with JavaScript

What is JavaScript?

JavaScript is a high-level, interpreted programming language that makes web pages interactive. It runs in the browser and is one of the three core technologies of the web alongside HTML and CSS.

Where to Put JavaScript

Inline JavaScript

You can add JavaScript directly inside HTML elements using event attributes:

<button onclick="alert('Hello!')">Click Me</button>

Internal JavaScript

Place code inside a <script> tag in the <head> or before the closing </body>:

<script>
  console.log("Hello from internal JS");
</script>

External JavaScript

Link a separate .js file using the src attribute:

<script src="app.js"></script>

Output Methods

JavaScript provides several ways to display output:

// Console output — great for debugging
console.log("This goes to the browser console");

// Write directly to the document
document.write("This appears on the page");

// Show a popup dialog
alert("This is an alert box");

Basic Syntax

JavaScript statements end with a semicolon (optional but recommended). The language ignores whitespace, making it flexible in formatting.

Comments

// This is a single-line comment

/*
  This is
  a multi-line
  comment
*/

Variables

Use var, let, or const to declare variables:

// var — function-scoped, avoid in modern code
var name = "Alice";

// let — block-scoped, can be reassigned
let age = 25;
age = 26;

// const — block-scoped, cannot be reassigned
const birthYear = 1998;
Tip: Prefer const by default and use let only when you need to reassign. Avoid var in modern JavaScript.

Operators

Arithmetic Operators

let sum = 10 + 5;     // 15
let diff = 10 - 5;    // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let mod = 10 % 3;     // 1
let exp = 2 ** 3;     // 8

Assignment Operators

let x = 10;
x += 5;  // x = 15
x -= 3;  // x = 12
x *= 2;  // x = 24
x /= 4;  // x = 6

Comparison Operators

5 == "5"   // true  (loose equality)
5 === "5"  // false (strict equality)
5 != "5"   // false
5 !== "5"  // true
5 > 3     // true
5 <= 5    // true

Logical Operators

let a = true, b = false;
a && b  // false (AND)
a || b  // true  (OR)
!a      // false (NOT)
JavaScript in the browser
Key Point: JavaScript is case-sensitive. myVariable and myvariable are two different identifiers. Use camelCase for variable names by convention.
Exercise: Create a script that declares two variables firstName and lastName, combines them into a full name using the + operator, and logs the result to the console. Then use alert() to display the full name.