Assignment: =

Assignment in programming is when you take a value and you store it in a property (e.g. document.body.style.color, someimg.src, or window.location) or a variable. When you change something this is almost always done with assignment, if only indirectly (such as with a function call). This is done with the '=' operator. Variable also touches on the differences between assignment and mathematical equals. What is important to note is that when the assignment operator = is processed, then whatever value is on the right will be stored in the place on the left. The directionality is important: "x=2;" is fine but "2=x" will cause an error because there is no location labelled by '2' that can store the value of x. Also, note than in

Examples:

Changing Properties (someObject.style.CSSPropertyName and someImage.src)

The Code
<button onclick="document.body.style.backgroundColor='green';">Background Color to green</button>
<input type="button" onclick="document.body.style.backgroundColor='gray';" value="Background Color to gray" />
<br /><br />

<img alt="divide by zero" src="images/divide_by_zero_question.jpg"
onclick="this.src='images/divide_by_zero.jpg' " />
<!--From http://3.bp.blogspot.com/_ZTt7ivF2m-0/TCfimRhIymI/AAAAAAAAJoo/mNrRbc79xGQ/s1600/divide-by-zero-blog-safe.jpg
-->
Click button to execute:


divide by zero


Basic Usage with Strings

The Code
<script type="text/javascript">
function alertNames(){
var name1='Bob';
var name2='Jaime';
alert('name1 :' + name1);
alert('name2 :' + name2);
name2=name1;
alert('after "name2=name1;" name2 :' + name2);
}
</script>
<button onclick="alertNames()">Alert Names</button>
Click button to execute:



Usage with Number Variables

The Code
<script type="text/javascript">
function alertNumbers(){
var num1=10;
var num2=20;
alert('num1 :' + num1);
alert('num2 :' + num2);
ar num3=num1+num2;
alert('num3 after "var num3=num1+num2;" :' + num3);
num1=num2;
alert('num1 after "num1=num2;"' + num1);
}
</script>
<button onclick="alertNumbers()">Alert Numbers</button>
Click button to execute:





Back to Knowledge Dump