twibiral / obsidian-execute-code

Obsidian Plugin to execute code in a note.
MIT License
1.06k stars 67 forks source link

Javascript: Let is not block scoped #278

Closed bgk0018 closed 1 year ago

bgk0018 commented 1 year ago

This plugin is amazing, thank you!

I'm sure I'm just doing something wrong, but I was doing a course on TypeScript and was putting notes in on the difference between var and let. I understand that let is block scoped as opposed to var.

However, my javascript example showing that let should fail some code due to that block scoping did not function as expected.

let age = 25;

if(age > 20){
  let isOld = true;
}

console.log(isOld); //This breaks! isOld is block scoped!

function funcScope(){
    console.log(isOld); //This breaks! isOld is block scoped!
}

funcScope();

This actually returned true, true.

image

Is it possible that the way the plugin is constructed could've led to this? Any feedback would be awesome.

Thanks!

bgk0018 commented 1 year ago

AHA, I found it! I was doing something silly. Literally got bit by the stupid hoisting we created let to avoid using var for!!

I have a code block just ahead of this that uses the same code except with var. This means the isOld variable is hoisted global and accessible by the next code block down -.-

Amazing.

You can see here that now that I've changed the name of the variable, it's working as expected.

image

Closing this issue

twibiral commented 1 year ago

You can go to the settings and disable the notebook mode for javascript if you don't want to keep variables from other code blocks. Without notebook mode, each cell is executed independently of the others :)