codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › JS scope

JS scope

Where variables are visible.

let and const live in their block. var lives in the whole function. Variables outside functions are global.

Commands in this lesson

let

Definition: Declares a variable that can change. It lives inside its block.

Syntax:

let name = value;

Example:

let n = 1;
n = n + 1;
console.log(n);

const

Definition: Declares a variable that cannot be reassigned.

Syntax:

const name = value;

Example:

const pi = 3.14;
console.log(pi);

Example code

<pre id='o'></pre>
<script>
let g='global';
function f(){var a='function';if(true){let b='block';var c='var leaks';}return a+' '+c+' '+typeof b;}
o.textContent=g+', '+f();
</script>

Run this code in the online editor

← JS numbersJS dates →