Learn JavaScript Basics

JavaScript makes your web pages interactive. Let’s explore the core concepts for beginners!

1. Adding JavaScript

Add JavaScript using a

Steps:

  1. Add the script tag before the closing tag for better performance.
  2. For external files, create a .js file and link it.
VS Code Tip: Type script and press Tab (Mac: Tab, Windows: Tab) to auto-generate a script tag.

2. Variables

Store data using let, const, or var (use let and const for modern code).

let name = "Alice"; // Can change const age = 20; // Cannot change console.log(name, age); // Outputs: Alice 20

Try it: Click to log variables to the console!

VS Code Tip: Press Cmd + Shift + J (Mac) or Ctrl + Shift + J (Windows) to open the browser console and see console.log output.

3. Functions

Functions are reusable blocks of code. Define them with function.

function sayHello(name) { return "Hello, " + name + "!"; } console.log(sayHello("Bob")); // Outputs: Hello, Bob!

Try it: Click to call a function!

VS Code Tip: Use Cmd + D (Mac) or Ctrl + D (Windows) to select and edit multiple instances of a function name.

4. Conditionals

Use if, else if, and else to make decisions.

let age = 18; if (age >= 18) { console.log("You can vote!"); } else { console.log("Too young to vote."); }

Try it: Click to toggle age and see the result!

VS Code Tip: Press Cmd + / (Mac) or Ctrl + / (Windows) to comment out conditionals while testing.

5. Loops

Repeat tasks with for or while loops.

for (let i = 1; i <= 3; i++) { console.log("Count: " + i); } // Outputs: // Count: 1 // Count: 2 // Count: 3

Try it: Click to run a loop!

VS Code Tip: Use Option + Up/Down (Mac) or Alt + Up/Down (Windows) to move loop lines up or down.

6. DOM Manipulation

Change your webpage with JavaScript using the Document Object Model (DOM).

Original Text

Try it: Click to change the text below!

Original Text
VS Code Tip: Press Cmd + Shift + F (Mac) or Ctrl + Shift + F (Windows) to search for DOM methods across your project.

7. Events

Respond to user actions like clicks with event listeners.

Try it: Click the button below!

VS Code Tip: Press Cmd + T (Mac) or Ctrl + T (Windows) to quickly find event listener functions in your code.