Algo Infinity Verse

Start Your Journey With JavaScript Programming Beginner-Friendly Concepts, Code & Practice

|
0 Topics
0 Examples
0 Exercises

🟨 Learn JavaScript

Master the building blocks of the web with step-by-step interactive lessons

0 / 12 topics completed
01

Introduction to JavaScript

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js.

Why Learn JavaScript?

  • Programming for the Web – It is supported by all modern web browsers and forms the core of front-end web development.
  • Full-Stack Potential – Write JavaScript on both the frontend (browser) and backend (Node.js).
  • Rich Ecosystem – Power modern single-page applications with frameworks like React, Vue, and Angular.

Your first JavaScript statement prints a greeting to the developers' console:

JavaScript
console.log('Welcome to JavaScript!');
Console Output
Welcome to JavaScript!
💡

Unlike Python, JavaScript statements traditionally end with a semicolon (;). While optional in many cases due to Automatic Semicolon Insertion, it is considered a best practice to write them.

Practice: Hello World

Log a greeting message to the console using console.log().

JavaScript
console.log("Hello, JavaScript Learner!");
02

Setup & Browser Console

To start coding in JavaScript, you don't need any complex installation. Every web browser has a built-in JavaScript engine and a developer tool console.

Opening the Console

  • Chrome/Edge/Brave: Press F12 or Ctrl+Shift+I (Windows/Linux) / Cmd+Option+I (macOS) and click on the "Console" tab.
  • Firefox: Press Ctrl+Shift+K (Windows/Linux) / Cmd+Option+K (macOS).
  • Safari: Enable "Develop" menu in settings, then press Cmd+Option+C.

You can embed JavaScript directly inside an HTML file using the <script> tag:

HTML
<!-- Inside HTML body -->
<script>
  console.log('Script is running!');
</script>
Practice: Logging Active Status

Write a script statement that outputs "Console is active!" to verify your understanding of console logging.

JavaScript
console.log("Console is active!");
03

Variables (let, const, var)

Variables are containers for storing data values. In modern JavaScript, we declare variables using three keywords: let, const, and var.

let vs const vs var

  • let: Block-scoped. Can be reassigned. Use when you expect the value to change.
  • const: Block-scoped. Blocked from reassignment. Use by default for stable values.
  • var: Function-scoped (legacy). Subject to hoisting anomalies. Generally avoided in modern JS.
JavaScript
let score = 10;
score = 15; // Allowed

const pi = 3.14159;
// pi = 3.14; // Throws Error!
Practice: Declaring Variables

Create a mutable variable named userAge set to 20, and an immutable variable named countryOfBirth set to "India".

JavaScript
let userAge = 20;
const countryOfBirth = "India";
04

Data Types

JavaScript is a dynamically typed language, meaning variables don't hold fixed types. Instead, types are associated with values.

Type Example Description
String"Alice"Textual characters
Number42 or 3.14Integers and double-precision floats
Booleantrue / falseLogical truths
UndefinedundefinedAssigned to variables without initialized value
NullnullExplicit empty or non-existent value
BigInt9007199254740991nArbitrary precision integers
Object{ id: 1 }Non-primitive key-value collections
JavaScript
console.log(typeof 'Hello'); // "string"
console.log(typeof 42);      // "number"
console.log(typeof true);    // "boolean"
Practice: Type Checking

Check the data type of the value 99.9 using the typeof operator.

JavaScript
console.log(typeof 99.9); // Outputs: "number"
05

Operators

Operators allow us to perform operations on variables and values. Essential operator types include arithmetic, assignment, comparison, and logical operators.

Strict Equality (===) vs Loose Equality (==)

  • Loose (==): Performs type coercion before comparing (e.g. 5 == "5" is true).
  • Strict (===): Checks both value and type without coercion (e.g. 5 === "5" is false). Always prefer strict equality.
JavaScript
let sum = 10 + 5;
console.log(10 === '10'); // false
console.log(10 == '10');  // true
Practice: Calculations

