Hello WorldRunning in SourcesIntroductionLinkingAsync vs DeferSingle threadedGarbage collectedValues & VariablesConventionsThe ConsoleConsole GroupConsole StylesData TypesDeclaring VariablesOperatorsStrings & Template LiteralsMethodsNumbersTaking DecisionsGuard ClausesType Conversion & CoercionTruthy & Falsy ValuesEquality OperatorsBoolean LogicShort CircuitLogical OperatorsThe switch StatementThe Conditional Operator (Ternary)Statements & Expressions
Hello World
- Open console in developer tools using
ctrl+shift+J
- This is the
replenvironment 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
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:
- First the script is downloaded
- Then it will be executed immediately
There are three ways of adding scripts:
- Normal mode
- Using
asynckeyword
- Using
deferkeyword
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.
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.
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.
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 underscoreanother_nameis 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
neworfunction)
- 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 environmentpresent in the browser’s developer tools used for debugging purposes
- The
consoleobject in JS allows us to print to the developer tool’s Console tab
- The
console.clear()clears up the console
Console Group
We can also show as a tooltip using
console.group() and console.groupEnd()Console Styles
We can also give styles for this we need to use:
console.log("%c", cssStyles); 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:
number: Floating point numbers, used for decimals and integersstring: Sequence of charactersboolean: Logical type, eithertrueorfalseundefined: Value not yet definednull: Explicit empty valueSymbol(ES2015): Value that is unique and can’t be changedBigInt(ES2020): Large integers that the Number type can hold. Used for numbers beyondNumber.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
\\ Single Line\* Multi line *\
- The
typeofoperator to get the type of the value
- The
typeof nullis object (legacy bug from JS's early design).
Declaring Variables
letsupports reassigning/mutating the variable
constis not meant to be changed and only assigned once
- Always use
constby default and only useletif needed mutation
- The
varis the legacy way of defining variables
letandconstare block scoped whereasvaris 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/elsecontrol 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
- 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
trueandfalsevalues to solve complex problems
- For which it uses multiple logical operators:
&&,IIand!
- For
&&to be true all cases must match
- For
IIto be true only one case needs to match
- The
!operator has a higher precedence over all the other operators
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.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-elsestatements
- Multiple
casecan be combined together
- The
breakkeyword is required and thedefaultis 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
😮