Topic:
FundamentalsVariables, data types, operators, control flow, and your first lines of JS.
- 1. Hello World
- 2. A brief introduction to Javascript
- 3. Linking a JavaScript File
- 4. Values and Variables
- 5. Variable name conventions
- 6. Data Types
- 7. Basic Operators
- 8. Operator Precedence
- 9. Coding Challenge ##1
- 11. Taking Decisions: if else Statements
- 12. Coding Challenge ##2
- 13. Type Conversion and Coercion
- 14. Truthy and Falsy Values
- 15. Equality Operators: == vs. ===
- 16. Logical Operators
- 17. Coding Challenge ##3
- 18. The switch Statement
- 19. Statements and Expressions
- 20. The Conditional (Ternary) Operator
- 21. Coding Challenge ##4
The console.log() function prints output to the browser's developer console. It's the most basic debugging tool in JavaScript.
console.log("Hello World!") // → "Hello World!"💡 Concept: JavaScript is the only programming language that runs natively in web browsers. While HTML provides structure and CSS provides styling, JavaScript provides behavior and interactivity. Today, JavaScript also runs on servers (Node.js), mobile devices (React Native), and even IoT devices.
Why is it called JavaScript? Originally named "LiveScript," it was rebranded to ride the popularity of Java in the 1990s. Despite the similar name, JavaScript and Java are completely different languages with different designs and purposes.
JavaScript was initially created to “make web pages alive”.
The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.
let js = "amazing";
console.log(40 + 8 + 23 - 10);console.log("xoraus");
console.log(23);
let firstName = "Matilda";
console.log(firstName);
console.log(firstName);
console.log(firstName);📝 Naming Rules:
- Variable names can only contain letters, numbers, underscores (
_), and dollar signs ($)- The first character cannot be a number
- Reserved words (
function,return,class, etc.) cannot be used as names- JavaScript uses camelCase by convention:
myFirstJob,currentUser
Why camelCase? It improves readability without the verbosity of snake_case (my_first_job) or the ambiguity of PascalCase (MyFirstJob, reserved for classes).
let xoraus_matilda = "JM";
let $function = 27;
let person = "xoraus";
let PI = 3.1415;
let myFirstJob = "Coder";
let myCurrentJob = "Teacher";
let job1 = "programmer";
let job2 = "teacher";
console.log(myFirstJob);💡 Dynamic Typing: JavaScript is a dynamically typed language. This means you don't manually declare types — the engine figures it out at runtime. A variable can hold any type, and you can reassign it to a different type later.
| Type | Description | Example |
|---|---|---|
number |
Integers and floats | 23, 3.14 |
string |
Text sequences | "hello", 'world' |
boolean |
Logical true/false | true, false |
undefined |
Variable declared but not assigned | let x; |
null |
Intentional absence of value | let y = null; |
symbol |
Unique identifier (ES6+) | Symbol('id') |
bigint |
Arbitrarily large integers | 9007199254740991n |
object |
Complex data structures | {name: "Jonas"} |
⚠️ Quirk Alert:typeof nullreturns"object". This is a bug in JavaScript that has existed since 1995 and cannot be fixed without breaking the web.
let javascriptIsFun = true;
console.log(javascriptIsFun);
console.log(typeof true); // → "boolean"
console.log(typeof javascriptIsFun); // → "boolean"
console.log(typeof 23); // → "number"
console.log(typeof 'xoraus'); // → "string"
javascriptIsFun = 'YES!';
console.log(typeof javascriptIsFun); // → "boolean"
let year;
console.log(year);
console.log(typeof year);
year = 1991;
console.log(typeof year);
console.log(typeof null); // → "object" (JavaScript quirk!)
// Let, const and var
// Use let when the value will change in future
// Let is block scoped
// VAR is function-scoped
let age = 30;
age = 31; // here let (age) is mutable
const birthYear = 1991; // it is immutable
birthYear = 1990;
const job; // this will throw an error;
var job = 'programmer'; // used in legacy codebases
job = 'teacher'
lastName = 'Ahmed';
console.log(lastName);📝 Operator Categories:
- Arithmetic:
+,-,*,/,**(exponent),%(remainder)- Assignment:
=,+=,-=,*=,/=,++,--- Comparison:
>,<,>=,<=,===,!==- Logical:
&&(AND),||(OR),!(NOT)
The + operator is special: When used with strings, it performs concatenation instead of addition. This is the most common source of accidental type coercion bugs.
const now = 2037;
const ageXoraus = now - 1991;
const ageSarah = now - 2018;
console.log(ageXoraus, ageSarah);
console.log(ageXoraus * 2, ageXoraus / 10, 2 ** 3);
// 2 ** 3 means 2 to the power of 3 = 2 * 2 * 2
const firstName = 'xoraus';
const lastName = 'Ahmed';
console.log(firstName + ' ' + lastName);let x = 10 + 5; // → 15
x += 10; // x = x + 10 - Output: 25
x *= 4; // x = x * 4 - Output: 100
x++; // x = x + 1
x--; // x = x - 1
x--;
console.log(x);console.log(ageXoraus > ageSarah); // >, <, >=, <=
console.log(ageSarah >= 18); // → true
const isFullAge = ageSarah >= 18;
console.log(now - 1991 > now - 2018);const now = 2037;
const ageXoraus = now - 1991;
const ageSarah = now - 2018;
console.log(now - 1991 > now - 2018);
let x, y;
x = y = 25 - 10 - 5; // → x = y = 10, x = 10 - Assignment works from right to left
console.log(x, y);
const averageAge = (ageXoraus + ageSarah) / 2;
console.log(ageXoraus, ageSarah, averageAge);Mark and John are trying to compare their BMI (Body Mass Index), which is calculated using the formula: BMI = mass / height ** 2 = mass / (height * height). (mass in kg and height in meter).
- Store Mark's and John's mass and height in variables
- Calculate both their BMIs using the formula (you can even implement both versions)
- Create a boolean variable 'markHigherBMI' containing information about whether Mark has a higher BMI than John.
- TEST DATA 1: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.
- TEST DATA 2: Marks weights 95 kg and is 1.88 m tall. John weights 85 kg and is 1.76 m tall.
My Solution
const markMass = 78;
const markHeight = 1.69;
const johnMass = 92;
const johnHeight = 1.95;
function calculateBMI(mass, height) {
let BMI;
BMI = mass / height ** 2;
return BMI
}
const markBMI = calculateBMI(markMass,markHeight);
const johnBMI = calculateBMI(johnMass, johnHeight);
const markHigherBMI = markBMI > johnBMI
console.log(markBMI)
console.log(johnBMI)
console.log(markHigherBMI)Solution by xoraus
const massMark = 78;
const heightMark = 1.69;
const massJohn = 92;
const heightJohn = 1.95;
const massMark = 95;
const heightMark = 1.88;
const massJohn = 85;
const heightJohn = 1.76;
const BMIMark = massMark / heightMark ** 2;
const BMIJohn = massJohn / (heightJohn * heightJohn);
const markHigherBMI = BMIMark > BMIJohn;
console.log(BMIMark, BMIJohn, markHigherBMI);const firstName = 'xoraus';
const job = 'teacher';
const birthYear = 1991;
const year = 2037;
const xoraus = "I'm " + firstName + ', a ' + (year - birthYear) + ' year old ' + job + '!'; // concept of type coercion
console.log(xoraus);
const xorausNew = `I'm ${firstName}, a ${year - birthYear} year old ${job}!`; // one of most used ES6 Feature :)
console.log(xorausNew);
console.log(`Just a regular string...`);
console.log('String with \n\
multiple \n\
lines');
console.log(`String
multiple
lines`);const age = 15;
if (age >= 18) {
console.log('Sarah can start driving license 🚗');
} else {
const yearsLeft = 18 - age;
console.log(`Sarah is too young. Wait another ${yearsLeft} years :)`);
}
const birthYear = 2012;
let century;
if (birthYear <= 2000) {
century = 20;
} else {
century = 21;
}
console.log(century);Use the BMI example from Challenge ##1, and the code you already wrote, and improve it:
- Print a nice output to the console, saying who has the higher BMI. The message can be either "Mark's BMI is higher than John's!" or "John's BMI is higher than Mark's!"
- Use a template literal to include the BMI values in the outputs. Example: "Mark's BMI (28.3) is higher than John's (23.9)!"
My Solution
const markMass = 78;
const markHeight = 1.69;
const johnMass = 92;
const johnHeight = 1.95;
function calculateBMI(mass, height) {
let BMI;
BMI = mass / height ** 2;
return BMI
}
const markBMI = calculateBMI(markMass,markHeight);
const johnBMI = calculateBMI(johnMass, johnHeight);
// console.log(`BMI of Mark is ${markBMI}`)
// console.log(`BMI of John is ${johnBMI}`)
// console.log(`Does Mark has higher BMI - ${markHigherBMI}`)
if (markBMI > johnBMI) {
console.log(`Mark's BMI (${markBMI}) is higher than John's (${johnBMI})!`)
} else {
console.log(`John's BMI (${johnBMI}) is higher than Marks's (${markBMI})!`)
}Another Solution
// Test Data 1
const massMark = 78;
const heightMark = 1.69;
const massJohn = 92;
const heightJohn = 1.95;
// Test Data 2
// Const massMark = 95;
// Const heightMark = 1.88;
// Const massJohn = 85;
// Const heightJohn = 1.76;
const BMIMark = massMark / heightMark ** 2;
const BMIJohn = massJohn / (heightJohn * heightJohn);
console.log(BMIMark, BMIJohn);
if (BMIMark > BMIJohn) {
console.log(`Mark's BMI (${BMIMark}) is higher than John's (${BMIJohn})!`)
} else {
console.log(`John's BMI (${BMIJohn}) is higher than Marks's (${BMIMark})!`)
}// Type Conversion (Explicit): We manually convert from one type to another using functions like Number(), String(), and Boolean().
const inputYear = '1991';
console.log(Number(inputYear), inputYear);
console.log(Number(inputYear) + 18);
console.log(Number('xoraus')); // → NaN (Not a Number - it actually means invalid number)
console.log(typeof NaN); // → number
console.log(String(23), 23); // String(23) is a string; 23 is a number
// Type Coercion (Implicit): JavaScript automatically converts types behind the scenes when operators encounter mismatched types.
// Coercion happens whenever an operator encounters values of different types and tries to make them compatible.
console.log('I am ' + 23 + ' years old'); // → "I am 23 years old" (number coerced to string)
console.log('23' - '10' - 3); // → 10 (strings converted to numbers by - operator)
console.log('23' * '2'); // → 46 (strings converted to numbers by * operator)
console.log('23' / '2'); // → 11.5 (strings converted to numbers by / operator)
let n = '1' + 1; // String - '11'
n = n - 1; // String 11 will be converted to number 11 then 11 - 1 = 10
console.log(n); // 10
console.log(2+3+4+'5') // → 95 as string ; 9 + '5' → 95
console.log('10'-'4'-'3'-2 +'5') // → 15 as string ; 1 + '5' → 15📝 Why does this matter? In conditions (
if,while, ternary), JavaScript coerces values to booleans. Knowing the 5 falsy values prevents logical errors — especially with0and empty strings, which are valid values but evaluate asfalse.
The 5 Falsy Values: 0, '' (empty string), undefined, null, NaN
⚠️ Gotcha: An empty object{}and an empty array[]are truthy, not falsy. Beginners often assume they're "empty" so they should be false.
// In javascript there are 5 falsy values: 0, '', undefined, null, NaN
console.log(Boolean(0)); // → false
console.log(Boolean(undefined)); // → false
console.log(Boolean('Jonas')); // → true
console.log(Boolean({})); // → true
console.log(Boolean('')); // → false
const money = 100;
if (money) {
console.log("Don't spend it all ;)");
} else {
console.log('You should get a job!');
}
let height = 0;
if (height) {
console.log('YAY! Height is defined');
} else {
console.log('Height is UNDEFINED'); // this will be the output because 0 is a falsy value. But this is a bug because we have defined height as 0. We can fix this using logical operators.
}So in practice, the conversion to boolean is always implicit, not explicit, or in other words is always typed coercion that JavaScript does automatically behind the scenes.
But when exactly does JavaScript do type coercion to booleans? Well, it happens in two scenarios. First, when using logical operators, and Second in logical context, like for example, in the condition of an if else statement.
const age = '18';
if (age === 18) console.log('You just became an adult :D (strict)'); // → true (strict equality doesn't perform type coercion)
if (age == 18) console.log('You just became an adult :D (loose)'); // Loose equality does the type coercion therefore output: true (the string '18' will be converted to number before checking)
const favourite = Number(prompt("What's your favourite number?"));
console.log(favourite);
console.log(typeof favourite);
if (favourite === 23) { // 22 === 23 -> FALSE
console.log('Cool! 23 is an amazing number!')
} else if (favourite === 7) {
console.log('7 is also a cool number')
} else if (favourite === 9) {
console.log('9 is also a cool number')
} else {
console.log('Number is not 23 or 7 or 9')
}
if (favourite !== 23) console.log('Why not 23?');💡 Best Practice: Always use strict equality (
===) for comparisons. Loose equality (==) performs type coercion and leads to unpredictable bugs.
So as a general rule for clean code, avoid the loose equality operator as much as you can. So when comparing values, always use strict equality with the three equal signs.
💡 Short-Circuit Evaluation: Logical operators don't just return
trueorfalse— they return the first operand that determines the result.
A && B: IfAis falsy, returnA. Otherwise returnB.A || B: IfAis truthy, returnA. Otherwise returnB.
This behavior is incredibly powerful for setting default values and conditional rendering.
const hasDriversLicense = true; // A
const hasGoodVision = true; // B
console.log(hasDriversLicense && hasGoodVision); // → true
console.log(hasDriversLicense || hasGoodVision); // → true
console.log(!hasDriversLicense); // → false
// If (hasDriversLicense && hasGoodVision) {
// console.log('Sarah is able to drive!');
// } else {
// console.log('Someone else should drive...');
// }
const isTired = false; // C
console.log(hasDriversLicense && hasGoodVision && isTired); // → false
if (hasDriversLicense && hasGoodVision && !isTired) {
console.log('Sarah is able to drive!');
} else {
console.log('Someone else should drive...');
}
// → Sarah is able to drive!The NOT operator actually has proceedings over the OR and AND operators.
There are two gymnastics teams, Dolphins and Koalas. They compete against each other 3 times. The winner with the highest average score wins the a trophy!
- Calculate the average score for each team, using the test data below
- Compare the team's average scores to determine the winner of the competition, and print it to the console. Don't forget that there can be a draw, so test for that as well (draw means they have the same average score).
- BONUS 1: Include a requirement for a minimum score of 100. With this rule, a team only wins if it has a higher score than the other team, and the same time a score of at least 100 points. HINT: Use a logical operator to test for minimum score, as well as multiple else-if blocks 😉
- BONUS 2: Minimum score also applies to a draw! So a draw only happens when both teams have the same score and both have a score greater or equal 100 points. Otherwise, no team wins the trophy.
TEST DATA: Dolphins score 96, 108 and 89. Koalas score 88, 91 and 110 TEST DATA BONUS 1: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 123 TEST DATA BONUS 2: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 106
My Solution
const scoreDolphins = (96 + 108 + 89) / 3;
const scoreKoalas = (88 + 91 + 110) / 3;
console.log(scoreDolphins, scoreKoalas);
if (scoreDolphins > scoreKoalas) {
console.log('Dolphins win the trophy 🏆');
} else if (scoreKoalas > scoreDolphins) {
console.log('Koalas win the trophy 🏆');
} else if (scoreDolphins === scoreKoalas) {
console.log('Both win the trophy!');
}BONUS 1
const scoreDolphins = (97 + 112 + 80) / 3;
const scoreKoalas = (109 + 95 + 50) / 3;
console.log(scoreDolphins, scoreKoalas);
if (scoreDolphins > scoreKoalas && scoreDolphins >= 100) {
console.log('Dolphins win the trophy 🏆');
} else if (scoreKoalas > scoreDolphins && scoreKoalas >= 100) {
console.log('Koalas win the trophy 🏆');
} else if (scoreDolphins === scoreKoalas && scoreDolphins >= 100 && scoreKoalas >= 100) {
console.log('Both win the trophy!');
} else {
console.log('No one wins the trophy 😭');
}const day = 'friday';
switch (day) {
case 'monday': // day === 'monday'
console.log('Plan course structure');
console.log('Go to coding meetup');
break;
case 'tuesday':
console.log('Prepare theory videos');
break;
case 'wednesday':
case 'thursday':
console.log('Write code examples');
break;
case 'friday':
console.log('Record videos');
break;
case 'saturday':
case 'sunday':
console.log('Enjoy the weekend :D');
break;
default:
console.log('Not a valid day!');
}
if (day === 'monday') {
console.log('Plan course structure');
console.log('Go to coding meetup');
} else if (day === 'tuesday') {
console.log('Prepare theory videos');
} else if (day === 'wednesday' || day === 'thursday') {
console.log('Write code examples');
} else if (day === 'friday') {
console.log('Record videos');
} else if (day === 'saturday' || day === 'sunday') {
console.log('Enjoy the weekend :D');
} else {
console.log('Not a valid day!');
}3 + 4 // → 7 - an expression
1991
true && false && !false
// Following is a Statement
if (50 > 10) {
const str = '50 is bigger';
}
const me = 'Xoraus';
console.log(`I'm ${2050 - 1997} years old ${me}`); // In javascript literals we can use expressions but not statements.- an expression is a piece of code that produces a value.
- statements are like full sentences that translate our actions.
const age = 23;
// Age >= 18 ? console.log('I like to drink wine 🍷') : console.log('I like to drink water 💧');
const drink = age >= 18 ? 'Sharbat-e-Jaam 🍷' : 'water 💧'
console.log(drink);
let drink2;
if (age >= 18) {
drink2 = 'Sharbat-e-Jaam 🍷';
} else {
drink2 = 'water 💧';
}
console.log(drink2);
console.log(`I like to drink ${age >= 18 ? 'Sharbat-e-Jaam 🍷' : 'water 💧'}`);Steven wants to build a very simple tip calculator for whenever he goes eating in a restaurant. In his country, it's usual to tip 15% if the bill value is between 50 and 300. If the value is different, the tip is 20%.
- Your task is to calculate the tip, depending on the bill value. Create a variable called 'tip' for this. It's not allowed to use an if else statement 😅 (If it's easier for you, you can start with an if else statement, and then try to convert it to a ternary operator!)
- Print a string to the console containing the bill value, the tip, and the final value (bill + tip). Example: 'The bill was 275, the tip was 41.25, and the total value 316.25'
TEST DATA: Test for bill values 275, 40 and 430
HINT: To calculate 20% of a value, simply multiply it by 20/100 = 0.2 HINT: Value X is between 50 and 300, if it's >= 50 && <= 300 😉
const bill = 275;
const tip = (bill >= 50 && bill <= 300) ? 0.15 * bill : 0.20 * bill;
const totalValue = bill + tip;
console.log(`The bill was ${bill}, the tip was ${tip}, and the total value ${bill + tip}`);| Concept | Syntax / Rule |
|---|---|
| Declare variable | let name = value; |
| Constant | const PI = 3.14; |
| Template literal | `Hello ${name}` |
| Strict equality | === (prefer over ==) |
| Ternary operator | condition ? A : B |
| Falsy values | 0, '', undefined, null, NaN |
| Type coercion | '23' - '10' = 13 (minus triggers Number) |
💡 Best Practice: Always use
constby default. Switch toletonly when you know the value will change. Never usevarin modern code.
← Start of Course | 🏠 Home | 📄 02. JavaScript Fundamentals Part 2 →
Happy Coding! 🚀