Fundamentals

Fundamentals


Hello World

  • Open console in developer tools using ctrl+shift+J
  • This is the repl environment where we can run JS code for learning or testing purposes

Running in Sources

  • We can also run JS inside the sources tab in Chrome
notion image

Introduction

JavaScript is a high-level, object-oriented, multi-paradigm language that powers dynamic web applications. Its usage extends beyond browsers to backend, mobile, and desktop development, making it a must-learn language.

Linking

  • Internal scripts are written in the <script> tag in html
  • External scripts can be linked using the <script src=”script.js”></script>
  • We use console.log() to log something on the developer console
  • We don’t add scripts in the head as elements are not rendered at that time so DOM manipulation won’t be possible
<script src="main.js"></script>

Async vs Defer

There are two phases in script lifecycle:
  1. First the script is downloaded
  1. Then it will be executed immediately
notion image
There are three ways of adding scripts:
  1. Normal mode
  1. Using async keyword
  1. Using defer keyword
In normal mode, script blocks rendering, downloads, and executes before continuing. Async downloads and executes immediately after, useful for independent scripts like analytics. Defer downloads in parallel but executes in order after HTML parsing, ideal for maintaining script execution order.
notion image

Single threaded

JavaScript executes code in a single-threaded environment, meaning it processes one task at a time. We will dive deeper into this next week.
notion image
notion image

Garbage collected

JavaScript automatically manages memory allocation and deallocation through garbage collection, which helps prevent memory leaks by automatically reclaiming memory used by objects no longer in use.
notion image

Values & Variables

A value is data (e.g., 45, "Chak"). A variable stores this data and is declared using let, const, or var (deprecated). Use descriptive names, avoid special characters, and prefer camelCase. Reserve all-uppercase for constants.

Conventions

  • Use descriptive variable names
  • Names must be camelCased. Using underscore another_name is common in Python or Ruby
  • A name can’t start with a number and can’t contain special characters other than $ or _
  • Can’t be a reserved keyword (like new or function)
  • All uppercase are used for constants (PI)
camelCase PascalCase mumblecase or flatcase snake_case kebab-case doubleHumpCamelCase SCREAMING_SNAKE_CASE or UPPER_SNAKE_CASE for constants

The Console

  • This is a repl environment present in the browser’s developer tools used for debugging purposes
  • The console object in JS allows us to print to the developer tool’s Console tab
  • The console.clear() clears up the console
notion image

Console Group

We can also show as a tooltip using console.group() and console.groupEnd()
notion image

Console Styles

We can also give styles for this we need to use: console.log("%c", cssStyles);
notion image

