25 JavaScript Basics Every Beginner Should Know (with Examples)

After learning HTML and CSS, the next step to making interactive websites is JavaScript. JS makes your site alive, enabling dynamic content, forms, pop-ups, sliders, and more.
In this post, I will walk you through 25 JavaScript concepts with examples you can try right away as a beginner.

πŸš€ What is JavaScript?

JavaScript is a lightweight, browser-based scripting language that lets you control how a web page behaves. It is used to create dynamic and interactive effects on websites. JavaScript allows developers to add features like form validation, content updates without reloading the page, animations, and much more. It is supported by all major web browsers and runs on the client side (browser) by default.

More about JavaScript: It was developed by Brendan Eich in 1995 while he was working at Netscape Communications Corporation. It is a case-sensitive language and is not the same as ‘Java’.

Why use JavaScript?

JavaScript is essential for web development because it allows you to:

  • Manipulate the DOM: Dynamically updates the content, style, or structure of HTML pages.
  • Handle User Events: React to clicks, scrolls, form submissions, etc.
  • Validate Forms in Real-Time: Check input without submitting data to the server.
  • Make asynchronous HTTP requests without reloading the page.
  • Build complex web applications with the help of various JS libraries and frameworks like React, Vue, and Angular.

Where to Write JavaScript?

There are 3 common places to write JavaScript in a web project.

Inline JavaScript – JavaScript code written directly inside an HTML tag

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

Internal JavaScript – JavaScript written inside a <script> tag within an HTML file. It is useful for testing or smaller scripts.

<!DOCTYPE html>
<html>
<head>
  <title>Internal JS</title>
</head>
<body>
  <script type="text/javascript">
    //JS code goes here
  </script>
</body>
</html>

External JavaScript File – JavaScript written in a separate .js file and linked using the <script src="..."></script> tag. It is considered best practice to keep HTML, CSS, and JavaScript in separate files. This helps to keep the structure (HTML), style (CSS), and behavior (JavaScript) organized, making the code easier to maintain and reuse.

<!DOCTYPE html>
<html>
<head>
  <title>External JS</title>
</head>
<body>
  <script src="script.js"></script>
</body>
</html>

πŸ“‹ 25 JavaScript Basics to Learn First

Now that you have learned the basic syntax of JavaScript and where to write it, let’s dive a little deeper.

Syntax and Comments

Syntax is the set of rules for writing JavaScript code.
Comments are lines that are ignored by the browser (used to explain the code to ourselves or others).

// This is used for commenting out single line
/* This is used for commenting out multiple lines */

Variables (var, let, const)

A variable stores data like a name, number, or list.

let name = "John"; // You can change its value.
const age = 25; // You cannot reassign it (constant)
var city = "New York"; // Older, not recommended due to confusing behavior

// var is function-scoped, not block-scoped, so it ignores {} blocks, which can lead to unexpected bugs. It can accidentally overwrite variables in the global scope.

Data Types

JavaScript supports multiple data types. Data types are the different kinds of values you can store. Each variable stores a different type of data. You use different types for different jobs.

let str = "Hello";      // String
let name = "Bob";       // String Example

let num = 123;          // Number
let age = 30;           // Number Example

let isTrue = true;      // Yes/No (Boolean)
let isStudent = true;   // Boolean Example

let arr = [1, 2, 3];                          // List of items (array)
let car = ["car1", "car2", "car3", "car4"];  // Array Example

let obj = { name: "Joe", age: 30 };     // Object (grouped data)
let person = { name: "Bob", age: 30 };  // Object Example

let nothing = null;     // Empty
let notDefined;         // Not yet given a value

console.log()

Prints output to the browser’s console (used for testing/debugging).

console.log("Hello world");  // Prints Hello world

let a  = 5;
console.log(a);  // Prints 5

Functions

Reusable blocks of code that do something.

// Example 1
function greet() {  // // "greet" is the name of function
  console.log("Hello!");
}
greet(); // Calls the function and prints Hello!

// Example 2
function greet() {
  alert("Hi!");
}
greet(); // Calls the function and pops up Hi! message in floating window 

Arrow Functions

An arrow function is a shorter way to write a function in JavaScript. It saves space and typing.

// Traditional function expression
const addTraditional = function(a, b) {
  return a + b;
};

// Arrow function equivalent
const addArrow = (a, b) => a + b;

console.log(addTraditional(2, 3)); // 5
console.log(addArrow(2, 3));      // 5

Parameters and Arguments

A parameter is a placeholder inside the function, while an argument is the actual value you pass when calling the function. Functions can use multiple parameters and can even set default values.

function vendingMachine(drink) { // "drink" is the parameter
  console.log("You selected: " + drink);
}

vendingMachine("Coke"); // "Coke" is the argument
// Output = You selected: Coke

Return

Returns a value from a function to be used later.

