The average and the best grade
Write a function stats(array) that, for an array of grades, returns an object with the average (rounded to two decimal places), the highest and the lowest grade. Try it in the console for [5, 4, 3, 5, 5, 2].
JavaScript is the programming language of the browser: it makes pages interactive. If you already know C++ or Python, most of the concepts are familiar – this lesson shows how they are written in JavaScript: variables, types, branching, loops, arrays, objects and functions.
| Way | How |
|---|---|
| the browser console | F12 → Console; you type a statement and see the result right away – ideal for trying things out |
| in the page | <script> ... </script> at the end of the body |
| a separate file (best) | <script src="js/script.js" defer></script> in the head; defer – run it only when the whole HTML has loaded |
| outside the browser | Node.js: node program.js on the command line |
<p>Open F12 → Console and click the button.</p>
<button onclick="console.log('Hello from the console!'); this.textContent = 'Clicked!';">Click</button>
<p id="output"></p>
<script>
// output on the page
document.getElementById("output").textContent = "2 + 3 = " + (2 + 3);
</script>
Result:
console.log(...) is like cout / print – it prints to the console. Errors in the code are also shown there (in red).
let name = "Anna"; // text (string)
let grade = 7; // a number – there are no separate int and double
let average = 4.75;
let competitor = true; // a logical value (boolean)
const PI = 3.14159; // a constant – it cannot change
grade = grade + 1; // let can change
console.log(name, grade); // Anna 8
console.log(typeof average); // "number"
console.log(`${name} is in grade ${grade}`); // a template string with ` (backtick)
| C++ | Python | JavaScript | |
|---|---|---|---|
| variable | int x = 5; | x = 5 | let x = 5; |
| constant | const int N = 10; | N = 10 (by convention) | const N = 10; |
| output | cout << x; | print(x) | console.log(x); |
| integer division | 7 / 2 → 3 | 7 // 2 → 3 | Math.floor(7 / 2) → 3 (7 / 2 is 3.5) |
| equality | == | == | === (strict, without type conversion) |
"5" + 3 gives "53" (text), while "5" * 3 gives 15. Convert numbers from form fields with Number(...). Always use === instead of ==, because "5" == 5 is true, while "5" === 5 is not. Do not use the old word var.let points = 72;
if (points >= 90) {
console.log("excellent");
} else if (points >= 60) {
console.log("passed");
} else {
console.log("keep practising");
}
// a for loop – the same as in C++
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("sum 1..10 =", sum); // 55
// while
let n = 1234, digits = 0;
while (n > 0) {
n = Math.floor(n / 10);
digits++;
}
console.log("number of digits:", digits); // 4
The logical operators are as in C++: && (and), || (or), ! (not).
let grades = [5, 4, 5, 3];
grades.push(5); // add to the end
console.log(grades.length); // 5
console.log(grades[0]); // 5 – indexes start at 0
for (const g of grades) { // going through all the elements
console.log(g);
}
// useful array methods
let doubled = grades.map(g => g * 2); // [10, 8, 10, 6, 10]
let fives = grades.filter(g => g === 5); // [5, 5, 5]
let total = grades.reduce((s, g) => s + g, 0); // 22
grades.sort((a, b) => a - b); // sorting numbers in ascending order
// an object: a group of named data (like a struct / dictionary)
let student = { name: "Anna", grade: 7, grades: [5, 4, 5] };
console.log(student.name); // Anna
student.city = "Belgrade"; // a new property
Watch out: [10, 9, 1].sort() gives [1, 10, 9], because without a function it compares as text. For numbers always write sort((a, b) => a - b).
function rectangleArea(a, b) {
return a * b;
}
// the same, shorter notation – an "arrow" function
const square = x => x * x;
function isPrime(n) {
if (n < 2) return false;
for (let d = 2; d * d <= n; d++) {
if (n % d === 0) return false;
}
return true;
}
console.log(rectangleArea(3, 4)); // 12
console.log(square(9)); // 81
let primes = [];
for (let i = 1; i <= 30; i++) if (isPrime(i)) primes.push(i);
console.log(primes.join(" ")); // 2 3 5 7 11 13 17 19 23 29
The function isPrime is the same as in the C++ lessons – the algorithms do not change, only the notation. Functions are especially important in JavaScript because they are called in response to events (a click, input) – the topic of the next lesson.
Each task has an example, a hint and a solution. The solutions have been checked in the browser.
Write a function stats(array) that, for an array of grades, returns an object with the average (rounded to two decimal places), the highest and the lowest grade. Try it in the console for [5, 4, 3, 5, 5, 2].
Print the numbers from 1 to 20, but instead of a number divisible by 3 print "Fizz", instead of one divisible by 5 "Buzz", and instead of one divisible by both 3 and 5 "FizzBuzz". Print the result on one line, separated by spaces.
"5" + 3 is "53" – convert values from a form into a number with Number().===, not ==.7 / 2 is 3.5; for integer division use Math.floor(7 / 2).1. How do you declare a variable whose value changes?
2. What is "2" + 2 in JavaScript?
3. Which operator compares without type conversion?
4. What does [3, 1, 2].map(x => x * 10) return?