18 November 2024
Lesson 3
Data Types
- String: Text values enclosed in single or double quotes.
Example:
'mama'
- Number: Numeric values, integers, or decimals.
Example:
10
- Boolean: Represents true or false values.
Example:
isPaid = true
- Null: Represents "nothing"; explicitly set by the developer.
Example:
obj.name = null
- Undefined: Represents "nothing"; not explicitly set, but rather assigned by JavaScript.
Example:
let variable;
Special Values
- NaN (Not a Number): Result of invalid mathematical operations.
Example:
Math.sqrt(-1)
- Object: A collection of key-value pairs.
Example:
const obj = { name: 'Alex', surname: undefined, };
Arrays
- Definition: An ordered collection of elements.
Example:
['red', 'yellow', 22, false, true]
- Indexing: Starts from 0.
Example:
const personArray = ['mike', 23]; console.log(personArray[0]); // Output: 'mike'
Objects
- Definition: A collection of properties defined as key-value pairs.
Example:
const car = { name: 'Mazda', yearOfBuild: 2020, color: 'red', isNew: true, owner: { name: 'Oly', salary: Infinity, }, };
Variables
const
: Used for values that do not change. Example:const ITEMS_TO_FETCH = 10;
let
: Used for values that may change. Example:let tempToday = '+3';
var
: An older way to declare variables (avoid using in modern JavaScript). Example:var item = '10'; item = '12';
Conditional Statements
if
Statement: Executes code blocks based on conditions. Example:if (color === 'green') { console.log('cars go'); } else if (color === 'yellow') { console.log('cars prepare'); } else { console.log('cars stop'); }
switch
Statement: Useful for multiple conditions. Example:switch (color) { case 'green': console.log('cars go'); break; default: console.log('cars stop'); }
Loops
- For Loop: Iterates through arrays or other collections.
Example:
const names = ['mike', 'john', 'alex']; for (let i = 0; i < names.length; i++) { console.log(names[i].toUpperCase()); }
- While Loop: Continues while a condition is true.
Example:
let index = 0; while (index < names.length) { console.log(names[index]); index++; }
Functions
- Definition: A reusable block of code.
Example:
function updateName(name) { return name.toUpperCase(); } console.log(updateName('alex'));
- Arrow Functions: A modern shorthand for functions.
Example:
const updateName = (name) => name.toUpperCase();
Practical Examples
- Random Color Generator:
function createColor() { const randomValue = Math.ceil(Math.random() * 100); return randomValue < 30 ? 'red' : 'green'; } console.log(createColor());
- Save Cart to Database:
function saveCart(items) { // Save to DB } if (userAddedItemToCart === true) { saveCart(updatedCart); }
Summary
In this lesson, we explored:
- Basic data types (
string
,number
,boolean
,null
,undefined
). - How to work with objects and arrays.
- Variables (
const
,let
,var
). - Control structures (
if
,switch
, loops). - Functions (traditional and arrow).
Practice these concepts to strengthen your understanding of JavaScript!