function add(x, y) {
  return x + y;
}

let result = add(2, 3);
console.log(result); // result = 5

Operators

(+, -, *, /, %, =, ==) Operators do things like math or comparisons.

// Arithmetic operators
let a = 10 + 5;       // Adds 10 and 5
let b = 10 - 5;       // Subtracts 5 from 10
let c = 10 * 2;       // Multiplies 10 and 2
let d = 10 / 2;       // Divides 10 by 2
let e = 10 % 3;       // Shows Remainder in Output

// Comparison operators
let p = 5 == '5';   // Equal: compares values, but not types, Output = true
let r = 10 != '10';  // Not equal: compares values, but not types, Output = false

let q = 5 === '5';  // Strict equal: compares values AND types, Output = false
let s = 10 !== '10';  // Strict not equal: compares values AND types, Output =  true

let t = 8 > 5;  // Greater than, Output = true
let t = 3 < 7;  // Less than, Output = true

let t = 6 >= 6;  // Greater than or equal to, Output = true
let t = 4 <= 5;  // Less than or equal to, Output = true

Conditional Statements

(If / else) These let your code make decisions.

let age = 18;

if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}
// It checks if the age is 18 or more. If yes, it prints β€œAdult”. Otherwise, β€œMinor”.

Switch

Simplifies multiple if/else if checks.

let day = 3;

switch (day) {
  case 1:
    console.log("Monday"); // Code runs if day === 1 and vice versa
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;  // switch ends if day = 3 else it continue further checks
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("Invalid day"); // Code runs if no cases match
}

// Output =  Wednesday (as the value of day is 3, break ends the switch at case 3 and returns Wednesday)

Loops (for, while)

A loop repeats a block of code multiple times, either a fixed number of times (for loop) or until a certain condition is met (while loop).

  • Use for when the number of times to loop is known
  • Use while when the loop depends on a condition and could vary
// for loop example

/* for (initialization; condition; update) {
  // code to repeat
} */

for (let i = 1; i <= 5; i++) {
  console.log("i is:", i);
}

/* Output:
i is: 1
i is: 2
i is: 3
i is: 4
i is: 5 */


// while loop example:

/* while (condition) {
  // code to repeat
} */

let secretNumber = 7;
let guess;

while (guess !== secretNumber) {
  guess = parseInt(prompt("Guess the number between 1 and 10:"));

  if (guess === secretNumber) {
    alert("πŸŽ‰ Correct! You guessed it!");
  } else {
    alert("❌ Wrong guess. Try again.");
  }
}

Arrays

An array is a list that can hold multiple values in one variable. It stores a group of similar items (e.g., names, numbers).

Items in arrays are ordered by index (starting from 0). You can access items using array[index], and .length gives the total number of items.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // "Apple"
console.log(fruits.length); // 3

Objects

Objects store data in key-value pairs, like a mini database. It stores related information (e.g., a person’s profile). Here, keys act like labels, and you can access values using either dot notation (e.g., person.name) or bracket notation (e.g., person['name']).

let person = {
  name: "Alice",
  age: 25,
  isStudent: true
};

console.log(person.name); // Output: Alice
console.log(person["name"]); // Output: Alice

Array Methods

push(), pop(), length, etc. Built-in functions to work with arrays.

// Add to end
let numbers = [1, 2, 3, 4];
numbers.push(5);
console.log(numbers); // [1, 2, 3, 4, 5]

// Remove from end
let numbers = [1, 2, 3, 4, 5];
numbers.pop();
console.log(numbers); // [1, 2, 3, 4]

// Return the length means number of items in array
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // 5

// Transform all items
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]

// Filter items
let numbers = [1, 2, 3, 4];
let even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2, 4]

DOM (Document Object Model)

The DOM is how JavaScript interacts with HTML to change things on the page. You can get, change, or add HTML elements using JavaScript.

<body>
  <p id="message">Hello!</p>
</body>

<script>
  document.getElementById("message").innerText = "Hi from JavaScript!";
</script>

// This changes Hello! to Hi from JavaScript! in webpage

Events

Events are actions like clicks or keypresses that your code can respond to. You listen for an event (like a click) and run code in response.

<button onclick="sayHello()">Click Me</button>

<script>
  function sayHello() {
    alert("Hello, user!");
  }
</script>

setTimeout()

Runs a function once after a delay. For example, in the code below, the message will be displayed after 2 seconds.

setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000); // 2000 ms = 2 seconds

setInterval()

Runs a function repeatedly at fixed intervals. By default, it acts like an infinite loop.

setInterval(() => {
  console.log("Runs every 1 second");
}, 1000);

// If you want to stop after certain condition is met then see below code

let count = 0; // To keep track of how many times it runs

