---
title: Javascript Hoisting
description: "Hoisting is JavaScript’s default behavior of moving declarations to the top. Өргөх нь JavaScript-ийн анхны мэдэгдэлийг дээд хэсэгт шилжүүлэх зан төлөв юм. --- ## JavaScript Declarations are Hoisted ## JavaScript-ийн тунхаглалыг өргөж байна In JavaScript, a variable can be declared…"
url: "https://apprentice.mn/docs/javascript-hoisting/"
updated: "2021-07-26"
category: Javascript
---

# Javascript Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top.

Өргөх нь JavaScript-ийн анхны мэдэгдэлийг дээд хэсэгт шилжүүлэх зан төлөв юм.

---

## JavaScript Declarations are Hoisted

## JavaScript-ийн тунхаглалыг өргөж байна

In JavaScript, a variable can be declared after it has been used.

JavaScript дээр хувьсагчийг ашигласны дараа зарлаж болно.

In other words; a variable can be used before it has been declared.

Өөрөөр хэлбэл; хувьсагчийг зарлахаас өмнө ашиглаж болно.

**Example 1** gives the same result as **Example 2**:

**Жишээ 1** нь **жишээ 2**-тэй ижил үр дүнг өгдөг:

### Example 1

### Жишээ 1

      `x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x`

### Example 2

### Жишээ 2

     `var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element`

To understand this, you have to understand the term “hoisting”.

Үүнийг ойлгохын тулд “өргөх” гэсэн нэр томъёог ойлгох хэрэгтэй.

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

Өргөх нь JavaScript-ийн бүх заруудыг одоогийн хамрах хүрээний дээд хэсэгт (одоогийн скрипт эсвэл одоогийн функцын дээд хэсэгт) шилжүүлэх анхны үйлдэл юм.

---

## The let and const Keywords

## Let and const Түлхүүр үгс

Variables defined with `let` and `const` are hoisted to the top of the block, but not *initialized*.

`let` ба `const`-ээр тодорхойлогдсон хувьсагчдыг блокийн дээд хэсэгт өргөх боловч эхлүүлээгүй болно.

Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

Утга: Блок код нь хувьсагчийн талаар мэддэг боловч үүнийг зарлахаас өмнө ашиглах боломжгүй юм.

Using a `let` variable before it is declared will result in a `ReferenceError`.

`let` хувьсагчийг зарлагдахаас өмнө ашиглах нь `ReferenceError`-ийг үүсгэдэг.

The variable is in a “temporal dead zone” from the start of the block until it is declared:

Хувьсагч нь блок эхэлснээс хойш тунхаглагдах хүртэл “түр зуурын үхсэн бүс” -д байна.

### Example Жишээ

This will result in a `ReferenceError`:

Үүний үр дүнд `ReferenceError`:

       `carName = "Volvo";
let carName;`

Using a `const` variable before it is declared, is a syntax errror, so the code will simply not run.

`const` хувьсагчийг зарлахаас өмнө ашиглах нь синтаксийн алдаа тул код нь ажиллахгүй болно.

### Example Жишээ

This code will not run.

Энэ код ажиллахгүй.

       `carName = "Volvo";
const carName;`

Read more about let and const in JS Let / Const.

Let and const-ийн талаар JS Let / Const-ээс уншина уу.

---

   

---

## JavaScript Initializations are Not Hoisted

## JavaScript-ийн эхлүүлэлт хийгддэггүй

JavaScript only hoists declarations, not initializations.

JavaScript нь зөвхөн тунхаглалыг өргөж, эхлүүлэх биш.

**Example 1** does **not** give the same result as **Example 2**:

**Жишээ 1**-т **Жишээ 2**-тэй ижил үр дүн өгөхгүй:

### Example 1

### Жишээ 1

      `var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y`

### Example 2

### Жишээ 2

     `var x = 5; // Initialize x

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

var y = 7; // Initialize y`

Does it make sense that y is undefined in the last example?

Сүүлийн жишээнд y нь тодорхойлогдоогүй гэсэн үг үү?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.

Учир нь эхлүүлэх (= 7) биш, зөвхөн тунхаглал (var y) дээш өргөгдсөн байдаг.

Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.

Өргөхөөс болж y-г ашиглахаас өмнө зарласан боловч эхлүүлэх ажил хийгдээгүй тул y-ийн утга тодорхойлогдоогүй байна.

Example 2 is the same as writing:

Жишээ 2 нь бичихтэй ижил байна:

### Example Жишээ

      `var x = 5; // Initialize x
var y;     // Declare y

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y;           // Display x and y

y = 7;    // Assign 7 to y`

## Declare Your Variables At the Top !

## Хувьсагчаа дээд талд нь зарла!

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

Өргөх нь JavaScript-ийн үл мэдэгдэх эсвэл үл тоомсорлосон зан үйл юм (олон хөгжүүлэгчдэд).

If a developer doesn’t understand hoisting, programs may contain bugs (errors).

Хэрэв хөгжүүлэгч өргөхийг ойлгохгүй байвал програмууд алдаа (алдаа) агуулж болно.

To avoid bugs, always declare all variables at the beginning of every scope.

Алдаанаас зайлсхийхийн тулд хамрах хүрээний эхэнд бүх хувьсагчдыг үргэлж зарлаж байгаарай.

Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript нь кодыг ингэж тайлбарладаг тул энэ нь үргэлж сайн дүрэм юм.

JavaScript in strict mode does not allow variables to be used if they are not declared.

Хатуу горим дахь JavaScript нь зарлагдаагүй бол хувьсагчийг ашиглахыг зөвшөөрдөггүй.

Study **“use strict”** in the next chapter.

Дараагийн бүлэгт **“хатуу ашиглах”** талаар судал.

          [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fjavascript-hoisting%2F&linkname=Javascript%20Hoisting)[https://www.addtoany.com/share](https://www.addtoany.com/share)
