Let and Const for Block Scope

Tiffany White,

Up until ES6, you couldn’t achieve true block scoping in JavaScript. With the var keyword, the scope in a code block could be accessed in the global scope, as variable declarations are hoisted to the top of scope and the assignments are kept where they are.

For instance, take this code:

<span class="&quot;c1&quot;">// some code</span>

<span class="&quot;kd&quot;">function</span> <span class="&quot;nx&quot;">bar</span><span class="&quot;p&quot;">()</span> <span class="&quot;p&quot;">{</span>
	<span class="&quot;c1&quot;">// ...</span>
<span class="&quot;p&quot;">}</span>

<span class="&quot;c1&quot;">// more code</span>

<span class="&quot;kd&quot;">var</span> <span class="&quot;nx&quot;">c</span> <span class="&quot;o&quot;">=</span> <span class="&quot;mi&quot;">3</span><span class="&quot;p&quot;">;</span>

}

You can make a const value immutable by adding object.freeze() method to it.

Up until ES6, you couldn’t achieve true block scoping in JavaScript. With the var keyword, the scope in a code block could be accessed in the global scope, as variable declarations are hoisted to the top of scope and the assignments are kept where they are.

For instance, take this code:

<span class="&quot;c1&quot;">// some code</span>

<span class="&quot;kd&quot;">function</span> <span class="&quot;nx&quot;">bar</span><span class="&quot;p&quot;">()</span> <span class="&quot;p&quot;">{</span>
	<span class="&quot;c1&quot;">// ...</span>
<span class="&quot;p&quot;">}</span>

<span class="&quot;c1&quot;">// more code</span>

<span class="&quot;kd&quot;">var</span> <span class="&quot;nx&quot;">c</span> <span class="&quot;o&quot;">=</span> <span class="&quot;mi&quot;">3</span><span class="&quot;p&quot;">;</span>

}

You can make a const value immutable by adding object.freeze() method to it.

© tiff.RSS