[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/var [Back]  [Original]

var - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

var

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 7.

var , .

In this article

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2

js
    var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
varnameN

. .

valueN

. .

. var , , .

( ) . :

  1. (execution context) . .

    js
    function x() {
      y = 1; // strict  ReferenceError .
      var z = 2;
    }
    
    x();
    
    console.log(y); //  "1" .
    console.log(z); // ReferenceError: z is not defined outside x .
    
  2. . .

    js
    console.log(a); // ReferenceError .
    console.log("still going..."); //   .
    
    js
    var a;
    console.log(a); //    "undefined"  "" .
    console.log("still going..."); //  "still going..." .
    
  3. (execution context) . . (e.g .)

    js
    var a = 1;
    b = 2;
    
    delete this.a; // strict  TypeError .    .
    delete this.b;
    
    console.log(a, b); // ReferenceError .
    // 'b'  ,   .
    

, . , . ECMAScript 5 strict mode, .

var (hoisting)

( ) , . . "(hoisting)" .

js
bla = 2;
var bla;
// ...

//       :

var bla;
bla = 2;

, ( ) . () , .

js
var a = 0,
  b = 0;

js
var a = "A";
var b = a;

//  :

var a,
  b = (a = "A");

:

js
var x = y,
  y = "A";
console.log(x + y); // undefinedA

, x y , . "x = y" , y ReferenceError 'undefined' . , x undefined . , y 'A' . , , x === undefined && y === 'A', .

js
var x = 0;

function f() {
  var x = (y = 1); // x  . y !
}
f();

console.log(x, y); // 0, 1
// x  
// y leaked outside of the function, though!

.

js
var x = 0; // x  , 0 .

console.log(typeof z); // undefined, z   .

function a() {
  // a   ,
  var y = 2; // y  a  , 2 .

  console.log(x, y); // 0 2

  function b() {
    // b  ,
    x = 3; //   x 3 ,   var   .
    y = 4; //   y 4 ,   var   .
    z = 5; //   z   5  .
  } // (strict mode ReferenceError .)

  b(); //  b   z .
  console.log(x, y, z); // 3 4 5
}

a(); //  a  b .
console.log(x, z); // 3 5
console.log(typeof y); // undefined y function a  .

Specification
ECMAScript 2027 LanguageSpecification
# sec-variable-statement


Web Proxy Viewer  |  New URL  |  Original Page