Data Types

  • Every data is of certain type
  • Every value is either an Object or a Primitive in JS
  • There are 7 primitive data types:
      1. number: Floating point numbers, used for decimals and integers
      1. string: Sequence of characters
      1. boolean: Logical type, either true or false
      1. undefined: Value not yet defined
      1. null: Explicit empty value
      1. Symbol (ES2015): Value that is unique and can’t be changed
      1. BigInt (ES2020): Large integers that the Number type can hold. Used for numbers beyond Number.MAX_SAFE_INTEGER
  • JS supports dynamic typing, we don’t have to define the type of data at declaration
  • Value has type, not the variable. This allows us to store data of any type in a variable
  • Comments are used to comment unwanted code
      1. \\ Single Line
      1. \* Multi line *\
  • The typeof operator to get the type of the value
  • The typeof null is object (legacy bug from JS's early design).

Declaring Variables

  • let supports reassigning/mutating the variable
  • const is not meant to be changed and only assigned once
  • Always use const by default and only use let if needed mutation
  • The var is the legacy way of defining variables
  • let and const are block scoped whereas var is function scoped

Operators

  • Operators allows us to transform or combine values
  • For logging multiple values console.log(first, second)
  • The + operator concatenates strings
  • The augmented assignment operators (*=, /=, +=, -=)
  • Comparison operator (> greater than or less than <) or equal ( or )
  • JS has a very well defined operator precedence rules, we can use brackets to prioritize the order

Strings & Template Literals

  • String is a sequence of characters
  • When adding strings we call it concatenation
  • They can be created using single, double quotes or backticks `
const firstName = 'Jonas'; const job = "Teacher"; const birthYear = 1991; const year = 2037; // Template Literals // ${} expression to interpolate const jonas = `I'm ${firstName}, a ${year - birthYear} years old ${job}.`; // Multi Line support console.log(`I'm a multi line console log statement.`)

Methods

.length .trim() .toUpperCase() .toLowerCase() .charAt() // -1 vs .at() Supports Negative Values .indexOf() .lastIndexOf() .slice() // start:end .substring() .replace() .includes() .startsWith() .endsWith() .repeat() // Repeats .split(seperator) // Creates array

Numbers

Only one type for numbers
Math.PI; // 3.141592653589793 Math.abs(-5); // 5 (Absolute Value) Math.ceil(4.2); // 5 up (ceiling) Math.floor(4.9); // 4 down (floor) Math.round(4.5); // 5 Math.max(1, 2, 3); // 3 Math.min(1, 2, 3); // 1 Math.pow(2, 3); // 8 Math.sqrt(16); // 4 Math.random(); // random number between 0 and 1 Math.trunc(4.9); // 4 remove parseInt() or parseFloat() // Handling Precision (0.1 + 0.2).toFixed(2); // "0.30” Converting types let str = "5"; let num = 2; console.log(+str + num); // 7 (string converted to number)

Taking Decisions

  • The if/else control structure
  • Variables declared using var don’t respect block scope
const age = 19; const isOldEnough = age >= 18; if(isOldEnough) { console.log("Can have driving license."); } else { const yearsLeft = 18 - age; console.log(`Wait for ${yearsLeft} years.`); }
  • Variables defined inside the code blocks are not accessible outside
  • This is not applicable for var, as it’s only function scope
if(true){ let century = 10; console.log(century); // 10 } console.log(century); // ReferenceError

Guard Clauses

notion image
  • Instead of nested if-else conditionals we can check for wrong cases
function getPayAmount() { if (isDead) return deadAmount(); if (isSeparated) return separatedAmount(); if (isRetired) return retiredAmount(); return normalPayAmount(); }

Type Conversion & Coercion

  • Type conversion is manual (explicit) and coercion is automatic (implicit)
// Converting a string to a number const inputYear = '1981'; Number(inputYear); // 1981 Number("Hello"); // NaN (Not a Number: is also of number type) // Converting into a string String(23); // "23"
  • Type coercion happens when doing some operation
console.log('I am ' + 23 + ' years old.'); // Number is coerced to string

Truthy & Falsy Values

  • There’re only 5 falsy values in JavaScript
  • Falsy values: 0, undefined, NaN, "", null, false, rest everything else is truthy.
const money = 0; money ? "Spend wisely" : "Start earning"; // Outputs: Start earning

Equality Operators

  • To check for values equality
  • The loose equality == only checks for the value and coerces the type
  • The strict equality === checks for value as well as the type (always use this)
  • The different operator checks if value is not equal !==
  • We can request some input from the user using the prompt() browser function

Boolean Logic

  • Boolean logic is a branch of computer science that uses true and false values to solve complex problems
  • For which it uses multiple logical operators: &&, II and !
  • For && to be true all cases must match
  • For II to be true only one case needs to match
  • The ! operator has a higher precedence over all the other operators
notion image

Short Circuit

Short-circuiting is a behaviour exhibited by logical operators (&&||) where the evaluation of the second operand is skipped if the outcome can be determined by evaluating the first operand alone.
notion image
The && operator returns the first falsy operand, or the last truthy operand if all operands are truthy.
const value = 0; const result = value && 'Truthy Value'; console.log(result); // Output: 0
The || operator returns the first truthy operand, or the last falsy operand if all operands are falsy.
const name = ''; const displayName = name || 'Guest'; console.log(displayName); // Output: Guest

Logical Operators

const hasLicense = true; const hasGoodVision = true; const isTired = true; if(hasLicense && hasGoodVision && !isTired) { console.log("Sarah is able to drive"); } else { console.log("Someone else should drive"); // will be logged }

The switch Statement

  • Alternative to writing multiple if-else statements
  • Multiple case can be combined together
  • The break keyword is required and the default is recommended to add at end
let weekDay = 11; switch(weekDay) { case 1: case 2: case 3: case 4: case 5: console.log('Working Day'); break; case 6: case 7: console.log('Weekend!'); break; default: console.log('Out of range!'); }

The Conditional Operator (Ternary)

  • Ternary means three (operands)
  • Can be used inside template literal as this is an expression
const age = 18; age >= 18 ? console.log('Can Vote') : console.log("Can't Vote");

Statements & Expressions

  • Expression is a piece of code that produces a value
  • Statement is some code block that runs but doesn’t produce a value, like switch statement and if-else statement

😮