Calculate the area of a rectangle with a width of 8 and length of 12, storing it in a variable named area.

JavaScript
const width = 8;
const length = 12;
const area = width * length;
console.log(area); // 96
06

Input and Output

While console.log() is perfect for developers, browsers support other built-in dialog functions for interacting with standard users: alert() and prompt().

JavaScript
alert('Welcome to Algo Infinity!');

let userName = prompt('What is your name?');
if (userName) {
  console.log('Hello, ' + userName);
}
⚠️

Both alert() and prompt() block the main thread and pause browser interaction. Use them sparingly or design custom HTML dialog forms for modern UI layouts.

Practice: User Prompt

Prompt the user for their favorite programming language and alert it back to them.

JavaScript
let favLang = prompt("What is your favorite language?");
if (favLang) {
  alert("You like " + favLang + "!");
}
07

Conditional Statements

Conditionals direct execution flow by testing logic states. JavaScript supports if, else if, else, and switch blocks.

JavaScript
let score = 85;
if (score >= 90) {
  console.log('Grade: A');
} else if (score >= 80) {
  console.log('Grade: B');
} else {
  console.log('Grade: F');
}
Practice: Even or Odd

Write an if/else condition that logs "Even" if a variable num is even, or "Odd" otherwise.

JavaScript
let num = 17;
if (num % 2 === 0) {
  console.log("Even");
} else {
  console.log("Odd");
}
08

Loops (for, while, for...of)

Loops repeat execution. JavaScript features standard for index loops, conditional while loops, and collection-centric for...of loops.

JavaScript
// Classic loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// for...of loop
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
  console.log(color);
}
Practice: Count to Ten

Write a loop that logs numbers from 1 to 10 to the console.

JavaScript
for (let i = 1; i <= 10; i++) {
  console.log(i);
}
09

Functions and Arrow Functions

Functions package modular blocks of code. JavaScript supports standard declarations as well as ES6 concise arrow functions (() => {}).

JavaScript
// Traditional function
function add(a, b) {
  return a + b;
}

// ES6 Arrow function
const multiply = (a, b) => a * b;
Practice: Square Function

Create an arrow function named square that accepts a single number and returns its squared value.

JavaScript
const square = (n) => n * n;
console.log(square(5)); // 25
10

Arrays and Objects

Arrays represent ordered indexed lists, and Objects represent keyed collection dictionaries. They are the key structures for managing complex application data states.

JavaScript
// Array setup
const fruits = ['apple', 'banana'];
fruits.push('orange');

// Object setup
const user = {
  name: 'Alice',
  age: 25
};
console.log(user.name);
Practice: Object Attributes

Create an object representing a car with properties brand, model, and year. Log the model value.

JavaScript
const car = {
  brand: "Tesla",
  model: "Model 3",
  year: 2023
};
console.log(car.model);
11

DOM Manipulation Basics

The Document Object Model (DOM) is the programming interface for web documents. It represents the page structure so that programs can change document structure, style, and content.

JavaScript
// DOM Selection & Update
const title = document.getElementById('my-title');
title.textContent = 'Hello, Interactive DOM!';
title.style.color = '#7c3aed';
Practice: Modifying Content

Write a JS statement to select an element with the ID main-heading and change its text content to "Welcome to JavaScript!".

JavaScript
document.getElementById("main-heading").textContent = "Welcome to JavaScript!";
12

Event Handling Basics

JavaScript reacts to user interactions via events. By registering event listeners using addEventListener(), elements trigger functions on click, input, submit, and more.

JavaScript
// Event registration
const btn = document.querySelector('#action-btn');
btn.addEventListener('click', (event) => {
  console.log('Button clicked!');
});
Practice: Click Listener

Register a click event listener on a button with ID "submit-btn" that alerts "Form Submitted!".

JavaScript
document.getElementById("submit-btn").addEventListener("click", () => {
  alert("Form Submitted!");
});