Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Logically let should have block scope, how this snippet is returning number?

function fn() {
  let ax = bx = 110;
  ax++;
  return ax;
}
fn()
console.log(typeof bx)
console.log(typeof ax)

its answer is // undefined number .
I am very confused, how it is possible. as ax , bx is in scope

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When we write let ax = bx = 110;, we are not doing

let ax = 110;
let bx = 110;

In fact there is no keyword in front of bx, and hence it is considered to be from the outer scope. In this case, bx becomes a part of global scope. And hence it is available outside.

PS:

One hacky way to do it in one line:

function fn() {
  let [ax,bx] = [110,110];
  ax++;
  return ax;
}
fn()
console.log(typeof bx)
console.log(typeof ax)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading