Back to feed
Renewal·서른의 생활코딩

Sample source 3) JavaScript basic document structure ( user-defined function 2 _ local variable )

NS
normalstory
cover image

Let's press the button
This time, the number doesn't increase.


Each time you press the onclick button, 
in the alert(i) popup window shown to the user, the variable i, which represents the number,

is a local variable that runs only inside the function called "one_plus()".
 
Why??? The reason is simple. !!!
Because it was written inside the function, (if you put a sink in the living room, you can also use it in the living room.) 

i+=1; runs only within the function.

So then?
Is there no way to write it inside the function and still use it outside?
To answer first,

"Yes, there is."
 

It's simple. When declaring the variable, 
in front of it, 
just drop the "var" and declare it.

Now let's stop thinking and talking, and just try it.



<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">




<head>


<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />




<title> 사용자 정의 함수3.지역변수 </title>




<script type="text/javascript">


//<!CDATA[






function one_plus(){


var i=0; //지역변수


i+=1;


alert(i);


}


// onclick -> 클릭할 때 마다 1씩증가 X
-> 불러 올 때마다 초기 값인 상태인 0을 불러 옮으로 증가하지 않는다.


//]]]]]]>


</script>




</head>






<body>




<form method="post" action""]]>


<p>


<input type="button" value="one plus one" onclick="one_plus()" />


</p>


</form>




</body>




</html>

This English version was translated by Claude.

친절한 찰쓰씨
Written by
친절한 찰쓰씨

Pleasant Charles — UI/UX researcher at AIT. Keeping notes on design, planning, and slow days here since 2010.

More on the author's page

Keep reading

Renewal

Why You Should Use .html Instead of .md Seeing Is Believing

Jul 25, 2026·1 min
Renewal

The Most Important Thing About AX

Jul 17, 2026·2 min
Renewal

디지털 기술과 혁신에 대한 논고(지탱하는 힘)

Jul 17, 2026·5 min