Why does JavaScript execute code after return statement differently than PHP?

I’m really confused about how JavaScript handles code that comes after a return statement. In PHP, any code written after return just doesn’t run at all, which makes sense to me. But in JavaScript, I noticed some weird behavior that I can’t understand.

function test() {
    console.log('first', myVar)
    myVar = 25;
    console.log('second', myVar)
    return;
    console.log('third', myVar)
    function myVar() {}
    console.log('fourth', myVar)
}

When I run this code, the lines with ‘third’ and ‘fourth’ don’t execute, which is what I expected. But I’m wondering if there are special cases in JavaScript where code after return might still have some effect. Is this related to function hoisting? When would someone actually write code after a return statement in JavaScript and expect it to do something?

Function and var declarations get hoisted in JavaScript - they’re processed before any code runs. In your example, function myVar() {} gets moved to the top of the scope, so myVar exists when you log it. That’s different from PHP, which processes declarations and executes code line by line. Even though code after return won’t run, the declarations have already been processed. You’ll sometimes see developers put code after return for debugging or in transpiled code, but it’s bad practice since it creates unreachable code.

Yeah, that’s hoisting in action. JavaScript moves function declarations to the top during compilation, before any code runs. So even though function myVar() {} comes after the return, it’s already been processed.

PHP runs sequentially - JavaScript doesn’t. The JS engine makes two passes: first hoisting declarations, then executing code line by line.

Here’s the thing though - I’ve dealt with tons of legacy code where unreachable functions still mess with the program through hoisting. Manual cleanup is a nightmare, so I automate it.

I set up workflows that scan JS files, find hoisted declarations after returns, and automatically move them where they belong. They also flag dead code for removal and generate cleanup reports.

Saves me hours every week on inherited codebases. Way better than manual reviews and fixes.

Check out https://latenode.com for automating code cleanup like this.

totally! js can be quite confusin if you’re coming from php. just remember, hoisting plays a big role in how the code is executed. it’s common to see leftover code after a return in older projects or just for debugging purposes, but it’s better to avoid that nonsense.