JavaScript assignment
statements and programs
Statements
A statement is a section Examples:
of JavaScript that can be
evaluated by a Web Last_name = “Dunn”;
browser. x = 10 ;
A script is simply a y = x*x ;
collection of statements.
Statements
End with semi-colon.
Cannot occupy multiple lines.
Assignment statement
var = value;
The “value” on the right can be any legal
expression.
Function call
[Link] ("foo");
Variables
A variable is a name
associated with a piece of
data. Example:
var x = 10;
Variables allow you to
store and manipulate var y = 17;
data in your programs.
var color = “red”;
In JavaScript variables are
created using the var name = “Katie”;
keyword var
Assignment statements
target = new-value;
CHANGE the value of the target variable TO
the new-value.
new-value can be a constant, a variable, or
an expression:
x = 3;
x = y;
x = x+ 5;
JavaScript Constants
Declared with the const keyword
const RETIREMENT_AGE = 65;
const SCHOOL = “NKM”;
Should be initialized when declared.
Can’t be changed.
Assignment vs. Algebra
The assignment statement is not an algebraic
equation!
<variable> = <expression>; means:
"store the value of <expression> into <variable>"
Examples:
GPA = 3.25;
x = 2 * (1 + 3);
Some people read x = 3 * 4; as "x gets the value of
3 * 4"
ERROR: 3 = 1 + 2; is an illegal statement, because 3
is not a variable.
Assigning Values To Variables
We often know an initial value for the
variables we declare.
A variable can be declared and assigned an
initial value in the same statement.
Declaration/initialization statement syntax:
var <identifier> = <expression>;
Example:
var taxRate = 0.088;
Assigning Variables
A variable can be assigned a value more
than once.
Example:
var x = 1.5;
x = 3;
x = 4 + 7; // x now has a value of 11
Assignment Conundrum
What happens when a variable is used on
both sides of an assignment statement?
var x = 3;
x = x + 2; // what happens?
Answer: x now has a value of 5.
Using Variables
Once a variable has been assigned a value, it
can be used in expressions.
var x = 2 * 4;
var y = x * 5 - 1;
The above statement is equivalent to:
var y = 8 * 5 - 1;
Random Selection
Choose between options randomly
var n = [Link]();
[Math is a collection of functions].
If you use it twice, you get two different
values. Need to save it to reuse!
Example: Add Two Numbers
<html>
…
<p> … </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>
…
</html>
slide 13
Data types
What is the difference between the following
statements:
val1 = "53";
val2 = 53;
These values are different to JavaScript:
- stored differently;
- manipulated differently;
- same operation may mean something
different
+ on strings in concatenation
+ on numbers is addition
Assignment statement (example)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Assignment Statements</h2>
<p>a = 13, b = 12, find the sum c = a + b, and show the output c:</p>
<p id="demo"></p>
<script> var a = 13;
var b = 12;
var c = a + b;
[Link]("demo").innerHTML = c;
</script>
</body>
</html>
JavaScript Assignment Statements
a = 13, b = 12, find the sum c = a + b, and show the output c: 25
JavaScript assignment operators
• <script>
• var a;
• a = 25;
• [Link](a + "<br>"); // Prints:25
• a = 40;
• a += 50;
• [Link](a + "<br>"); // Prints: 90
• a = 70;
• a -= 60;
• [Link](a + "<br>"); // Prints: 10
• a = 12;
• a *= 6;
• [Link](a + "<br>"); // Prints: 72
• a = 80;
• a /= 20;
• [Link](a + "<br>"); // Prints: 4
• a = 80;
• a %= 15;
• [Link](x); // Prints: 5
• </script>
JavaScript assignment operator
The assignment operator (=) is used to assign value to a
variable, for example: var varName = value
<script>
var name = “Kamil Boz";
var age = 28;
var isMarried = true;
[Link](name + "<br>");
[Link](age + "<br>");
[Link](isMarried);
</script>
Kamil Boz
28
true
Using String Objects
• Strings store groups of text characters and are named
similarly to other variables
test= “This is a test”;
• JavaScript stores strings as String objects. There are 2
ways to create a new String object.
1. test = “This is a test”;
2. test = new String(“This is a test”);
Note: The second statement uses the new keyword,
which is used to create new objects. This tells the
browser to create a new String object containing the text
This is a test and assigns it to the variable test
Assigning a Value
• You can also assign a value after the string has
already been created. For example,
test = “This is only a test. ”;
• You can also use the concatenation operator (+)
to combine the values of two strings
Example
• <html><head><title>String Test</title>
• </head>
• <body>
• <h1>String Test</h1>
• <script LANGUAGE="JavaScript">;
• test1 = "This is a test.";
• test2 = “So What!!";
• both = test1 + test2;
• alert(both);
• </script>
• </body>
• </html>
Printing on one line
<HTML>
<HEAD>
<TITLE>Program in JavaScript</TITLE>
<SCRIPT>
[Link]( “<FONT COLOR=‘red’><H1>Welcome to “
[Link](“JavaScript Programming!</H1></FONT>”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
Displaying multiple lines in
a dialog box
<HTML>
<HEAD>
<TITLE>Printing Multiple Lines</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
[Link](“Welcome to\nJavaScript\nProgramming!”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
Substr method
var str = "The white rabbit jumps over the chair";
[Link]([Link](4, 16)); // Prints:
white rabbit
[Link]([Link](10, 0)); // Prints: The
white
[Link]([Link](-50,-40)); // Prints
nothing
[Link]([Link](4)); // Prints: white
rabbit jumps over the chair
Replace method for replacing the
substring’s content
• var str = "The white rabbit jumps over the chair";
• var result1 = [Link](“white“, “black“);
• alert resul1t; // Prints: The black rabbit jumps
over the chair;
• var result2 = [Link](“rabbit“, “dog“);
• alert result2; // Prints: The white dog jumps over
the chair;
Increment and Decrement Operators
• You can use any expression to the right of the equal sign,
including other variables.
E.g. Lines = lines + 1;
• JavaScript includes two types of shorthand increment
and decrement variables
- The first uses the += operator:
e.g lines += 1;
- similarly, you can subtract a number from a variable
using the -= operator:
e.g lines -=1;
• JavaScript also includes the increment ++ and decrement
-- operators
e.g lines++;
lines--;
Increment and Decrement Operators
Both the increment x = 10; x = 10;
(++) and decrement y = ++ x; z = x ++;
(- -) operator come in
two forms: prefix and y = 11
postfix. z = 10
These two forms yield x = 11 in both cases
different results.
Increment and Decrement Operators
Assignment Initial Sample Explanation ASSIGNS
Operator variable expression
Value
+= c=3 c += 7 c=c+7 10 to c
-= d=5 d -= 4 d=d–4 1 to d
*= e=4 e *= 5 e=e*5 20 to e
/= f=6 f /= 3 f=f/3 2 to f
%= g = 12 g %= 0 g=g%9 3 to g
Increment and Decrement Operators
Operator Called Example Explanation
Prefix ++a Increment a by 1, then use the new
++ increment value of a in the expression in which a
resides.
Postfix a++ Use the new value of a in the
++ increment expression in which a resides, then
increment a by 1.
Prefix --a Decrement a by 1, then use the new
-- decrement value of a in the expression in which a
resides.
Postfix a-- Use the new value of a in the
-- decrement expression in which a resides, then
decrement a by 1.
JavaScript Increment and Decrement
• <script>
Operators
• var a;
• a = 25;
• [Link](++a); // Prints: 26
• [Link]("<p>" + a + "</p>"); // Prints: 26
• a = 25;
• [Link](a++); // Prints: 25
• [Link]("<p>" + a + "</p>"); // Prints: 26
• a = 25;
• [Link](--a); // Prints: 24
• [Link]("<p>" + a + "</p>"); // Prints: 24
• a = 25;
• [Link](a--); // Prints: 25
• [Link]("<p>" + a + "</p>"); // Prints: 24
• </script>
The “for” loop
• The Counting Loop OR Counter-Controlled
Loop
• Allows repeatable code until in an iterative
loop for a finite amount of times.
• Useful when the program runs for a pre-
determined length of time.
• Must have a way of terminating the structure
from within the loop’s header (test against an
maximum or minimum value).
Parts of a For loop
• The conditions for the test
–Starting point for counter
–A maximum/minimum value
–A way to increment/decrement the
counter
• The action the loop should perform while
the counter hasn’t met the max/min.
For Loop – Example
Maximum Value
for(var i=0; i<100; i++)
{ Starting Point How to Increment
keep driving; what to do when i<100
}
Example: For loop
<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
[Link]("1");
[Link]("2");
for (i=1; i<=5; i++)
[Link]("3");
[Link](i);
[Link]("4");
[Link]("5");
</SCRIPT>
Example: For loop
// Print the numbers 1 i=1 initializes the counter
through 10
i<=10 is the target
for (i=1; i<= 10; i++) value
[Link](i);
i++ updates the
counter at the end
of the loop
Example: For loop
General Format:
for ( initialization; loopContinuationTest; increment )
statement
<HTML>
<HEAD>
<TITLE>Counter-controlled loops</TITLE>
<SCRIPT LANGUAGE="JavaScript">
// Initialization, loop condition and incrementing
// are all included in the for structure header.
for ( var counter = 1; counter <= 7; ++counter )
[Link]( "<p><FONT SIZE = '" + counter + "'>HTML font size " +
counter + "</FONT></p>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil 22
The “while“ loop
• Allows repeatable code until a given condition
is met
• Useful when the program should go on for an
indeterminate length of time
• Must have a way of terminating the structure
from within the loop!
• Pre-Test Loop (Loop may NEVER execute)
3 basic parts of the while loop
• The condition being tested
• The action to be performed while the
condition is evaluated to be true
• A method by which the condition can be
evaluated to be false, ending the while
loop
While loop
while (sign is not a stop sign)
{ condition to test
keep driving; what to do while true
recognize next sign; how to stop
}
While loops and user control
• Many while loops have a definitive ending specified
in the condition programmed by the programmer
(i.e. – counters)
• However, most of the time we need code to repeat
until the user (not the programmer) decides when
it’s time to quit
• You can write a program like this using a combination
of while and if/else structures
Counter-controlled while loop
General Format:
initialization;
while ( loopContinuationTest ) {
statement
increment;
}
----------------------------------------------------------------------------------------------------------------
<HTML>
<HEAD>
<TITLE>Counter-controlled loops</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var counter = 1; // initialize the counter
while ( counter <= 7 ) // loop condition
{
[Link]( "<p><FONT SIZE = '" + counter + "'>HTML font size " +
counter + "</FONT></p>" );
++counter; // increment
}
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil 28
Creating an infinite loop
1: while (j < 10) {
2: n++;
3: values[n] = 0;
4: }
• There is a mistake in this example. The variable j doesn’t
actually change during the loop.
• This will create an infinite loop. The loop will continue
executing until it is stopped by the user, or until it
generates an error of some kind
• JavaScript won’t give you an error that actually tells you
there is an infinite loop.
Basic parts of a Do/While loop
• The action to be performed AT LEAST
ONCE and while the condition is
evaluated to be true.
• The condition to test.
• A method by which the condition can be
evaluated to be false, ending the while
loop.
Do/While loop
do
{
keep driving; what to do while true
recognize next sign; how to stop
condition to test
}
while (sign is not a stop sign);
Example
<script >
[Link]("<b>Using do...while loops </b><br />");
var i = 6;
[Link]("Even numbers from 6 to less than 18<br />");
do
{
[Link](i + "<br />");
i = i + 2;
}while(i<18)
</script>
Using do...while loops
Even numbers from 6 to less than 18
6
8
10
12
14
16
Do/While loop
General Format:
do {
statement
} while ( condition );
-----------------------------------------------------------------------------------------------------
<HTML>
<HEAD>
<TITLE>Using the do/while loop</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var counter = 1;
do {
[Link]( "<H" + counter + ">This is an H" + counter + " level head" + "</H" +
counter + ">" );
++ counter;
} while ( counter <= 6 );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil 34
Programmer-defined function
<HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
[Link]( "<H1>Square the numbers from 1 to 10</H1>" );
// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
[Link]( "The square of " + x + " is " + square( x ) + "<BR>" );
// square function definition
function square( y )
{
return y * y;
}
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil 36
Break statement (example)