Yes, console.log() is a side effect. Any operation that affects the external environment or depends on it is considered a side effect. console.log() outputs information to the console, changing the state of the external environment, so it’s a side effect.
// Side effect — output to console
function greet(name) {
console.log('Hello, ' + name); // side effect
return name;
}
greet('John'); // Outputs: 'Hello, John'console.log() is like a messenger who runs from house to house delivering messages. It affects the “external world” (console), so it’s a side effect! 📢
A side effect is when a function does something other than returning a value. That is, it affects the external environment or depends on it:
function add(a, b) {
console.log('Adding numbers'); // side effect
return a + b;
}
const result = add(2, 3); // Outputs: 'Adding numbers'// Changing variable outside function
let counter = 0;
function increment() {
counter++; // side effect
return counter;
}
// Changing DOM
function updatePage(title) {
document.title = title; // side effect
return title;
}
// HTTP requests
async function fetchData() {
const response = await fetch('/api/data'); // side effect
return response.json();
}// Always returns the same result for the same arguments
function pureAdd(a, b) {
return a + b; // No side effects
}
pureAdd(2, 3); // Always 5// May return different results
let x = 1;
function impureAdd(a) {
console.log('Calculating'); // side effect
return a + x; // depends on external variable
}
impureAdd(2); // 3
x = 5;
impureAdd(2); // 7 (different result!)function processUser(user) {
console.log('Processing user:', user.name); // For debugging
// ... processing logic
return user;
}// Saving data
function saveToLocalStorage(key, value) {
localStorage.setItem(key, JSON.stringify(value)); // side effect
return true;
}
// Sending data to server
async function sendToServer(data) {
const response = await fetch('/api/save', {
method: 'POST',
body: JSON.stringify(data)
}); // side effect
return response.ok;
}// ❌ Error — thinking this is a pure function
function logAndReturn(value) {
console.log(value); // side effect!
return value;
}
// ✅ Correctly — understand that this is a function with side effect// ❌ Hard to test
function bad(name) {
console.log('Hello, ' + name);
return name.length;
}
// ✅ Better — separate logic and side effects
function good(name) {
const length = name.length; // pure logic
console.log('Hello, ' + name); // side effect
return length;
}Understanding side effects helps write more predictable code and better understand how functions work! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