JavaScript Fundamentals

Learn the core concepts of JavaScript programming with practical examples and interactive demonstrations.

Essential Concepts

Variables

In JavaScript, variables are used to store data values. You can declare variables using var, let, or const.

// Using var (function-scoped)
var name = "John";

// Using let (block-scoped)
let age = 25;

// Using const (block-scoped, immutable reference)
const PI = 3.14;

Functions

Functions are blocks of code designed to perform specific tasks. They can take parameters and return values.

// Function declaration
function greet(name) {
  return "Hello, " + name + "!";
}

// Arrow function (ES6+)
const add = (a, b) => a + b;

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(add(5, 3)); // Output: 8

Arrays

Arrays are used to store multiple values in a single variable. They can contain any data type.

// Creating an array
const fruits = ["apple", "banana", "orange"];

// Adding elements
fruits.push("grape");

// Iterating through array
fruits.forEach(fruit => console.log(fruit));

Object Example

Objects are collections of key-value pairs that represent entities with properties and methods.

// Creating an object
const person = {
  name: "John",
  age: 30,
  greet: function() {
    return "Hello, I'm " + this.name;
  }
};

console.log(person.name); // Output: John
console.log(person.greet()); // Output: Hello, I'm John

Interactive Example

Try out this simple calculator function:

function calculate(operation, num1, num2) {
  switch(operation) {
    case 'add':
      return num1 + num2;
    case 'subtract':
      return num1 - num2;
    case 'multiply':
      return num1 * num2;
    case 'divide':
      if(num2 !== 0) return num1 / num2;
      else return "Cannot divide by zero";
    default:
      return "Invalid operation";
  }
}

// Examples
console.log(calculate('add', 10, 5)); // Output: 15
console.log(calculate('multiply', 4, 6)); // Output: 24