Web Development courseLesson 6 of 20 · tap to see all lessons
Web Development · Beginner
JavaScript Fundamentals: Variables, Types, Operators, Conditions, Loops, Functions, Arrays, and Objects
Learn the JavaScript every web page uses: let and const, data types, operators, if and loops, functions and arrow functions, arrays, and objects, all runnable here.
- Qyubie Learn Editorial Team
- Published
- 14 min read
Includes 2 exercises and 1 quick check you can do right here.
PHP runs on the server, before the page is sent. JavaScript runs in the browser, after the page arrives, so it can react the instant a user clicks, types, or scrolls without asking the server for a new page. It's the only programming language browsers run, and with Node.js (lesson 11) it runs on servers too. React and Next.js, later in this course, are JavaScript.
By the end of this lesson you will be able to:
- declare variables with
letandconst, and use JavaScript's data types, - use arithmetic, comparison, and logical operators,
- write conditions and loops,
- write functions, including arrow functions, and
- work with arrays and objects.
Every example below has a Run button. console.log() prints to the output box, the same way it prints to the browser's Console tab (F12) on a real page.
Where JavaScript goes
On a web page, JavaScript goes in a <script> element, usually in an external file loaded at the end of the <body>:
<body>
<h1>Hello</h1>
<script src="app.js"></script>
</body>Loading it last means the HTML is already on the page when the script runs. (Or put the tag in the <head> with defer: <script src="app.js" defer></script>.) In the next lesson your scripts will change the page itself; this lesson focuses on the language.
Variables and data types
Try it · JavaScript
Output:
BISU 4
string number
Hi Ana, welcome to BISU!
3 ANA- Use
constby default, andletonly when the value must change. Avoid the oldvar. - JavaScript has one number type for whole numbers and decimals.
- Template literals use backticks and
${...}to put values inside text, like PHP's double quotes. - Strings, numbers, and booleans (
true/false) are the everyday types.nullmeans "no value" on purpose;undefinedmeans "never given a value".
JavaScript converts types on its own, sometimes surprisingly:
Try it · JavaScript
Output:
53
2
43
3.75
0.30000000000000004
0.30Values from forms are always strings, so convert them with Number() or parseFloat() before doing math. And like Java's double, 0.1 + 0.2 isn't exactly 0.3; round with toFixed when you display money.
Operators
Try it · JavaScript
Output:
22 12 85 3.4
2 256
16
true
false
true
Guest
bigAs in PHP, always use === and !==. ?? gives a fallback for a missing value, and the ternary condition ? a : b picks between two values.
Conditions
Try it · JavaScript
Output:
82: Passed
Weekend
falsy: 0
falsy:
falsy: null
falsy: undefined
falsy: NaN
falsy: falseEvery value counts as true or false in a condition. The six falsy values are 0, "", null, undefined, NaN, and false; everything else is truthy, including "0" and empty arrays. That's why if (input.value) works as "if the user typed something".
Loops
Try it · JavaScript
Output:
Row 1
Row 2
Row 3
243
- CS 324
- CS 325
- GE 7
0 CS 324
1 CS 325
2 GE 7for...of goes through the values of an array (like PHP's foreach). break and continue work as in Java and PHP.
Exercise · JavaScript
Multiplication row
Use a loop to print the 7 times table from 7 × 1 to 7 × 5, one line each, like 7 x 1 = 7.
Expected output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Hint
for (let i = 1; i <= 5; i++) { console.log(${n} x ${i} = ${n * i}); }
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
const n = 7;
for (let i = 1; i <= 5; i++) {
console.log(`${n} x ${i} = ${n * i}`);
}
Functions
Try it · JavaScript
Output:
85
Hello, Ana!
Maayong buntag, Ben!
81 Failedfunction name(params) { ... return value; }is a function declaration.- An arrow function
(params) => expressionreturns the expression's value automatically. With curly braces,(x) => { ...; return y; }, you needreturn. - Functions are values: you can store them in variables and pass them to other functions, as
forEachdid above. That's called a callback, and the DOM,fetch, and React all depend on it.
Arrays
Try it · JavaScript
Output:
["guava","mango","banana","pineapple"] 4
guava pineapple
true -1
guava | mango | banana
[85,92,78,95] [90,97,66,83,100] 411 [95,92,85,78,61]
92The three array methods you'll use constantly, especially in React:
| Method | Returns | Example |
|---|---|---|
filter(fn) | a new array of the items where fn returns true | passing scores |
map(fn) | a new array with fn applied to each item | add 5 to each |
reduce(fn, start) | one value built from all items | the total |
They don't change the original array. sort does change it, which is why the example sorts a copy ([...scores]). Without the comparison function, sort orders numbers as text, so [10, 9, 100] becomes [10, 100, 9].
Objects
An object groups related values under named keys, like a PHP associative array:
Try it · JavaScript
Output:
Ana Reyes
BSCS
Ana Reyes (BSCS 4)
6
Ana Reyes 1.75
1 4Arrays of objects are how data arrives from servers and databases:
Try it · JavaScript
Output:
Ana, Cara
Top: Ana
{"name":"Ana","grade":92}JSON.stringify turns an object into JSON text, the format APIs use to send data (lesson 10). JSON.parse turns JSON text back into an object.
Quick check
Exercise · JavaScript
Class report
Using the students array, print the average grade rounded to 1 decimal (Average: 83.7), then the names of students below 75, joined with commas (Below 75: Ben, Dan).
Expected output
Average: 83.7 Below 75: Ben, Dan
Hint
Sum with reduce((sum, s) => sum + s.grade, 0), divide by students.length, and use .toFixed(1). For the names: filter, then map to s.name, then join(", ").
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
const students = [
{ name: "Ana", grade: 92 },
{ name: "Ben", grade: 74 },
{ name: "Cara", grade: 85 },
{ name: "Dan", grade: 70 },
{ name: "Ella", grade: 97 },
{ name: "Felix", grade: 84 },
];
const avg = students.reduce((sum, s) => sum + s.grade, 0) / students.length;
console.log(`Average: ${avg.toFixed(1)}`);
const low = students.filter((s) => s.grade < 75).map((s) => s.name);
console.log(`Below 75: ${low.join(", ")}`);
Common mistakes
=instead of===in a condition, which assigns instead of comparing.- Doing math on strings from forms:
"5" + 3is"53". Convert withNumber()first. - Reassigning a
const: Assignment to constant variable. Useletif it must change. - Forgetting
returnin a function with curly braces, so it returnsundefined. - Sorting numbers without a compare function.
- Misspelling a property:
student.nmaegivesundefined, not an error.
Summary
- JavaScript runs in the browser. Use
constby default andletwhen a value changes; template literals put values into text. - Types: string, number, boolean,
null,undefined, arrays, objects. Use===andNumber()to avoid conversion surprises. if/else,switch,for,while, andfor...ofwork much as in Java and PHP; six values are falsy.- Functions can be declarations or arrow functions, and can be passed around as callbacks.
- Arrays have
push,includes,filter,map, andreduce; objects hold named properties, and arrays of objects hold records.
Next lesson: the DOM and interactive web pages: using JavaScript to change the page and respond to clicks and typing.