JavaScript Notes
What is JavaScript? Learn what JavaScript is, how it works, key features, and why it
Introduction
JavaScript is the programming language of the web. Every time you interact with a website — clicking buttons, filling out forms, seeing animations, getting real-time updates — JavaScript is working behind the scenes to make it all happen.
In this comprehensive guide, we will explore everything about JavaScript: its definition, core features, how it works, and why it has become the most important programming language in modern software development. Whether you're an absolute beginner wondering "What is JavaScript?" or someone brushing up on the fundamentals, this guide covers it all.
Real World Analogy: JavaScript is Like the Muscles of a Body
Imagine a human body:
- HTML is the skeleton — gives structure (bones, organs)
- CSS is the skin and clothes — gives appearance
- JavaScript is the muscles and nervous system — gives movement and response
Without JavaScript, websites would be like beautiful statues — pretty to look at, but completely frozen. JavaScript makes them alive — they respond to you, change in real-time, and feel interactive.
Key Characteristics of JavaScript
1. Interpreted Language
JavaScript code is executed line by line by the browser's JavaScript engine. Unlike compiled languages (C, C++, Java), you do not need to compile JavaScript code before running it.
// This code runs directly in the browser — no compilation needed!
console.log("Hello, World!");
console.log("JavaScript is interpreted!");
console.log("No build step required.");Hello, World! JavaScript is interpreted! No build step required.
Note: Modern engines actually do compile JavaScript at runtime using JIT (Just-In-Time) compilation for performance, but from the developer's perspective it still feels "interpreted" — no manual compilation step.
2. Dynamically Typed
You do not need to declare the data type of a variable. JavaScript figures out the type automatically at runtime.
let message = "Hello"; // automatically a string
console.log(typeof message); // "string"
message = 42; // changed to a number
console.log(typeof message); // "number"
message = true; // changed to a boolean
console.log(typeof message); // "boolean"
message = { name: "Rahul" }; // changed to an object
console.log(typeof message); // "object"
// JavaScript variables are containers — they can hold anything!string number boolean object
3. Multi-Paradigm Language
JavaScript supports multiple programming styles — you can write code in different ways depending on what's clearest for the problem:
Procedural: 15 OOP: 15 Functional: [15, 28, 18]
4. Event-Driven
JavaScript responds to user actions (events) like clicks, key presses, mouse movements, and more. This is what makes web pages interactive:
// Event-driven programming model
// (This would work in a browser — using DOM)
document.getElementById("myButton").addEventListener("click", function() {
alert("You clicked the button!");
});
// The function above WAITS — does nothing until button is clicked
// When clicked → function runs → alert appears!
// Other common events:
// "click" → mouse click
// "keydown" → keyboard key pressed
// "mouseover" → mouse hovers over element
// "submit" → form submitted
// "load" → page finished loading
// "change" → input value changed
console.log("Event listeners are waiting for user actions...");Event listeners are waiting for user actions...
5. Single-Threaded with Asynchronous Capabilities
JavaScript runs on a single thread but can handle asynchronous operations gracefully — so slow operations (network requests, timers) don't freeze the page:
console.log("1: Start");
// This timer runs "in the background" — doesn't block code!
setTimeout(function() {
console.log("3: Timer fired (after 2 seconds)");
}, 2000);
console.log("2: End — JS didn't wait for the timer!");1: Start 2: End — JS didn't wait for the timer! 3: Timer fired (after 2 seconds)
The output order (1, 2, 3) shows that JavaScript didn't freeze while waiting for the timer. The page remained fully responsive.
How JavaScript Works: The Engine
Every browser has a JavaScript engine that reads, understands, and runs your code:
| Browser | Engine | Notes |
|---|---|---|
| Google Chrome | V8 | Also used in Node.js, Edge |
| Mozilla Firefox | SpiderMonkey | Oldest JS engine (1996) |
| Safari | JavaScriptCore (Nitro) | Used in Bun too |
| Microsoft Edge | V8 | Switched to Chromium in 2020 |
Where JavaScript Runs
1. In the Browser (Client-Side)
JavaScript was originally designed to run in web browsers — this is its home turf:
Stored name: Rahul
2. On the Server (Node.js)
Since 2009, JavaScript can run on servers using Node.js — making it a full-stack language:
Server running at http://localhost:3000
3. Mobile Applications
Using React Native, you can build real mobile apps that run on iOS and Android:
// Renders a native mobile app: // - Text: "Hello from React Native!" // - Button: "Tap Me" // - Tap button → native alert appears on phone
4. Desktop Applications
Using Electron.js, VS Code, Discord, and Slack are all built with JavaScript:
// Electron main process
const { app, BrowserWindow } = require("electron");
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: { nodeIntegration: true }
});
win.loadFile("index.html");
console.log("Desktop window created!");
}
app.whenReady().then(createWindow);Desktop window created!
JavaScript vs Java — The Biggest Confusion for Beginners!
Many beginners think JavaScript and Java are related. They are NOT. The name "JavaScript" was a marketing decision by Netscape in 1995 to leverage Java's popularity at the time.
// JavaScript: Dynamic and flexible
let greeting = "Hello"; // No type declaration
greeting = 123; // Can change type
greeting = true; // Still fine!
console.log(greeting, typeof greeting);
// Equivalent Java would require:
// String greeting = "Hello"; // Must declare type
// greeting = 123; // ERROR — cannot reassign different type!true boolean
Your First JavaScript Programs
Let's write some real JavaScript — run these in your browser console (F12 → Console tab):
Program 1: Hello World
console.log("Hello, World!");
console.log("My name is Rahul.");
console.log("I am learning JavaScript!");Hello, World! My name is Rahul. I am learning JavaScript!
Program 2: Variables and Math
Student: Priya Sharma Age: 22 Marks: [88, 92, 79, 95, 87] Average: 88.2 Grade: A
Program 3: Interactive Function
🎉 Welcome, Amit Kumar! 📚 You're enrolled in: JavaScript Master Course 🚀 Let's start your JavaScript journey! 💡 Pro tip: Practice every day for best results.
Features That Make JavaScript Unique
1. First-Class Functions
Functions in JavaScript are treated as values — they can be stored in variables, passed as arguments, and returned from other functions:
// Function stored in a variable
const greet = function(name) {
return "Hello, " + name + "!";
};
// Function passed as argument (callback)
function executeFunction(fn, value) {
return fn(value);
}
console.log(executeFunction(greet, "Rahul"));
// Function returning a function (Higher-Order Function)
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(double(10)); // 20Hello, Rahul! 10 15 20
2. Closures
A function can remember variables from its outer scope even after the outer function has finished:
11 12 13 12 10 10
3. Prototypal Inheritance
JavaScript uses prototypes for sharing behavior between objects:
function Animal(name, sound) {
this.name = name;
this.sound = sound;
}
// All Animal instances share this method via prototype
Animal.prototype.speak = function() {
return `${this.name} says "${this.sound}"`;
};
Animal.prototype.introduce = function() {
return `I am ${this.name}, a ${this.constructor.name}.`;
};
const dog = new Animal("Rex", "Woof");
const cat = new Animal("Whiskers", "Meow");
const cow = new Animal("Bessie", "Moo");
console.log(dog.speak());
console.log(cat.speak());
console.log(cow.speak());
console.log(dog.introduce());Rex says "Woof" Whiskers says "Meow" Bessie says "Moo" I am Rex, a Animal.
4. Asynchronous Programming with Async/Await
Fetching user... Name: Amit Singh Role: Developer Profile loaded successfully!
The JavaScript Ecosystem
JavaScript has the largest package ecosystem in the world:
Common Mistakes Beginners Make
1. Confusing == and ===
// == (loose equality) converts types before comparing
console.log(5 == "5"); // true (string "5" → number 5)
console.log(0 == false); // true (false → 0)
console.log("" == false); // true (both falsy)
// === (strict equality) checks value AND type — always prefer this!
console.log(5 === "5"); // false (different types)
console.log(0 === false); // false (number vs boolean)
console.log("" === false);// false (string vs boolean)
// BEST PRACTICE: Always use ===
if (userAge === 18) {
console.log("Exactly 18!");
}true true true false false false
2. Not Understanding Hoisting
// Function declarations are fully hoisted — you can call them before declaring!
sayHello(); // This WORKS!
function sayHello() {
console.log("Hello! (function declarations are hoisted)");
}
// var is hoisted but initialized as undefined
console.log(myVar); // undefined — NOT an error!
var myVar = "I exist now";
console.log(myVar); // "I exist now"
// let and const are NOT accessible before declaration
// console.log(myLet); // ReferenceError: Cannot access before initialization
let myLet = "Let variable";Hello! (function declarations are hoisted) undefined I exist now
3. The Infamous this Keyword
Regular function: Hello, Rahul Arrow function: Hello, undefined
4. Forgetting semicolons (and relying on ASI)
// JavaScript has Automatic Semicolon Insertion (ASI)
// but it can cause bugs!
// This looks like it returns an object:
function getObject() {
return // ← ASI inserts semicolon HERE!
{ // This line is unreachable!
name: "Rahul"
};
}
console.log(getObject()); // undefined — NOT the object!
// FIX: Put the opening brace on the same line as return
function getObjectFixed() {
return { // ← brace on same line — no ASI problem
name: "Rahul"
};
}
console.log(getObjectFixed()); // { name: "Rahul" }undefined
{ name: 'Rahul' }5. Modifying an Array While Iterating
Evens: [2, 4] Original unchanged: [1, 2, 3, 4, 5] Doubled: [2, 4, 6, 8, 10]
Best Practices for Writing Good JavaScript
1. Use const and let — Never var
API: https://api.wohotech.com Login count: 1
2. Use Meaningful Names
Rahul is 25 years old Sum: 30
3. Always Handle Errors
function parseJSON(jsonString) {
try {
const data = JSON.parse(jsonString);
return { success: true, data };
} catch (error) {
return { success: false, error: error.message };
}
}
const valid = parseJSON('{"name": "Rahul", "age": 25}');
console.log("Valid JSON:", valid.data);
const invalid = parseJSON("this is not JSON!");
console.log("Invalid JSON error:", invalid.error);Valid JSON: { name: 'Rahul', age: 25 }
Invalid JSON error: Unexpected token h in JSON at position 1Key Takeaways
| Concept | Summary |
|---|---|
| What is JS | High-level, interpreted, dynamic language for the web |
| Where it runs | Browser, Node.js, mobile (React Native), desktop (Electron) |
| Key feature 1 | Dynamic typing — variables can hold any type |
| Key feature 2 | Event-driven — responds to user interactions |
| Key feature 3 | Async-capable — non-blocking via callbacks, promises, async/await |
| Key feature 4 | First-class functions — functions are values |
| Key feature 5 | Prototype-based inheritance |
| Ecosystem | npm: 2.5M+ packages; React, Node, Next.js, React Native |
| Career | Most demanded language globally |
| vs Java | Completely different — just share a name for marketing reasons |
Interview Questions
Q1: What is JavaScript?
Answer: JavaScript is a high-level, interpreted, dynamically-typed programming language primarily used to create interactive web pages. It supports multiple programming paradigms (OOP, functional, procedural) and runs in browsers natively, on servers via Node.js, and on mobile via React Native.
Q2: Is JavaScript compiled or interpreted?
Answer: Historically interpreted, but modern engines (like V8) use JIT (Just-In-Time) compilation. Code is first interpreted from bytecode for fast startup, then frequently-called ("hot") functions are compiled to optimized machine code at runtime for performance.
Q3: What is the difference between JavaScript and ECMAScript?
Answer: ECMAScript is the standard/specification defining the language rules (maintained by ECMA TC39). JavaScript is the most popular implementation of that standard. Think of ECMAScript as the blueprint and JavaScript as the actual building.
Q4: What does "dynamically typed" mean?
Answer: Variable types are determined at runtime, not at declaration time. A variable can hold a string, then a number, then a boolean — no type declaration needed. Contrast with statically typed languages (Java, TypeScript) where types must be declared upfront.
Q5: What is the difference between == and ===?
Answer: == (loose equality) compares values after type coercion — 5 == "5" is true. === (strict equality) compares both value AND type without coercion — 5 === "5" is false. Always use === to avoid unexpected behavior.
Q6: What are the data types in JavaScript?
Answer: 8 types total. 7 primitives: string, number, bigint, boolean, undefined, null, symbol. 1 non-primitive: object (includes arrays, functions, dates, maps, sets — they are all objects).
Q7: What is hoisting?
Answer: JavaScript's behavior of moving declarations to the top of their scope during the creation phase. Function declarations are fully hoisted (callable before written). var variables are hoisted but initialized as undefined. let/const are hoisted but stay in the Temporal Dead Zone until declaration.
Q8: What is the event loop?
Answer: The mechanism enabling JavaScript's non-blocking concurrency. It monitors the call stack and task queues. When the call stack is empty, it moves callbacks from the microtask queue (Promises, higher priority) and task queue (setTimeout, lower priority) to the call stack for execution.
Q9: What is the DOM?
Answer: The Document Object Model — a tree structure representation of an HTML page that JavaScript can manipulate. Using DOM APIs, JavaScript can read and change any element's content, style, attributes, and structure. This is how websites become interactive.
Q10: Can JavaScript run outside the browser?
Answer: Yes! Node.js (2009) enabled server-side JavaScript. Deno (2018) and Bun (2022) are newer alternatives. JavaScript also runs in mobile apps (React Native), desktop apps (Electron), IoT devices, and even space equipment!
Q11: What is the difference between null and undefined?
Answer: undefined means a variable was declared but not assigned a value — JavaScript sets it automatically. null is an intentional empty value — you assign it deliberately to indicate "no value here." typeof undefined === "undefined" while typeof null === "object" (a known language bug that was kept for backward compatibility).
Q12: What makes JavaScript different from other languages?
Answer: (1) It's the only language that runs natively in browsers — irreplaceable for web frontend. (2) Prototype-based inheritance instead of class-based. (3) First-class functions enabling functional programming patterns. (4) Single-threaded with a powerful event loop for async. (5) One language for everything — frontend, backend, mobile, desktop.
Summary
JavaScript is the most versatile programming language today:
- Created in 1995 by Brendan Eich in just 10 days at Netscape
- Runs everywhere — browsers, servers, mobile, desktop, IoT
- Dynamic and flexible — dynamically typed, multi-paradigm
- Massive ecosystem — npm has 2.5 million+ packages
- Highest demand — most sought-after skill for developers globally
- Constantly evolving — yearly ECMAScript updates keep it modern
- One language for all — the only true full-stack language
Whether you want to build websites, mobile apps, server APIs, desktop software, or even ML models — JavaScript has the tools and frameworks for everything. There has never been a better time to learn it.
What is Next?
In the next lesson, we will explore the History of JavaScript — how it was created in 10 days, went through browser wars, nearly died, and rose to become the world's most popular programming language.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for What is JavaScript? Complete Beginner.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, introduction, what, what is javascript? complete beginner
Related JavaScript Master Course Topics