Start your JavaScript journey with fundamental concepts, syntax, variables, and basic operations.
Start your JavaScript journey with fundamental concepts, syntax, variables, and basic operations.
Learn about JavaScript's history, evolution, and why it's the most popular programming language in 2025
Content by: Kriyansh Khunt
MERN Stack Developer
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web. Originally created by Brendan Eich at Netscape in 1995, JavaScript has evolved from a simple scripting language to a powerful, versatile programming language that runs everywhere.
// Frontend Development
// React, Vue, Angular applications
const App = () => {
return <div>Hello World</div>;
};
// Backend Development
// Node.js server applications
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Node.js!');
});
// Mobile Development
// React Native applications
import React from 'react';
import { Text, View } from 'react-native';
// Desktop Applications
// Electron applications
const { app, BrowserWindow } = require('electron');// Browser Environment
console.log('Running in browser');
window.addEventListener('load', () => {
console.log('Page loaded');
});
// Node.js Environment
console.log('Running in Node.js');
process.on('exit', () => {
console.log('Process exiting');
});
// Deno Environment
console.log('Running in Deno');
Deno.serve(() => new Response('Hello from Deno'));// 1. Browser Hello World
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Hello World</title>
</head>
<body>
<h1 id="greeting">Hello World!</h1>
<button onclick="changeGreeting()">Click Me!</button>
<script>
function changeGreeting() {
const greeting = document.getElementById('greeting');
greeting.textContent = 'Hello from JavaScript!';
}
</script>
</body>
</html>
// 2. Node.js Hello World
// hello.js
console.log('Hello World from Node.js!');
// Run with: node hello.js
// 3. Modern ES6+ Hello World
const greet = (name = 'World') => {
return `Hello, ${name}!`;
};
console.log(greet()); // Hello, World!
console.log(greet('JavaScript')); // Hello, JavaScript!Test your understanding of this topic:
Master JavaScript variables, data types, and type conversion for effective programming
Content by: Praveen Kumar
MERN Stack Developer
JavaScript provides three ways to declare variables: var (legacy), let (block-scoped), and const (immutable). Each has different scoping rules and mutability characteristics.
// Variable declaration methods
// 1. var (function-scoped, legacy)
var oldWay = "This is the old way";
console.log(oldWay);
// 2. let (block-scoped, mutable)
let modernWay = "This is the modern way";
modernWay = "This can be changed";
console.log(modernWay);
// 3. const (block-scoped, immutable)
const constantValue = "This cannot be changed";
// constantValue = "This will cause an error"; // Error!
// Block scoping example
{
let blockScoped = "Only available in this block";
const alsoBlockScoped = "Also only in this block";
}
// console.log(blockScoped); // ReferenceError// Primitive types
let number = 42;
let string = "Hello World";
let boolean = true;
let undefinedVar = undefined;
let nullVar = null;
let symbol = Symbol('unique');
let bigint = 123n;
// Reference types
let object = { name: "John", age: 30 };
let array = [1, 2, 3, 4, 5];
let functionVar = function() { return "Hello"; };
let date = new Date();
let regex = /pattern/gi;
// Type checking
console.log(typeof number); // "number"
console.log(typeof string); // "string"
console.log(typeof boolean); // "boolean"
console.log(typeof undefinedVar); // "undefined"
console.log(typeof nullVar); // "object" (historical quirk)
console.log(typeof symbol); // "symbol"
console.log(typeof bigint); // "bigint"
console.log(typeof object); // "object"
console.log(typeof array); // "object"
console.log(typeof functionVar); // "function"// Explicit type conversion
let num = 42;
let str = String(num); // "42"
let bool = Boolean(num); // true
let numFromStr = Number("123"); // 123
// Implicit type coercion
console.log(1 + "2"); // "12" (string concatenation)
console.log("2" + 1); // "21" (string concatenation)
console.log(1 - "2"); // -1 (numeric subtraction)
console.log("2" - 1); // 1 (numeric subtraction)
console.log(true + 1); // 2 (boolean to number)
console.log(false + 1); // 1 (boolean to number)
// Truthy and falsy values
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("0")); // true
console.log(Boolean("false")); // true// Type Converter Tool
class TypeConverter {
static toNumber(value) {
const num = Number(value);
if (isNaN(num)) {
throw new Error(`Cannot convert "${value}" to number`);
}
return num;
}
static toString(value) {
return String(value);
}
static toBoolean(value) {
return Boolean(value);
}
static getType(value) {
return typeof value;
}
static isPrimitive(value) {
return typeof value !== 'object' || value === null;
}
}
// Usage examples
try {
console.log(TypeConverter.toNumber("123")); // 123
console.log(TypeConverter.toString(456)); // "456"
console.log(TypeConverter.toBoolean("hello")); // true
console.log(TypeConverter.getType([1, 2, 3])); // "object"
console.log(TypeConverter.isPrimitive("test")); // true
console.log(TypeConverter.isPrimitive([1, 2])); // false
} catch (error) {
console.error(error.message);
}
// Advanced type checking
function getDetailedType(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
if (value instanceof Date) return 'date';
if (value instanceof RegExp) return 'regexp';
if (typeof value === 'function') return 'function';
return typeof value;
}
console.log(getDetailedType(null)); // "null"
console.log(getDetailedType([])); // "array"
console.log(getDetailedType(new Date())); // "date"
console.log(getDetailedType(/test/)); // "regexp"
console.log(getDetailedType(() => {})); // "function"Test your understanding of this topic:
Learn JavaScript operators, expressions, and how to perform calculations and comparisons
Content by: Sachin Patel
Node.js Developer
// Basic arithmetic operators
let a = 10;
let b = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (modulus)
console.log(a ** b); // 1000 (exponentiation)
// String concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "John Doe"
// Increment and decrement
let counter = 5;
console.log(++counter); // 6 (pre-increment)
console.log(counter++); // 6 (post-increment, then becomes 7)
console.log(--counter); // 6 (pre-decrement)
console.log(counter--); // 6 (post-decrement, then becomes 5)// Equality comparisons
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (no type coercion)
console.log(5 != "5"); // false (type coercion)
console.log(5 !== "5"); // true (no type coercion)
// Numeric comparisons
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10 <= 5); // false
// Special cases
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // true
// String comparisons (lexicographic)
console.log("apple" < "banana"); // true
console.log("Z" < "a"); // false (uppercase comes first)// Logical AND (&&)
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
// Logical OR (||)
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
// Logical NOT (!)
console.log(!true); // false
console.log(!false); // true
console.log(!!"hello"); // true (double negation)
// Short-circuit evaluation
let user = null;
let username = user && user.name; // null (short-circuits)
let defaultName = user || "Guest"; // "Guest" (fallback)
// Practical examples
let age = 25;
let hasLicense = true;
let canDrive = age >= 18 && hasLicense; // true
let weather = "sunny";
let temperature = 75;
let goodWeather = weather === "sunny" || temperature > 70; // true// Simple Calculator Application
class Calculator {
constructor() {
this.display = document.getElementById('display');
this.currentInput = '';
this.operator = null;
this.previousInput = null;
}
addNumber(number) {
this.currentInput += number;
this.updateDisplay();
}
setOperator(op) {
if (this.currentInput) {
this.previousInput = this.currentInput;
this.currentInput = '';
this.operator = op;
}
}
calculate() {
if (this.previousInput && this.currentInput && this.operator) {
const prev = parseFloat(this.previousInput);
const current = parseFloat(this.currentInput);
let result;
switch (this.operator) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
result = current !== 0 ? prev / current : 'Error';
break;
case '**':
result = prev ** current;
break;
default:
result = current;
}
this.currentInput = result.toString();
this.previousInput = null;
this.operator = null;
this.updateDisplay();
}
}
clear() {
this.currentInput = '';
this.previousInput = null;
this.operator = null;
this.updateDisplay();
}
updateDisplay() {
this.display.value = this.currentInput || '0';
}
}
// Advanced expression evaluator
function evaluateExpression(expression) {
try {
// Simple expression evaluator (for educational purposes)
// In production, use a proper math parser library
const result = Function('"use strict"; return (' + expression + ')')();
return isNaN(result) ? 'Invalid expression' : result;
} catch (error) {
return 'Invalid expression';
}
}
// Test the calculator
console.log(evaluateExpression('2 + 3 * 4')); // 14
console.log(evaluateExpression('(2 + 3) * 4')); // 20
console.log(evaluateExpression('2 ** 3')); // 8
console.log(evaluateExpression('10 / 2')); // 5Test your understanding of this topic:
Master JavaScript syntax, statements, comments, and code formatting for clean, readable code
Content by: Parth Patel
Node.js Developer
JavaScript programs are made up of statements. Each statement performs a specific action and is terminated with a semicolon. Statements can be simple or complex, and they control the flow of execution in your program.
// Expression statements
let x = 5;
let y = x + 3;
console.log(y);
// Declaration statements
let name = "John";
const age = 30;
var city = "New York";
// Control flow statements
if (x > 0) {
console.log("Positive number");
} else {
console.log("Non-positive number");
}
// Loop statements
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Function statements
function greet(name) {
return "Hello, " + name + "!";
}
// Return statements
function add(a, b) {
return a + b;
}
// Break and continue statements
for (let i = 0; i < 10; i++) {
if (i === 5) break;
if (i % 2 === 0) continue;
console.log(i);
}// Single-line comment
let price = 100; // Price in dollars
/* Multi-line comment
This is useful for longer explanations
that span multiple lines */
let discount = 0.1;
/**
* JSDoc comment for function documentation
* @param {number} price - The original price
* @param {number} discount - The discount percentage (0-1)
* @returns {number} The discounted price
*/
function calculateDiscount(price, discount) {
return price * (1 - discount);
}
// Good comment example
// Calculate compound interest using the formula A = P(1 + r/n)^(nt)
let principal = 1000;
let rate = 0.05;
let time = 2;
let compoundInterest = principal * Math.pow(1 + rate, time);
// Bad comment example (obvious)
let name = "John"; // Set name to John
// Good comment example (explains why)
let config = {
apiUrl: "https://api.example.com", // Use production API
timeout: 5000 // 5 second timeout for slow networks
};// Consistent indentation (2 or 4 spaces)
function formatCode() {
if (true) {
console.log("Properly indented");
if (true) {
console.log("Nested properly");
}
}
}
// Consistent spacing
let sum = a + b; // Good spacing
let product = x * y; // Good spacing
let quotient = a / b; // Good spacing
// Consistent naming conventions
let userName = "john"; // camelCase for variables
const MAX_USERS = 100; // UPPER_CASE for constants
function getUserName() { // camelCase for functions
return userName;
}
// Consistent quote usage
let message = "Hello World"; // Double quotes
let anotherMessage = 'Hi there'; // Single quotes (be consistent)
// Line length and readability
let longVariableName = "This is a very long string that might exceed the recommended line length and should be broken into multiple lines for better readability";
// Better formatting
let longVariableName = "This is a very long string that " +
"might exceed the recommended line length and " +
"should be broken into multiple lines for " +
"better readability";// Simple Code Formatter
class CodeFormatter {
static formatBasic(code) {
// Basic formatting rules
return code
.replace(/s*{s*/g, ' {
') // Opening braces
.replace(/s*}s*/g, '
}
') // Closing braces
.replace(/;s*/g, ';
') // Semicolons
.replace(/
s*
/g, '
') // Multiple newlines
.trim();
}
static addComments(code, language = 'javascript') {
const commentMap = {
javascript: '//',
python: '#',
css: '/*',
html: '<!--'
};
const comment = commentMap[language] || '//';
return code.split('
').map(line => {
if (line.trim() && !line.trim().startsWith(comment)) {
return line + ' ' + comment + ' ' + this.generateComment(line);
}
return line;
}).join('
');
}
static generateComment(line) {
// Simple comment generation based on code patterns
if (line.includes('if')) return 'Conditional statement';
if (line.includes('for')) return 'Loop statement';
if (line.includes('function')) return 'Function definition';
if (line.includes('return')) return 'Return statement';
if (line.includes('console.log')) return 'Debug output';
return 'Code line';
}
static validateSyntax(code) {
try {
// Basic syntax validation
new Function(code);
return { valid: true, error: null };
} catch (error) {
return { valid: false, error: error.message };
}
}
}
// Usage examples
let sampleCode = `function greet(name) {if(name) {console.log("Hello " + name);} else {console.log("Hello World");}}`;
console.log("Original code:");
console.log(sampleCode);
console.log("
Formatted code:");
let formatted = CodeFormatter.formatBasic(sampleCode);
console.log(formatted);
console.log("
With comments:");
let withComments = CodeFormatter.addComments(formatted);
console.log(withComments);
console.log("
Syntax validation:");
let validation = CodeFormatter.validateSyntax(sampleCode);
console.log(validation);
// Advanced formatting with proper indentation
function formatWithIndentation(code) {
let lines = code.split('
');
let indentLevel = 0;
const indentSize = 4;
return lines.map(line => {
const trimmed = line.trim();
if (!trimmed) return '';
// Decrease indent for closing braces
if (trimmed.startsWith('}')) {
indentLevel = Math.max(0, indentLevel - 1);
}
const indented = ' '.repeat(indentLevel * indentSize) + trimmed;
// Increase indent for opening braces
if (trimmed.endsWith('{')) {
indentLevel++;
}
return indented;
}).join('
');
}Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 2