This lab goes through the basic data types (Number and String) and control structures of the JavaScript programming language.
Two basic data types in JavaScript are Number and String.
There are no separate types for integers and doubles. You define a variable x
with let x
. You don’t need to specify data type. (In some old code, you may also see definition of variables with var x
. This is similar to let x
, but allows you to redefine the variable. var
is not recommended in new code in general.)
let a = 1;
let b = 2e3; /* 2 * (10*10*10) */
let c; /* c is undefined */
c = a * 1.5 + b;
console.log(c);
You can also define constant with const x
and assign an initial value. After definition, you cannot change the value of a constant.
Also notice that this example shows that semicolon at end of line is optional.
const pi = 3.1415927
let radius // declare a variable
radius = 4 // later, somehow the user inputs the value
console.log('area =', pi * radius ** 2)
In addition to the basic arithmetic operators (+, -, *, /, %) (ref), the Math built-in object (ref) provides some useful functions (e.g. Math.random()
, Math.floor()
, Math.ceil()
, Math.round()
, Math.pow()
, Math.sqrt()
and trigonometric functions.)
let r = 10
let area = Math.PI * r * r
// same as Math.PI * Math.pow(r,2)
// a number from 1,2,3,4,5 and 6
// Math.random() returns a number between 0 and 1
let dice = Math.floor(Math.random()*6)+1
let x = Math.sin(Math.PI/2) // 1
let y = Math.sqrt(-1) // NaN
Note: a recent update to the JavaScript language provides the new data type BigInt
. BigInt can represent integer of arbitrary length. Please refer to this page for more information.
The other commonly used JavaScript data type is String.
Strings can be delimited with single quote or double quote. Join two strings
with +
. Use the property .length
to check number of characters in a string.
let user = "peterchan"
let domain = 'ymail.com'
let addr = user + "@" + domain
let n = "seven".length // 5
String literals use backslash \
to escape character, e.g. \"
, \'
, \\
and \n
.
// no need to escape because the string is delimited with '
let s1 = 'A string with "double quoted text".'
// escape the backlash character
let s2 = 'c:\\inetpub\\index.html'
String literals can also use methods defined in the String class (ref). Examples:
const text = 'Mississippi'
let p = text.indexOf('ss') // location of 'ss'
const mesg = "All the best"
p = mesg.slice(0,3) // 'All'
p = mesg.slice(4) // 'the best'
p = mesg.slice(-4) // 'best'
p = mesg.slice(-4,-2) // 'be'
let A = "202.175.3.3".split('.')
// an array ['202', '175', '3', '3']
User input are usually returned as string. Before calculation, use parseInt()
or parseFloat()
to convert the string into an integer / floating point number.
const s = "3.14"
// unexpected result of string concatenation
console.log(s+1)
const pi = parseFloat(s)
console.log(pi+1)
In some code examples, you may also encounter using the prefix operator +
to convert a string into a number. However, I would recommend to use parseFloat
for easier understanding of the code.
const s = "3.14"
const pi = +s // pi is the Number 3.14
There are various methods to change a number into a string.
let n = 12;
let s1 = n.toString(); // "12"
let s2 = '' + n; // automatic conversion in string concatenation
A new features in ES6 is template string.
Template strings support interpolation. They evaluate JavaScript expressions embedded in ${}
and insert the result into the string. Notice the back ticks used to delimit a template string.
let user = "Peter";
let age = 18;
let s = `${user}'s age is ${age}`;
console.log(s);
A longer example to illustrate number-string conversion. The browser built-in function prompt
displays a dialog box with the given prompt and asks the user for a string input. See reference for more information about other browser built-in functions for input/output.
let s = window.prompt('Enter radius of the circle');
let r = parseFloat(s);
console.log(`Area = ${Math.PI * r * r}`);
You can compare numbers and strings using the operators <
, <=
, >
, >=
, ==
and !=
.
Comparison results are either true
or false
, which are the only two values in boolean
data type.
"apple" == "Apple" // false
"apple" < 'banana' // true
The first four operators may convert the data if they are of different data type. It is especially confusing if you compare numbers with strings. JavaScript converts strings into numbers before comparison. In general, it is better to do the conversion by yourself.
"1" == 1.0 // true
3 == '3.0' // true
'3' == '3.0' // false!
Some authors recommend the usage of ===
instead of ==
in comparison. The operator ===
does not convert values before comparison. Similarly, !==
checks whether two values are not equal without automatic type conversion.
Similar to Java, you can use &&
and ||
to combine comparison tests.
The control structure if, for and while are similar to those in Java. Please read the online reference of if…else, for, while and switch for detail.
let a = 1, b = -3, c = 2; // roots are 1 and 2
// let a = 1, b = 0, c = 1; // roots are i and -i
let det = b * b - 4 * a * c;
let root1, root2;
if (det>=0) {
// these two are Number
root1 = (-b - Math.sqrt(det)) / (2*a);
root2 = (-b + Math.sqrt(det)) / (2*a);
} else {
// these two are String.. sorry, no complex number support
root1 = `${-b/2/a} - ${Math.sqrt(-det)/2/a}i`;
root2 = `${-b/2/a} + ${Math.sqrt(-det)/2/a}i`;
}
console.log(`${a} x^2 + ${b} x + ${c} = 0`);
console.log(`The roots are ${root1} and ${root2}`);
Examples on loops.
// calculate 1+2+3+...+10;
let sum = 0;
for (let k=1; k<=10; k++) {
sum += k;
}
console.log(`The sum of 1+2+...+10 = ${sum}.`);
// calculate 1*1+2*2+...+n*n, where n*n<100;
let i = 1; let sum = 0;
while (i*i<100) {
sum += i*i;
i++;
}
console.log(`The sum of squares < 100 is ${sum}.`)
You might have noticed that when you define a variable with let x
or const x
, you don’t need to specify a data type. A JavaScript variable is not tied to a specific data type in declaration, and can hold values of different data types.
let x = 10;
x++; // x is a Number
x = x.toString(2); // binary representation
console.log(x); // x is now a String
Write a program to calculate the sum of even positive numbers up to 30. (The answer should be 240)
The following program asks the user a number n
, and print a n
by n
squares to console.
let s = window.prompt('Enter size of the square');
/* convert the input string into a number */
let n = parseInt(s);
/* build a line with n stars */
let line = '';
for (let i=0; i<n; i++) { line = line + '* '; }
/* build a square with n lines */
let sqr = '';
for (let i=0; i<n; i++) { sqr = sqr + line + '\n';}
console.log(sqr);
Modify the program to print an empty square.
* * * * *
* *
* *
* *
* * * * *
The sample answers are available at ex2-1q1.js and ex2-1q2.js respectively.