Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `console.log()` considered a side effect in JavaScript?

I was learning about side effects in JavaScript, and I came across the idea that console.log() is considered a side effect. However, I'm not entirely sure why.

For example, in the following function:

function greet(name) {
    console.log("Hello, " + name); 
    return "Hello, " + name;
}

Since console.log() does not modify any variables or return values, why is it classified as a side effect?

I tried using console.log() inside a function and expected it to just display output without affecting the program's logic. However, I read that logging is considered a side effect, and I’m trying to understand why.

like image 840
Rao Imtinan Avatar asked Oct 19 '25 23:10

Rao Imtinan


1 Answers

A subroutine is said to have a side effect if it has any observable effect other than its primary effect of reading the value of its arguments and returning a value to the invoker of the subroutine. [Wikipedia.org]

The subroutine console.log() has a side effect because when invoked, it reads the value of its arguments, returns undefined and has an observable effect of changing the state of the browser's console.

Any use of this subroutine will lead to side effects.

like image 143
Chukwujiobi Canon Avatar answered Oct 22 '25 13:10

Chukwujiobi Canon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!