These are fundamentals every JavaScript developer must know:
- What is JavaScript?
- JS Engine & How it runs in the browser
- Code Editors & Setup
- Variables (
var,let,const) - Data Types (Primitive & Non-Primitive)
- Operators
- Arithmetic
- Comparison
- Logical
- Assignment
- Bitwise
- Ternary
- Type Conversion & Coercion
- Conditionals (
if,else,switch) - Loops
for,while,do...whilefor...in,for...of
- Functions
- Declaration & Expressions
- Parameters vs Arguments
- Return Values
- Arrays
- Declaration, Access, and Iteration
- Basic Methods (
push,pop,shift,unshift,indexOf) - Array Methods (
map,filter,reduce, etc.)
- Objects
- Key-Value Pairs
- Dot & Bracket Notation
- Advanced Object Techniques
- Debugging using
console
JavaScript is a high-level, interpreted, lightweight, and multi-paradigm programming language that is one of the core technologies of the web, alongside HTML and CSS.
It allows developers to build interactive, dynamic, and responsive user experiences in the browser, and also power server-side applications using environments like Node.js. ๐๐ฅ๏ธ๐ก
- Interpreted: Runs directly in the browser (or in Node.js) without the need for compilation.
- Dynamically typed: You donโt need to define variable types explicitly.
- Single-threaded: Uses one call stack, but handles async tasks via the event loop.
- Prototype-based: Inheritance is done using prototypes instead of classical classes (though
classsyntax exists now). - Multi-paradigm: Supports functional, procedural, and object-oriented programming styles.
- Created in 1995 by Brendan Eich in just 10 days at Netscape.
- Originally called Mocha, then LiveScript, and finally JavaScript (for marketing reasons, not related to Java).
- Standardized as ECMAScript (ES), with ES6 (2015) being the most influential modern update. ๐ ๐๐
- Client-side (Browser): DOM manipulation, form validation, UI interactivity.
- Server-side: Backend APIs with Node.js, Express.js, etc.
- Mobile Apps: Frameworks like React Native, Ionic.
- Desktop Apps: Electron-based apps like VSCode, Slack.
- Game Development: 2D/3D games using libraries like Phaser or Three.js.
- IoT & Robotics: With platforms like Johnny-Five.
- Itโs the only programming language that natively runs in browsers.
- Massive community, endless job opportunities, and powerful ecosystem.
- Acts as a gateway to learning frontend frameworks (React, Vue, Angular) and full-stack development.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Vishnu")); // Output: Hello, Vishnu!JavaScript doesnโt work on its own โ it needs a JavaScript engine to interpret and execute the code. Every modern browser comes with its own JS engine that runs your code behind the scenes.
Letโs break down how it works, from engine to execution. ๐ ๏ธ๐งฉ๐
A JavaScript Engine is a program that takes your JS code, parses it, optimizes it, and finally executes it line by line.
Modern JS engines do much more than just interpretation โ they compile, optimize, and recompile code to make it fast.
๐ Popular JS Engines:
- V8 โ Chrome, Edge, Node.js
- SpiderMonkey โ Firefox
- JavaScriptCore โ Safari
- Chakra โ (Old) Microsoft Edge
- Parser: Breaks down your code into a syntax tree (AST โ Abstract Syntax Tree).
- Interpreter: Quickly converts AST to bytecode and starts executing it.
- Compiler (JIT): Just-In-Time compiler that takes frequently used code and compiles it into optimized machine code for faster execution.
- Garbage Collector: Automatically frees memory that's no longer needed.
๐งช Example Flow:
Your Code โ Parser โ AST โ Bytecode โ Optimized Machine Code
JavaScript code runs inside a browserโs environment, where the JS engine is part of a bigger system including:
๐ฆ Web APIs
๐งต Call Stack
๐ค Callback Queue
โณ Event Loop
-
Load HTML โ CSS โ JS
- The browser loads and parses the HTML.
- If it hits a
<script>tag, it pauses rendering and sends JS to the engine.
-
Parsing & Compilation
- JS engine parses the code into tokens and builds an AST.
- Bytecode is generated and compiled by the JIT compiler if needed.
-
Execution via Call Stack
- Synchronous code runs immediately via the call stack.
- Asynchronous operations (setTimeout, fetch) are sent to Web APIs.
-
Asynchronous Handling
- After completing, async tasks move to the callback queue.
- The event loop checks if the call stack is empty, and then pushes callback tasks to be executed.
JavaScript Code
โ
JavaScript Engine (V8)
โ
Parse โ AST โ Bytecode โ Optimized Code
โ
Execution in Browser (Call Stack + Web APIs + Event Loop)
- JS Engine handles execution, but the browser provides the environment (DOM, timers, fetch).
- Modern engines are blazing fast thanks to JIT compilation and smart memory management.
- The event loop enables JavaScript to be asynchronous even though it's single-threaded.
While JavaScript can be written in any plain text editor, using a modern code editor improves your speed, efficiency, and debugging skills. ๐ก
- Visual Studio Code (VS Code) โ Most popular, rich extensions, built-in terminal, Git support.
- Sublime Text โ Lightweight and fast.
- WebStorm โ Full-featured but paid.
- Install VS Code
- Add Extensions:
- ESLint ๐งน
- Prettier ๐จ
- JavaScript Snippets โก
- Enable autosave and format-on-save for better consistency.
You can also try out JavaScript instantly in the browser using tools like:
Variables are containers that store data. In JavaScript, you can declare variables using var, let, or const. Choosing the right one affects the behavior, scope, and mutability of your code. ๐๐โ๏ธ
| Keyword | Scope | Reassignable | Redeclarable | Hoisted | Use Case |
|---|---|---|---|---|---|
var |
Function | โ | โ | โ (undefined) | Legacy code |
let |
Block | โ | โ | โ (TDZ*) | Preferred for mutable values |
const |
Block | โ | โ | โ (TDZ*) | Preferred for constants |
*TDZ = Temporal Dead Zone: Variable exists but can't be accessed before declaration ๐งโโ๏ธ
var name = "Alice";
let age = 25;
const country = "India";๐ข var is function-scoped, allows redeclaration, and hoists with undefined.
๐ก let is block-scoped, doesn't allow redeclaration in the same scope, and hoists with TDZ.
๐ด const is block-scoped and must be initialized. It doesnโt allow reassignment.
if (true) {
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // โ
10
console.log(b); // โ ReferenceError
console.log(c); // โ ReferenceError๐ var leaks out of the block โ not recommended for block-scoped code! ๐๐จ๐
Using const doesnโt make the value immutable โ only the binding.
const arr = [1, 2, 3];
arr.push(4); // โ
Works
arr = [5, 6]; // โ Error: assignment to constant variableSo, use const by default, and only switch to let if reassignment is needed. โ
๐๐ก๏ธ
- Prefer
constunless you know the variable will change. - Use
letwhen mutation is required. - Avoid
varin modern code unless working with legacy systems.
JavaScript is a dynamically typed language, meaning you donโt have to declare variable types โ the type is determined at runtime. ๐ฏ๐ก๐
It has two major categories of data types:
- Number โ
123,3.14,-42 - String โ
"Hello",'World', `Template` - Boolean โ
true,false - null โ Intentional absence of value
- undefined โ Declared but not assigned
- Symbol โ Unique and immutable identifier (ES6)
- BigInt โ For arbitrarily large integers (ES2020)
let name = "Alice";
let age = 30;
let isLoggedIn = true;
let id = Symbol("id");
let big = 1234567890123456789012345678901234567890n;๐ Primitives are compared by value and are immutable. That means once created, their value canโt be changed (though variables can point to a new one). ๐๐๐
- Object โ
{ name: "John" } - Array โ
[1, 2, 3] - Function โ
function() {}or arrow functions - Date, RegExp, etc.
let user = { name: "John", age: 25 };
let colors = ["red", "green", "blue"];๐ These are stored by reference and are mutable โ modifying them affects the original.
Use typeof:
typeof "hello" // "string"
typeof 123 // "number"
typeof null // "object" ๐ฑ (quirk!)
typeof undefined // "undefined"
typeof {} // "object"
typeof [] // "object"
typeof (() => {}) // "function"๐ Note: typeof null returns "object" โ this is a long-standing bug in JavaScript. ๐๐๐งฑ
JavaScript does implicit and explicit type conversion (type coercion).
"5" + 1 // "51" โ string concatenation
"5" - 1 // 4 โ string converted to number
Number("123") // 123
Boolean("") // false๐ This can lead to confusing bugs, so understanding coercion is vital. โ๏ธ๐จ๐ง
- JavaScript has 7 primitive types and multiple reference types.
- Always be cautious with comparisons and coercion.
- Use
typeof,Array.isArray(), and strict equality===for clarity.
๐ง Knowing your data types makes debugging and designing logic much easier! ๐ฏ๐๐
Operators are special symbols used to perform operations on operands (variables and values). They are the building blocks of logic in any JavaScript program. ๐งฑโ๏ธ๐
Used to perform mathematical operations.
+Addition-Subtraction*Multiplication/Division%Modulus (remainder)**Exponentiation (ES6)++Increment--Decrement
let x = 10, y = 3;
x + y // 13
x % y // 1
x ** y // 1000๐ Arithmetic operators work on numbers and sometimes strings (like with +). ๐ฒ๐๐งฎ
Used to compare two values. Returns a Boolean.
==Equal to (with coercion)===Strictly equal (no coercion)!=Not equal!==Strictly not equal>Greater than<Less than>=Greater than or equal<=Less than or equal
5 == "5" // true
5 === "5" // false
10 > 3 // trueโ
Prefer === and !== for accurate comparisons. ๐ซ๐ก๐
Used to combine logical expressions.
&&AND||OR!NOT
true && false // false
true || false // true
!true // false๐ก Logical operators are essential for control flow and conditionals. ๐๐งฒ๐
Used to assign values to variables.
=+=,-=,*=,/=,%=,**=
let a = 5;
a += 3; // a = a + 3 โ 8๐ These help write cleaner, more concise code. ๐งผ๐ก๐งพ
Used for binary operations on 32-bit integers.
&AND|OR^XOR~NOT<<Left shift>>Right shift>>>Zero-fill right shift
5 & 1 // 1
5 | 1 // 5
5 ^ 1 // 4A shorthand for if...else:
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor"; // "Adult"Clean and expressive for simple conditional assignments! โ๏ธ
- Know the differences between
==and=== - Use logical operators for conditions and flow
- Ternary is your best friend for quick decisions
- Understand bitwise, even if you rarely use it
๐ Mastering operators improves your coding fluency drastically! ๐ฏ๐ง ๐ช
JavaScript is a dynamically typed language, which means variables can hold any type of data, and the engine automatically converts types when necessary. This behavior is called type coercion, and you can also convert types manually using type conversion. ๐ง โ๏ธ๐งช
You explicitly convert data from one type to another using built-in functions.
- To String:
String(value)orvalue.toString() - To Number:
Number(value),parseInt(),parseFloat() - To Boolean:
Boolean(value)
String(123); // "123"
Number("456"); // 456
Boolean(0); // false๐ Always use explicit conversion when you want full control over the type. ๐๏ธ๐งผ๐
JavaScript automatically converts types behind the scenes in certain operations.
'5' + 1 // "51" (number 1 is coerced to string)
'5' - 1 // 4 (string '5' is coerced to number)
true + 1 // 2 (true is coerced to 1)
false + '2' // "false2"๐ Coercion can lead to unexpected bugs if not well understood. ๐๐๐
When converting to Boolean, JavaScript treats some values as falsy, and everything else as truthy.
Falsy Values:
false0""(empty string)nullundefinedNaN
Everything else is truthy, including:
'0''false'[]{}
Boolean("") // false
Boolean([]) // true
Boolean(0) // false
Boolean("0") // true๐ง This plays a huge role in conditionals (if, while, etc.). ๐ก๏ธ๐๐งญ
null == undefined // true
null === undefined // false
[] == false // true
[] === false // false
'5' == 5 // true
'5' === 5 // falseโ
Use strict equality (===) to avoid bugs due to coercion. ๐๐งฏ๐
- Explicit Conversion = You choose the type.
- Implicit Coercion = JavaScript chooses the type (sometimes weirdly).
- Know your truthy/falsy values.
- Avoid confusion: prefer
===over==.
๐ฏ Understanding this is crucial to becoming a confident JS developer! ๐ง ๐โ
Conditionals let your program make decisions based on certain conditions. You use them to control the flow of execution. ๐โ๏ธ๐ฃ๏ธ
The most basic and widely used control structure.
let age = 20;
if (age >= 18) {
console.log("You're an adult.");
} else if (age > 12) {
console.log("You're a teenager.");
} else {
console.log("You're a child.");
}๐ง You can have multiple else if blocks, but only one else. ๐งฑ๐งญโ๏ธ
Used for multiple possible values of a single expression. It's more elegant than long if-else chains when checking equality.
const fruit = "apple";
switch (fruit) {
case "apple":
console.log("It's red.");
break;
case "banana":
console.log("It's yellow.");
break;
default:
console.log("Unknown fruit.");
}๐ Don't forget to use break to avoid fall-through behavior. ๐ซโ๏ธโฌ
A shorthand if-else, useful for short conditional logic.
let age = 16;
let access = age >= 18 ? "Granted" : "Denied";
console.log(access); // "Denied"โ Use ternary for simple conditions only. Avoid nesting for readability. ๐ช๐๐
&&(AND): All conditions must be true||(OR): At least one must be true!(NOT): Inverts a condition
if (isLoggedIn && userRole === "admin") {
// do something
}
if (!isEmailVerified) {
// ask to verify
}๐ Combine logical operators with conditionals for powerful decision-making logic. ๐๐ฏ๐งฐ
- Use
===instead of==to avoid unexpected coercion. - Keep ternary usage minimal and readable.
- Don't over-nest conditionals โ extract logic into functions if needed.
๐ฏ In summary, conditionals are the brain of your logic in JavaScript. Mastering them helps you write dynamic, decision-based programs! ๐ง ๐๐
Loops allow you to repeat a block of code multiple times, either for a fixed number of times or until a condition is met. They're essential for working with arrays, objects, or performing repetitive tasks. ๐ง๐๐ฆ
Most commonly used loop when the number of iterations is known.
for (let i = 0; i < 5; i++) {
console.log("Number:", i);
}- Initialization:
let i = 0 - Condition:
i < 5 - Increment:
i++
๐ Best for fixed-length iteration, like looping over indices. ๐งพ๐ฏ๐
Runs as long as the condition is true.
let i = 0;
while (i < 5) {
console.log("While Loop:", i);
i++;
}Useful when the number of iterations isnโt known beforehand. ๐ต๏ธโโ๏ธ๐๐
Executes the loop at least once, even if the condition is false initially.
let i = 0;
do {
console.log("Do While:", i);
i++;
} while (i < 5);๐ Use only when you must run the block at least once. ๐๐๐ฌ
Used to loop over iterables (arrays, strings, etc.).
const fruits = ["apple", "banana", "mango"];
for (const fruit of fruits) {
console.log(fruit);
}โ๏ธ Cleaner and more readable when working with values. ๐๐งผ๐ฆ
Used to loop over enumerable properties of objects.
const user = { name: "Alice", age: 25 };
for (const key in user) {
console.log(key, user[key]);
}for...of or for instead. ๐๐๐
break: Exits the loop entirely.continue: Skips the current iteration and moves to the next.
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // 0, 1, 2
}โ๏ธ Use wisely to control loop flow effectively. ๐ง ๐ง๐น๏ธ
- Use
for...offor clean iteration over arrays and strings. - Avoid infinite loops: always ensure your condition changes.
- Prefer functional methods (
map,filter,reduce) for array processing when possible.
๐ฏ Loops are a backbone of repetitive logic โ mastering all types gives you the flexibility to tackle any logic scenario with elegance! ๐ ๏ธ๐๐
Functions are reusable blocks of code designed to perform a particular task. They help keep your code modular, readable, and maintainable. You can define a function once and use it multiple times. ๐ก๐๐
Function Declaration:
function greet(name) {
return `Hello, ${name}!`;
}- Hoisted (can be called before declaration)
- Has a name
Function Expression:
const greet = function(name) {
return `Hello, ${name}!`;
};- Not hoisted
- Often used for anonymous functions
๐ Use expressions for inline logic and declarations for reusable named logic. ๐ง ๐ฆ๐ง
A shorter syntax for writing functions. Useful for small, concise functions.
const add = (a, b) => a + b;- No
this,arguments, orsuperbinding - Cannot be used as constructors
- Great for callbacks and one-liners
this in objects. โ๐งญ๐
- Parameters are variables listed in the function definition.
- Arguments are actual values passed to the function.
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}โ Use default parameters to make functions flexible. ๐๐ง ๐ฏ
Rest Parameter: Collects multiple arguments into an array.
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}Spread Operator: Expands arrays into individual elements.
const nums = [1, 2, 3];
console.log(Math.max(...nums));๐ These are great for variadic functions and working with arrays/objects. ๐ ๏ธ๐๐ง
Functions can return a value using the return keyword.
function multiply(x, y) {
return x * y;
}If no return is provided, the function returns undefined by default.
A callback is a function passed as an argument to another function to be executed later.
function greet(name, callback) {
callback(`Hello, ${name}`);
}Essential for asynchronous operations (e.g., setTimeout, event handlers). โฑ๏ธ๐ฏ๐๏ธ
- Use meaningful function names.
- Keep functions focused on one task.
- Prefer arrow functions for short, non-method functions.
- Document input/output behavior for clarity.
๐งฉ Mastering functions sets the foundation for asynchronous programming, event-driven architecture, and clean, modular code! ๐งฑ๐ฏ๐งช
Arrays are ordered collections used to store multiple values in a single variable. They can hold elements of any data type, including other arrays or objects. Arrays are zero-indexed โ meaning the first element is at index 0. ๐ข๐ฆ๐ก
Declaration:
const fruits = ["apple", "banana", "mango"];Access:
console.log(fruits[1]); // "banana"Update:
fruits[0] = "grape";Iteration (Looping through arrays):
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}โ
You can also use for...of, forEach(), or map() for iteration. ๐๐๐
These methods let you manipulate the contents of an array easily:
push(item)โ Add to the endpop()โ Remove from the endshift()โ Remove from the startunshift(item)โ Add to the startindexOf(item)โ Get index of a specific element
const nums = [10, 20, 30];
nums.push(40); // [10, 20, 30, 40]
nums.pop(); // [10, 20, 30]
nums.shift(); // [20, 30]
nums.unshift(5); // [5, 20, 30]
nums.indexOf(20); // 1๐งช These methods are commonly used for stack, queue, and search operations. ๐๐ง ๐
๐ Arrays are fundamental in JavaScript. Theyโre everywhere โ from handling lists of data to manipulating DOM elements, responses from APIs, or storing form inputs! ๐๐ฅ๐งฑ
Next: Letโs look into Array Methods (map, filter, reduce, etc.) โ the real power tools of JavaScript! โ๏ธ๐๐งฉ
โ๏ธ Array Methods (map, filter, reduce, etc.) โ The Real Power Tools of JavaScript ๐ ๏ธ๐๐งฉ
Once you master the basics of arrays, it's time to unlock their full potential using high-order methods. These built-in methods make array manipulation clean, readable, and expressive. ๐ฅ๐ก๐ง
Creates a new array by applying a function to every element.
const nums = [1, 2, 3];
const squares = nums.map(n => n * n); // [1, 4, 9]Useful when you want to transform or format data.
Creates a new array with elements that pass a condition.
const scores = [45, 78, 88, 32];
const passed = scores.filter(score => score >= 50); // [78, 88]Use it to extract matching or valid items.
Reduces the array to a single value (number, string, object, etc.).
const prices = [10, 20, 30];
const total = prices.reduce((sum, val) => sum + val, 0); // 60Perfect for totals, averages, or even object construction.
Returns the first element that satisfies the condition.
const users = [{id: 1}, {id: 2}];
const user = users.find(u => u.id === 2); // {id: 2}Stops as soon as it finds a match โ faster than filter() in such use-cases.
some()checks if at least one element matchesevery()checks if all elements match
const nums = [1, 3, 5];
nums.some(n => n > 4); // true
nums.every(n => n > 0); // trueGreat for quick yes/no conditions on arrays.
Sorts the array in-place. Be cautious: it modifies the original array!
const points = [40, 100, 1, 5];
points.sort((a, b) => a - b); // [1, 5, 40, 100]Use a compare function for accurate sorting (especially for numbers).
flat()flattens an arrayflatMap()maps and flattens in one go
const arr = [1, [2, 3], [4, [5]]];
arr.flat(2); // [1, 2, 3, 4, 5]Ideal for dealing with nested structures or returned arrays from mapping.
Performs an action on each item, but does not return anything.
[1, 2, 3].forEach(n => console.log(n * 2));Useful for logging, side effects, or calling external functions.
๐ก These methods donโt mutate the original array (except sort()), making them perfect for pure functional programming and cleaner, safer code. ๐งผ๐๐ง
Objects are one of the core building blocks in JavaScript, used to store related data and functionality together.
They consist of key-value pairs, where the key (property name) is always a string (or symbol), and the value can be anything โ string, number, array, object, function, etc.
const user = {
name: "Alice",
age: 30,
isAdmin: true
};Each entry in the object is a property with a key (name, age, isAdmin) and a value ("Alice", 30, true).
Dot Notation (most common):
console.log(user.name); // "Alice"Bracket Notation (for dynamic or invalid identifiers):
console.log(user["age"]); // 30Use bracket notation when:
- The property name is stored in a variable:
const key = "isAdmin"; console.log(user[key]); // true
- The property name contains special characters or spaces:
const obj = { "first-name": "Bob" }; console.log(obj["first-name"]); // "Bob"
You can easily change or add new properties:
user.age = 31;
user.city = "New York";Remove a property using the delete operator:
delete user.isAdmin;Objects can contain other objects, enabling complex data structures:
const person = {
name: "John",
address: {
city: "Paris",
zip: "75001"
}
};
console.log(person.address.city); // "Paris"Use the in operator or hasOwnProperty():
"age" in user; // true
user.hasOwnProperty("age"); // trueHere you go! Here's the next section covering Advanced Object Techniques with clean structure and subtle emoji decoration:
JavaScript objects come packed with powerful features that make data handling more elegant and readable. These advanced techniques are must-haves in your JS toolkit.
Object destructuring allows you to extract multiple properties into variables in a single statement.
const user = { name: "Alice", age: 30 };
const { name, age } = user;
console.log(name); // "Alice"You can also rename variables during destructuring:
const { name: userName } = user;
console.log(userName); // "Alice"Works perfectly with nested objects too:
const person = {
name: "John",
address: {
city: "Paris",
zip: "75001"
}
};
const { address: { city } } = person;
console.log(city); // "Paris"Assign defaults for missing properties:
const { role = "guest" } = user;
console.log(role); // "guest"These built-in methods are perfect for looping over objects or converting them to arrays.
const user = { name: "Alice", age: 30 };
Object.keys(user); // ["name", "age"]
Object.values(user); // ["Alice", 30]
Object.entries(user); // [["name", "Alice"], ["age", 30]]Looping with Object.entries():
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}Spread operator creates shallow copies:
const updatedUser = { ...user, city: "Berlin" };Rest operator gathers the remaining properties:
const { name, ...rest } = user;
console.log(rest); // { age: 30 }Prevent modifications:
Object.freeze(user); // Can't change or add/remove properties
Object.seal(user); // Can change, but not add/remove propertiesSafely access deeply nested properties:
const city = user?.address?.city ?? "Unknown";Debugging is a core skill for any developer. Fortunately, JavaScript offers the console object, which is a handy toolbox to inspect, trace, and troubleshoot your code with ease. Letโs explore how to use it from simple logs to advanced tactics.
console.log(): Outputs general information.console.error(): Displays error messages (in red).console.warn(): Shows warnings (often in yellow).console.info(): Gives informational messages (not widely different fromlog()in most browsers).
console.log("Hello world!");
console.error("Something went wrong!");
console.warn("This is a warning!");
console.info("Fetching data...");You can log anything โ strings, numbers, objects, arrays, functions, etc.
const user = { name: "Alice", age: 30 };
console.log(user);
console.log("User age is:", user.age);Perfect for visualizing objects or arrays in a table format.
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
];
console.table(users);Helps you organize logs into collapsible groups.
console.group("User Info");
console.log("Name: Alice");
console.log("Age: 30");
console.groupEnd();Measure how long a block of code takes to execute.
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop"); // loop: 1.234msOnly logs if a condition fails โ great for inline checks.
const age = 15;
console.assert(age >= 18, "Age is below 18");Make your logs visually stand out.
console.log("%cHello styled log", "color: blue; font-weight: bold;");Use browser developer tools:
- Set breakpoints in Sources tab.
- Inspect variables in Scope panel.
- Watch expressions.
- Step through your code line by line.
Tip: Use
debugger;in your code to automatically trigger a breakpoint.
function checkAge(age) {
debugger;
return age >= 18;
}- Keep logs consistent. Use log levels (
log,warn,error) smartly. - Remove/disable excessive logging in production.
- Label your logs clearly when debugging complex apps.