0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptの変数にvarをつけた場合とつけない場合の違い

Last updated at Posted at 2020-10-07

結論

varをつけた場合
→そのスコープ内でのみ生存するローカル変数を作成する。
 すでに外側に同一名の変数が存在しても干渉されない。

varをつけない場合
→スコープ外へ同一名の変数が存在するまで辿っていき、存在した場合はその変数を利用する。
 存在しなければグローバル変数を作成する。

検証

paizaで検証しました。

検証環境
https://paiza.io/projects/9LF5qxEJ0QdKsB-Z_8mhrg?language=javascript

ソースコード

x = 'global';
y = 'global';
z = 'global';

function outfunc(){
    var x = 'out'; // outfunc内のみ生存
    var y = 'out'; // outfunc内のみ生存
    z = 'out';     // globalのzを使用
    
    function infunc(){
        var x = 'in'; // infunc内のみ生存
        y = 'in';     // outfuncのyを使用(=outfunc内のみ生存)
        z = 'in';     // outfuncのz(=globalのz)を使用
        console.log('in           ', x, y, z); // in, in, in
    }
    
    console.log('out_before   ', x, y, z); // out, out, out
    infunc();
    console.log('out_after    ', x, y, z); // out, in, in
}

console.log('global_before', x, y, z); // global, global, global
outfunc();
console.log('global_after ', x, y, z); // global, global, in

出力結果

global_before global global global
out_before    out out out
in            in in in
out_after     out in in
global_after  global global in
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?