// Start the interval and store its ID
let intervalId = setInterval(() => {
  count++;
  console.log("Runs every 1 second. Count:", count);

  // Stop after 5 runs
  if (count === 5) {
    clearInterval(intervalId);
    console.log("βœ… Interval stopped after 5 seconds");
  }
}, 1000);

Math Object

Math objects are predefined mathematical methods used to perform mathematical calculations on numerical values.

console.log(Math.PI);
// Returns the value of Ο€ (pi)
// Output: 3.141592653589793

console.log(Math.round(4.6));
// Rounds to the nearest integer
// Output: 5

console.log(Math.floor(4.9));
// Always rounds down
// Output: 4

console.log(Math.ceil(4.1));
// Always rounds up
// Output: 5

console.log(Math.pow(2, 3));
// Returns x raised to the power of y (x^y)
// Output: 8

console.log(Math.sqrt(16));
// Square root of x
// Output: 4

console.log(Math.abs(-9));
// Returns the absolute (positive) value
// Output: 9

console.log(Math.min(3, 5, 1, 7));
// Returns the smallest value
// Output: 1

console.log(Math.max(3, 5, 1, 7));
// Returns the largest value
// Output: 7

console.log(Math.random());
// Random number between 0 and 1
// Output: e.g., 0.523 (changes every time)

console.log(Math.random() * 10);
// Random number between 0 and 10
// Output: e.g., 7.431 (changes every time)

String Methods

Functions for working with text (strings).

let msg = "Hello";

console.log(msg.toUpperCase()); // HELLO
console.log(msg.toLowerCase()); // hello
console.log(msg.length); // 5 total number of characters (spaces included)
console.log(msg.includes("he")); // true

let msg = "Welcome to JavaScript";
console.log(msg.slice(11, 21)); 
// Output: "JavaScript" β†’ from index 11 to 20

console.log(msg.indexOf("JavaScript"));
// Output: 11 β†’ position of substring

Boolean Logic

Use true / false values and logical operators to make decisions.

let isLoggedIn = true;
let isAdmin = false;

if (isLoggedIn && isAdmin) {
  console.log("Access granted");
} else {
  console.log("Access denied");
}

// Logical operators:
&& (AND) β†’ both must be true
|| (OR) β†’ at least one must be true
! (NOT) β†’ reverses true/false

null & undefined

null – Use null when you intentionally set something to β€œnothing”.
undefined – often shown by JavaScript automatically when something is missing or uninitialized. It helps during development and debugging.

let a = null;
let b;

console.log(a); // null
console.log(b); // undefined

try / catch

Used to handle errors without crashing your program.

try {
  let result = someFunction(); // If this fails...
} catch (error) {
  console.log("An error occurred:", error.message);
}

/* EXPLANATION

try { ... }
This block contains code you β€œtry” to run safely.
If anything inside the try block causes an error, the program won’t crash β€” it jumps straight to the catch block.

let result = someFunction();
This line tries to call a function named someFunction.
If someFunction(): works, result is stored in result.
If someFunction(): throws an error, control jumps to catch block.

catch (error) { ... }
This block catches the error if something inside the try block fails. The error object gives info about what went wrong.

console.log("An error occurred:", error.message);
This prints a friendly message + the actual error reason to the console.
The error.message part gives a readable explanation of error like "An error occurred: something went wrong". */

Here is a real-world example to help you better understand how try, catch, and throw work together.

function divideNumbers(a, b) {
  try {
    // Try to divide
    let result = a / b;

    // Check if result is invalid (like divide by 0 or non-number)
    if (!isFinite(result)) {
      throw new Error("Cannot divide by zero or invalid number");
    }

    console.log("βœ… Result:", result);
  } catch (error) {
    console.log("❌ Error:", error.message);
  }
}

// Try with valid numbers
divideNumbers(10, 2); // βœ… Result: 5

// Try dividing by 0
divideNumbers(10, 0); // ❌ Error: Cannot divide by zero or invalid number

// Try with invalid input
divideNumbers("abc", 5); // ❌ Error: Cannot divide by zero or invalid number

Template Literals

Allows you to insert variables inside strings easily using backticks.

let name = "John";
console.log(`Hello, ${name}!`);

// Output: Hello, John!

Example: Show Message on Button Click

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>JS Example: Show Message on Button Click</title>
</head>

<body>

	<p>JS Example: Show Message on Button Click</p>

	<button onclick="showMessage()">Click Me</button>

</body>

<script type="text/javascript">
    function showMessage() {
      alert("You clicked the button!");
    }
</script>
    
</html>

How to Practice JavaScript

Use these free tools to test your JS code live and observe the output:

Final Thoughts

JavaScript is a powerful scripting language, and these 25 basics are your first step into the real-world web development. Keep practicing and slowly build real projects to gain confidence.

πŸ’¬ Got questions or want more beginner tutorials? Drop a comment below or explore more on this blog.

Sharing Is Caring...