{"resource":{"author":{"id":"h2so9H8jPMmgUKGghoNl","name":"Yomesh Gupta","username":"yomeshgupta"},"content":{"link":"","difficulty":2,"domain":2,"type":1,"isInternal":true,"body":"Temporal Dead Zone is an advanced and interesting topic in JavaScript. To understand what it is and how things work, we need to understand different ways of variable declaration in JavaScript.\r\n\r\n## Var, Let, and Const\r\n\r\nES6 brought a lot of new features to the language and one of them was the ability to define variables using different keywords which have subtle differences among them.\r\n[ECMA Reference](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations)\r\n\r\nWe can declare variables in three ways:\r\n\r\n```js\r\nvar name = \"Yomesh\";\r\nlet surname = \"Gupta\";\r\nconst profession = \"Software Engineer\";\r\n```\r\n\r\nLet us understand what are the differences between these three.\r\n\r\n## Scoping\r\n\r\nIn the most simple terms, **scoping** is the area in which a variable is accessible. Scoping of a variable is controlled by the location of its declaration. Let us consider an example.\r\n\r\n```js\r\nfunction init() {\r\n    var firstname = \"Yomesh\";\r\n    console.log(firstname); // Yomesh\r\n}\r\nconsole.log(firstname); // Error\r\n```\r\n\r\nIn the above code snippet, variable `firstname` is declared inside the function `init`, i.e. anywhere inside this function we can get or set the value of the variable. However, accessing the same variable outside the function would lead to:\r\n\r\n```\r\nReferenceError: firstname is not defined\r\n```\r\n\r\n## Types of Scoping\r\n\r\nWe have three types of scoping, namely, **Global**, **Function**, and **Block** scoping. Now you must be thinking what does this all exactly mean? Think no more, it is example time!\r\n\r\n### Global Scope\r\n\r\n```js\r\nvar firstname = \"Yomesh\";\r\n\r\nfunction sayName() {\r\n    console.log(firstname); // firstname is accessible here\r\n}\r\n\r\nfunction nestedSayName() {\r\n    function sayNameNow() {\r\n        console.log(firstname); // firstname is accessible here\r\n    }\r\n    sayNameNow();\r\n}\r\n\r\nsayName(); // console logs \"Yomesh\"\r\nnestedSayName(); // console logs \"Yomesh\"\r\n```\r\n\r\nIn the above code snippet, the variable `firstname` is declared outside the functions. Any variable which is declared outside of a function will fall into global scope and is accessible to all parts of the code.\r\n\r\n### Function Scope\r\n\r\n```js\r\nfunction sayName() {\r\n    var firstname = \"Yomesh\";\r\n    console.log(firstname); // firstname is accessible here\r\n    function sayNameNow() {\r\n        // firstname is accessible here and we can update it.\r\n        firstname = \"Ronaldo\";\r\n        console.log(firstname); // Ronaldo\r\n    }\r\n    sayNameNow();\r\n}\r\nsayName();\r\n```\r\n\r\nIn the above code snippet, variable `firstname` is declared inside the function `sayName`. It is scoped to that function i.e. it can be used inside the `sayName` function or any nested functions. All variables declared via `var` are function scoped.\r\n\r\n### Block Scope\r\n\r\n```js\r\nfunction sayName() {\r\n    var condition = true;\r\n    if (condition) {\r\n        let firstname = \"Cristiano\";\r\n        const surname = \"Ronaldo\";\r\n        console.log(firstname, surname); // Cristiano Ronaldo\r\n    }\r\n    console.log(firstname, surname); // ReferenceError\r\n}\r\n```\r\n\r\nIn the above code snippet, variables `firstname` and `surname` are declared inside the scope created by the `if` code block. The first `console.log` statement logs the value correctly as variables are accessible in that scope. However, the second `console.log` throws an error because variables simply don't exist there.\r\n\r\n## Declaration & Initialisation\r\n\r\nA variable declaration introduces a new identifier. JavaScript interpreter creates a new variable during the creation phase.\r\n\r\n```js\r\nvar name = \"Yomesh\"; // allowed\r\nvar name = \"Cristiano\"; // allowed\r\nlet surname = \"Gupta\"; // allowed\r\nlet surname = \"Ronaldo\"; // Error\r\nconst profession = \"Software Engineer\"; // allowed\r\nconst profession = \"Footballer\"; // Error\r\n```\r\n\r\nAny variable declared via `var` can be re-declared as many times as we want. However, `let` and `const` can be only declared once in their respective scope. Variables declared via `var` have the default value of `undefined`. Variables declared via `let` and `const` exist but without a value and cannot be accessed before they are assigned (more on this later).\r\n\r\n## Binding to the Global Object\r\n\r\n```js\r\nvar firstname = \"Yomesh\";\r\nlet surname = \"Gupta\";\r\nconst profession = \"Software Engineer\";\r\n\r\n// Yomesh Gupta Software Engineer\r\nconsole.log(firstname, surname, profession);\r\n\r\n// Yomesh undefined undefined\r\nconsole.log(window.firstname, window.surname, window.profession);\r\n```\r\n\r\nVariables declared via `var` keyword in the global scope are automatically attached to the global object i.e. `window` in the browsers. The same is not the case with `let` and `const`.\r\n\r\n## Understanding Temporal Dead Zone\r\n\r\nJavaScript engine runs through our code in two phases — the **Creation phase** and the **Execution phase**. In the first phase, the engine goes through the code and allocates memory for the variables.\r\n\r\n```js\r\nconsole.log(firstname); // undefined\r\nvar firstname = \"Yomesh\";\r\n```\r\n\r\nIn the same phase, the variables declared via `var` are assigned the value `undefined` and that is why in the above code snippet you will get the value of the variable `firstname` as `undefined`. This is also what we know as **Hoisting**.\r\n\r\n```js\r\nconsole.log(firstname); // ReferenceError\r\nlet firstname = \"Yomesh\";\r\n```\r\n\r\nIn the case of the variables declared via `let` and `const`, they are also allocated memory but they are not assigned the value `undefined` initially, i.e. variable declarations do hoist but they throw an error till initialized. Let us consider an example.\r\n\r\n```js\r\n/*\r\n  Since variables are hoisted\r\n  it would be equivalent to\r\n  \r\n  let firstname;\r\n  Beginning of the temporal dead zone\r\n*/\r\n\r\nconsole.log(firstname); // ReferenceError as accessed in the TDZ\r\n\r\nfunction init() {\r\n  ...\r\n}\r\n\r\nfunction processing() {\r\n  ...\r\n}\r\n\r\nvar surname = \"Gupta\";\r\nvar profession = \"Software Engineer\";\r\n\r\nlet firstname = \"Yomesh\"; // Ending of the temporal dead zone\r\nconsole.log(firstname); // Yomesh\r\n```\r\n\r\nAs you can see, there exists a region (temporal dead zone) for the variable `firstname` which begins from the place where the variable is hoisted (its scope is created) till the place where the variable is initialized. Temporal Dead Zone is a good way to indicate bugs in the code. Accessing variables before declaration is often a root cause of errors.\r\n\r\nIn the **Execution phase**, variables are assigned their actual values and it is perfectly fine to use them afterwards.\r\n\r\n```js\r\n// Accessing `name` here before execution phase assigns the value to the variable would throw a ReferenceError due to TDZ.\r\n// console.log(name);\r\nconst name = \"Yomesh\";\r\nconsole.log(name); // Yomesh | Perfectly fine to use here\r\n```\r\n\r\nTemporal Dead Zone is everywhere. We considered the examples related to variable declarations but it also exists in newer features like **Default Parameters**.\r\n\r\nWe hope this article helped you in some way and gave you more clarity. Let me know your views in the comments or by clicking [here](https://devtools.tech/questions/s/what-would-be-the-output-based-on-temporal-dead-zone---qid---aDXxcPUD7LZNdjBCJYo8).\r\n","languages":[],"editorConfig":{}},"stats":{"views":8664,"used":0,"likes":0},"description":"","published":true,"isActive":true,"tags":["node.js","javascript","temporal dead zone","js tdz","es6","scoping","js","advanced javascript","advanced frontend"],"slug":"understanding-temporal-dead-zone-in-javascript---rid---0KEfke08AOZuNXVxRXPW","isPremium":false,"categories":[],"requires":[],"_id":"5f1dedf2cbec5f7ffc0c2fb3","title":"Understanding Temporal Dead Zone in JavaScript","resourceId":"0KEfke08AOZuNXVxRXPW","createdAt":1595796978578,"modifiedAt":1762885064292},"currentUser":null,"isOwner":false,"recommendations":{"questions":[{"_id":"68d3ef6ddb42322dc8303729","content":{"languages":["react","html"],"difficulty":2},"tags":["javascript","ui","ux","devtools tech","makemytrip","coding","frontend coding challenge"],"slug":"build-a-typing-speed-test-component---qid---dWAbFdPLCiHkx6WsJ1fu","title":"Build a Typing Speed Test Component","questionId":"dWAbFdPLCiHkx6WsJ1fu"},{"_id":"6215f62a1641361c7c65df22","content":{"difficulty":1,"languages":"css"},"tags":["css","frontend","design","frontend interview questions","box model","styling","sass","scss","code","interview","frontend fundamentals",""],"slug":"explain-box-model-in-css-or-frontend-interview-questions---qid---634yBSX4cAUvzvGWvzeo","title":"Explain Box Model in CSS | Frontend Interview Questions","questionId":"634yBSX4cAUvzvGWvzeo"},{"_id":"620b54fc1641361c7c65c08a","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["javascript","array","promises","async programming","code","devtools"],"slug":"how-would-you-implement-promise-race-from-scratch-or-promise-polyfills-or-javascript-interview-questions---qid---orv14AZtpF5qwu2QYjYR","title":"How would you implement Promise.race from scratch? | Promise Polyfills | JavaScript Interview Questions","questionId":"orv14AZtpF5qwu2QYjYR"},{"_id":"6319da3977f9961d5b7d17e0","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["","javascript","localStorage","js","frontend interview question","devtools tech","frontend masters","problem solving","document","window"," window localstorage","advanced js","tooling"],"slug":"design-and-implement-localstorage-api-or-frontend-problem-solving-or-javascript-interview-question---qid---UAh0XKLuf8zdwv0JcA43","title":"Design and Implement localStorage API | Frontend Problem Solving | JavaScript Interview Question","questionId":"UAh0XKLuf8zdwv0JcA43"},{"_id":"62dfadbc77f9961d5b7bf558","content":{"languages":["react","html"],"difficulty":1},"tags":["javascript","ui based","machine coding","coding challenge","frontend practice","css","styling","devtools tech","dictionary","frontend masters","frontend challenge","devkode","codedamn","egghead"],"slug":"build-a-dictionary-app-or-react-js-or-frontend-coding-challenge---qid---rnrC8DZ3wOanc86iJ5hK","title":"Build A Dictionary App | React.js | Frontend Coding Challenge","questionId":"rnrC8DZ3wOanc86iJ5hK"}],"resources":[{"_id":"662a9bac4079503047f8376b","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","frontend","code","react","list performance","ui","ux","devtools tech","microsoft"],"slug":"how-to-improve-list-rendering-performance-in-a-react-app-or-list-virtualization-or-microsoft-frontend-interview-question---rid---AgCMhGtE8GZmJa5cKY71","title":"How to improve list rendering performance in a React app? | List Virtualization | Microsoft Frontend Interview Question","resourceId":"AgCMhGtE8GZmJa5cKY71"},{"_id":"652d64e4d5ab2876a4ca213c","content":{"difficulty":4,"domain":2,"type":1,"isInternal":false,"languages":["undefined"]},"tags":["frontend","coding","interviews","experience","devtools tech","blog","medium"],"slug":"zeta-interview-experience-sde-1-frontend---rid---2RwNAPVBDsL25iOQe1l0","title":"Zeta Interview Experience SDE-1 FrontEnd","resourceId":"2RwNAPVBDsL25iOQe1l0"},{"_id":"636b69d7c958c137b34c4eaf","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true},"tags":["javascript","frontend code","faded background","html","css","js","ui","ux","styling","sass","linear gradient","css opacity"],"slug":"how-to-create-faded-background-using-html-css-and-javascript---rid---biuSrrx7QmDLJ8iCN0Uh","title":"How to Create Faded Background using HTML, CSS, and JavaScript","resourceId":"biuSrrx7QmDLJ8iCN0Uh"},{"_id":"5f202d38cbec5f7ffc0c2fbc","content":{"difficulty":1,"domain":2,"type":2},"tags":["Slice"," Splice"," Javascript ","Interview Questions "],"slug":"slice-and-splice-oror-javascript-interview-questions-oror-puneet-ahuja---rid---vJoGsYEHYTzhQDdvQJ4O","title":"Slice and Splice || Javascript Interview Questions || Puneet Ahuja","resourceId":"vJoGsYEHYTzhQDdvQJ4O"},{"_id":"69970bdb58fa65a0ece72546","content":{"difficulty":2,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend","ui","ux"],"slug":"what-is-the-significance-of-the-react-fiber-architecture---rid---2tPtREBBpVUslyJcRGrw","title":"What is the significance of the React Fiber architecture?","resourceId":"2tPtREBBpVUslyJcRGrw"}]}}