DEV Community

Dhairya Shah
Dhairya Shah

Posted on

JavaScript Question: Is this correct syntax?

  console.log(name);
  console.log(age);
  var name = 'John Doe';
  let age = 21;
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
umashankar_s profile image
Umashankar S • Edited

No. it is not a correct syntax for let.

1. let me take the example of only var:-

console.log(name);
var name = "John Doe";

In this case, JS engine will take the var declaration initially and it will assigned with "undefined"(Hoisting). so at the time of console.log(name) //undefined.

But this is a bad practice to write this kind of syntax, and this has been overcome in let and const.

2. Let example:-

console.log(age);
let age=21;

In this case also, JS engine will take the let and it will hoist. but it will not assigned with any undefined or null value and that let variable cannot used anywhere untill and unless the execution comes to the point.(Temporal dead Zone)
let age=21;

conclusion:-
console.log(age); -> reference error
let age=21;

Collapse
 
rconr007 profile image
rconr007 • Edited

In Javascript variables are hoisted (float to the top) as well as functions.
Meaning you can declare them anywhere but their values won't be assigned until you hit the line where you are assigning them. This also means that you can call the variables before they are declared with (var, let, const).
You won't get an error in this instance but he values of the variables are unassigned, but they have been declared which will have an undefined value.

Collapse
 
ashokraju105605 profile image
ashokraju105605

will print undefined, as variable hoisting happens, but assignment not done at printing time.

Collapse
 
zippcodder profile image
Deon Rich

nope.

Collapse
 
_moehab profile image
Mahmoud Ehab

Yep!
It's syntactically correct, but not semantically.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Yes, there's nothing wrong with the syntax

Collapse
 
suhakim profile image
sadiul hakim

name= undefiend
age=undefiend