JS - let, const, var, primitive data types, type conversion, Operations, Comparison

make sure you have installed node to run js files locally in terminal.
First print statement
simply use console.log() to get a output on the terminal.
console.log('My age is',25);
Output
My age is 25
The comma inside the console.log() automatically adds a single space between the arguments.
In case you don’t want the space you can use concatenation with + operator.
console.log('My age is'+25);
Output
My age is25
const vs let
Values (at least the reference of the value) assigned to const cannot be changed but it can be in let.
const accountId = 232323;
let accountEmail = "gambit@gmail.com";
var accountPassword = "123456789";
accountCity = "Moscow"
let accountState;
console.log(accountEmail, accountPassword, accountCity);
// accountId = 2; // not allowed as it's a const
accountEmail = "abc@yahoo.com";
accountPassword = "1211212";
accountCity = "Bangaluru";
console.table([accountId, accountEmail, accountPassword, accountCity, accountState])
Output
gambit@gmail.com 123456789 Moscow
┌─────────┬─────────────────┐
│ (index) │ Values │
├─────────┼─────────────────┤
│ 0 │ 232323 │
│ 1 │ 'abc@yahoo.com' │
│ 2 │ '1211212' │
│ 3 │ 'Bangaluru' │
│ 4 │ undefined │
└─────────┴─────────────────┘
Pointers:
the
accountCityvariable not declared using let, var or const but was initialized with a value, JS allows it but it is bad practice to do so.the values with ““ wrapped are strings (text basically) and without them are numbers in this example
Use
console.table()to represent data in a tabular fashion with “index” (starting from 0) and “values”console.table()also works great with array of objects.Never use var in modern javascript, it's good to know it’s existence as it’s written in older code bases, var is function-scoped and let is block-scoped(eg: inside if statements or for loops)
any variable that isn’t defined or initialized has
undefinedas the default value.
console.warn and console.error
console.warn('Toxic code ahead!!')
console.error('error404')
“use strict”;
Writing this as the first line in the JS file tells it to enable “strict mode”, a restricted and safer variant of the language.
This mode enforces stricter parsing and error handling, changing previously silent errors into explicit errors and disallowing certain "unsafe" or poorly-thought-out features.
Datatypes Overview
We visit any website all we see is data, we interact with data, we send and receive data, it’s the bed rock of any development not just web dev.
Primitive: these are the foundational data types (7 total).
number → includes integers, floats(decimal places), negative numbers, ranges from +-(2ˆ53-1)
let a = 50; console.log(typeof a) // 'number'bigint → unlike size limit of number, BigInt can represent integer of any size, limited only by the host system’s available memory.
let a = 12345678901234567890n; console.log(typeof a) // 'bigint'string → stores text
let a = "Javascript"; console.log(typeof a) // 'string'boolean → stores either true or false.
let singleForLife = true; console.log(typeof singleForLife) // 'boolean'null → It is the data type and also standalone value. It’s used to show that the variable is intentionally empty.
let a = null; console.log(typeof a) // 'object'undefined → when the value isn’t defined yet.
let a;
console.log(a, typeof a) // undefined undefined
- symbol → used mostly for uniqueness of values.
let a = Symbol("blue");
console.log(a, typeof a) // Symbol(blue) symbol
Pointers:
typeof is a operator that returns the type of the variable in a string form.
You can also use typeof as a method,
typeof(a);typeof null;should be null but returns object, this is a widely recognized historical error, just check the value directly if checking for null instead of it’s type.when printing symbols do variable name.toString()
The second category of data types are non-primitive type or reference type or object types, mainly three types
- Object
let myObj = {
name: 'gambit',
followers: 1000
}
console.log(typeof myObj) // object
- Array
Example : heroes = ["batman", "wonder woman", "superman"]
console.log(typeof heroes) // object
- Function
const myFunc = function() {
console.log("hello world")
}
console.log(typeof myFunc) // function
Will discuss them in detail later, just know they exist for now.
Type Conversion Basics
converting to number
For converting one primitive type into another we can use functions like Number(), String(), Boolean(),etc.
let score = "42";
console.log(typeof score)
let scoreInNumber = Number(score)
console.log(scoreInNumber, typeof scoreInNumber)
Output
string
42 number
Now what if we keep something in score that isn’t convertible to number.
let score = "42abc";
console.log(typeof score)
let scoreInNumber = Number(score)
console.log(scoreInNumber, typeof scoreInNumber)
Output
string
NaN number
What if the value of score is null.
let score = null;
console.log(typeof score)
let scoreInNumber = Number(score)
console.log(scoreInNumber, typeof scoreInNumber)
Output
object
0 number
for true and false.
let score = true;
console.log(typeof score)
let scoreInNumber = Number(score)
console.log(scoreInNumber, typeof scoreInNumber)
Output
boolean
1 number
for false it will be 0.
Pointers:
“42” => 42
“42abc” => NaN, which means Not a Number, JS tried to convert it but failed (won’t throw error tho), NaN is of the number type
null => 0
true => 1
false => 0
converting to boolean
let’s try some examples
let isLoggedIn = 1;
let booleanIsLoggedIn = Boolean(isLoggedIn)
console.log(booleanIsLoggedIn)
Output
true
Let’s try with an empty string
let isLoggedIn = "";
let booleanIsLoggedIn = Boolean(isLoggedIn)
console.log(booleanIsLoggedIn)
Output
false
In Javascript truthy values convert to true and falsy values convert to false.
List of falsy values
false
0
-0
““ or ‘‘
null
undefined
NaN
Any other value is truth and returns true.
converting to string
let someNumber = 33;
someNumber = String(someNumber)
console.log(typeof someNumber)
Output
string
Operations Basics
negative number
let value = 5
let negValue = -value
console.log(negValue)
Output
-5
Math Operations
console.log(3+2) // plus
console.log(3-2) // minus
console.log(3*2) // multiply
console.log(3**2) // power
console.log(3/2) // division
console.log(3%2) // remainder
Output
5
1
6
9
1.5
1
String Operations and Operator Precedence
In Javascript the + operator works with both numbers and string. It performs type coercion (JS changes type of the output based on the operands, between string and number string always wins)
‘5’ + 2 = ‘52'
Another simple rule to follow brackets have the highest precedence (it’s cleaner to use them when trying to describe which operation you want to be done first) then comes * and / then comes + and -.
In the same level of precedence go from left to right.
console.log('10'+5+2) // 1052
console.log('10'+5*2) //1010
console.log(10+20+'30') // 3030
console.log('10'-5) // 5
console.log('10'*'2') // 20
console.log('10'+(6+6)) // 1012
Since - and * operators are not defined for JS, it is type coerced into number to perform the operation.
We can also type coerce any type into number using plus but it’s not clean code (good to know)
| Expression | Result | Why? |
|---|---|---|
+true |
1 | Boolean true maps to 1. |
+false |
0 | Boolean false maps to 0. |
+"" |
0 | Empty strings map to 0. |
+" " |
0 | Whitespace strings also map to 0. |
+null |
0 | null is treated as empty/zero. |
+undefined |
NaN | Undefined cannot be turned into a valid number. |
Prefix and Postfix
Both essentially increase the value of the variable by 1.
a = a + 1;
Postfix (a++): Returns the value before incrementing. (Use, then change)
Prefix (++a): Returns the value after incrementing. (Change, then use)
Example 1:
let x = 5;
let y = x++;
console.log(x, y); // 6 5
Example 2:
let a = 1;
let b = ++a + a++;
console.log(a, b); // 3 4
Step-by-Step Logic:
++a:abecomes 2, returns 2.Now the expression is
2 + a++. At this moment,ais 2.a++: Returns the current value 2, thenabecomes 3.2 + 2 = 4. Sobis 4 andais 3.
Comparison
Let’s start with the basics that are self explanatory.
console.log(2 > 1) // true
console.log(2 >= 1) // true
console.log(2 < 1) // false
console.log(2 == 1) // false
console.log(2 != 1) // true
console.log(8 <= 8) // true
If both are strings, we go lexicographically (letter by letter which ever has higher letter first is higher overall), if they are same longer one is bigger.
“2” < “12”→ false, as 2 is bigger than 1 and both are strings“zebra” > “apple”→ true (z > a)“Apple” > “apple”→ false (‘a’ ASCII code is 97, ‘A’ has 65)“2” < 12→ true (the string “2” becomes the number 2)true > 0→ true (1 > 0)null >= 0→ true ( null becomes 0)
We basically convert everything to number and then compare other than when both are strings.
Equality Operator (==)
== also known as loose equality. If the types aren't the same JS tries to convert it to same type.
5 == '5' // true, string gets converted to number
1 == true , boolean gets converted to number
0 == false, true
null == undefined // true , null is only loosely equal to itself and undefined
null == 0 // false, huh but null >= 0 is true, yes this is quirk of js
Strict Equality (=== and !==)
This doesn't perform type coercion, it checks for both type and value.
The above example will all give false for ===.
Stack and heap memory
Primitive data types are store in stack and non-primitive (reference type) are stored in heap.
in stack when you copy the variable into another, a copy is stored but in heap the address or reference is passed, hence if you make changes to the copy it affects the original and it doesn't in stack memory original stays intact.
let a = 23
let b = a
b = 42
console.log(a) // 23
let arr1 = [1]
let arr2 = arr1
// arr2 = [1,2] , this changes existing reference from arr1 to [1,2] deosnt change it.
arr2.push(2)
console.log(arr1) // [ 1, 2 ]
Hoisting in const and let VS var
In case of let, it is hoisted (JS knows there is a variable starting as undefined) but throws error if you try to use it before declaring it.
Also all the lines above it's declaration from start of block scope to declaration where it isn't supposed to be used is TDZ (Temporal Dead Zone)
console.log(a)
let a = 5
++a
console.log(a)
Output
ReferenceError: Cannot access 'a' before initialization
but if we replace let with var
console.log(a)
var a = 5
++a
console.log(a)
Output
undefined
6
Comments
comments are your way of leaving "sticky notes" for yourself or other developers. They do not affect the code in any way.
- Single-Line Comment (
//)
Example:
const ethPrice = 3500; // Current price from Oracles // checkLiquidity(); // Temporarily disabled for debugging
- Multi-Line Comments(
/* ... */)
Example:
/* RISK MANAGEMENT PROTOCOL: This function calculates the maximum drawdown allowed before the circuit breaker triggers. */
- JSDoc Comments
Modern code editors (like VS Code) read these to give you helpful "hover" tooltips.
/**
* Calculates the total tiffin cost.
* @param {number} days - Total delivery days
* @param {number} rate - Daily price in USD
* @returns {number} Total calculated cost.
*/
function calculateTotal(days, rate) {
return days * rate;
}
There are a lot of types of @ used in JSDocs like param, returns, throws, description, example, deprecated, etc..




