Question about blocks

Hello, I am a JavaScript beginner. So far, I’m learning about global and local scope. Here’s this code that I copied/pasted from a book:

{ const a = 3; a; }

In this block, why is there an undeclared ‘a’ variable at the end?

It’s not undeclared, you declared it in the immediately preceding statement.

The naked a; is a lazy way of outputting the value of a from the block;
image

4 Likes

Huh, I have to say I head to read that line twice to get its purpose… are you sure this book is aimed at beginners, using such gimmicks from the outset? oO

It’s the Novice to Ninja book from Sitepoint. So far, I’ve noticed errors in the HTML coding, and some things need to be explained better. The book needs improvement.

1 Like

Ah okay, well IMHO a decent learning resource is The Modern JavaScript Tutorial… case in point, here’s the chapter on ninja code hehe:

Another one I’d wholeheartedly recommend is the You Don’t Know JS series by Kyle Simpson; this one from the 2nd edition is on scope specifically.

Oh. Which page is that on?

In the paperback, it’s on pages 41-43.

1 Like

Ok, thanks for that.

The chapter is about scope and the author is demonstrating how scope works in JavaScript. For context, here’s the full snippet:

const a = 1;

{ const a = 3; a; }
<< 3

a;
<< 1

As others have pointed out, the variable is not undeclared, you are assigning it a value in the preceding statement. This is scoped to the block, which is why a has two different values at different places in the program.

Maybe the confusion is arising as normally you would log this value to the console, not just list the variable name:

const a = 1;

{ const a = 3; console.log(a); }
<< 3

console.log(a);
<< 1

This has been omitted in the book, as the author is assuming you are typing these examples in a console (see page 16).

Would including the console.log statement have made it clearer?

2 Likes

IMO, yes, to a novice, it would be best to explicitly use console.log, OR to explicitly explain what the naked a; is doing, especially as this is block-related. (Don’t have the book, so I can’t swear this isn’t done?)

2 Likes

I second what m_hutley said.

Ok. Thanks. I’ll make sure that gets passed on.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.