1.
datatypes in Javascript
n JavaScript, data types describe the kind of value a variable can hold. JavaScript has two main categories:
πΉ 1. Primitive Data Types
Primitive types are simple and immutable.
β 1. Number
Represents both integers and decimals.
let age = 21;
let price = 99.5;
β 2. String
Represents text.
let name = "Priya";
β 3. Boolean
Represents true/false values.
let isStudent = true;
β 4. Undefined
A variable declared but not assigned a value.
let x;
console.log(x); // undefined
β 5. Null
Represents an empty or unknown value.
let data = null;
β 6. BigInt
Used for very large numbers beyond Number limit.
let big = 123456789012345678901234567890n;
β 7. Symbol
Used for unique values (often in objects).
let id = Symbol("id");
πΉ 2. Non-Primitive (Reference) Data Types
These store collections or complex data.
β 1. Object
Keyβvalue pairs.
let student = {
name: "Priya",
age: 21
};
β 2. Array
Ordered list of items (objects but special type).
let colors = ["red", "blue", "green"];
β 3. Function
Functions are also objects in JavaScript.
function greet() {
console.log("Hello!");
}
2.
Types Of Variables in JavaScript
πΉ 1. var
β Can be redeclared
β Can be updated (reassigned)
β Has function scope (NOT block scope)
β var is old β not recommended now
Example:
var x = 10;
var x = 20; // allowed
x = 30; // allowed
πΉ 2. let
β Cannot be redeclared in the same block
β Can be updated (reassigned)
β Has block scope { }
β Preferred for normal variable usage
Example:
let a = 10;
// let a = 20; β not allowed
a = 20; // β allowed
πΉ 3. const
β Cannot be redeclared
β Cannot be reassigned
β Has block scope
β Used for values that should NOT change
Example:
const PI = 3.14;
// PI = 3.15; β not allowed
3.Feature Dynamically Typed (JavaScript) Statically Typed (TypeScript, Java)
Type checking Runtime Compile-time
Flexibility High Low
Errors caught While running Before running
Requires type declaration No Yes
4.
Arithmetic Operators
Used for mathematical calculations.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
** Exponent
++ Increment
-- Decrement
β Example:
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333
console.log(a % b); // 1
console.log(a ** b); // 1000
console.log(++a); // 11
console.log(--b); // 2
β Assignment Operators
Used to assign values.
Operator Meaning
= Assign value
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
β Example:
let x = 10;
x += 5; // 15
x -= 3; // 12
x *= 2; // 24
x /= 4; // 6
x %= 5; // 1
β Comparison Operators
Used to compare values β returns true/false.
Operator Meaning
== Equal to (value only)
=== Strict equal (value + type)
!= Not equal
!== Strict not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
β Example:
5 == "5"; // true
5 === "5"; // false
10 != 8; // true
10 !== "10"; // true
10 > 5; // true
5 < 2; // false
10 >= 10; // true
4 <= 5; // true
β
Logical Operators
Operator Meaning Example
&& AND β true only if ALL are true true && false β false
! NOT β reverses boolean !true β false
β Example:
true && false; // false
true || false; // true
!true; // false
β Bitwise Operators
Work on binary numbers.
Operator Meaning
& AND
^ XOR
~ NOT
<< Left shift
Right shift
Unsigned right shift
β Example:
5 & 1; // 1
5 | 1; // 5
5 ^ 1; // 4
~5; // -6
5 << 1; // 10
5 >> 1; // 2
β Ternary Operator
Short form of if-else.
Syntax:
condition ? valueIfTrue : valueIfFalse
β Example:
let age = 20;
let result = age >= 18 ? "Adult" : "Minor";
console.log(result); // Adult
5.
IF Statement in JavaScript
β€ What is it?
The if statement is used to run a block of code only if a condition is true.
β Syntax:
if (condition) {
// code to run
}
β Example 1: Basic if
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote");
}
Output:
You are eligible to vote
IFβELSE Statement
If the condition is true β one block runs
If false β another block runs
β Example 2: ifβelse
let mark = 45;
if (mark >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Output:
Fail
ELSE IF Statement
Used when there are multiple conditions.
β Example 3: ifβelse ifβelse
let temp = 32;
if (temp > 35) {
console.log("Hot");
} else if (temp > 20) {
console.log("Warm");
} else {
console.log("Cold");
}
Output:
Warm
β Nested IF Statement
A nested if means:
π An if statement inside another if.
β€ Used when one condition depends on another.
β Example 4: Nested if
let username = "Priya";
let password = "12345";
if (username === "Priya") { // Outer if
if (password === "12345") { // Nested (inner) if
console.log("Login Successful");
} else {
console.log("Incorrect Password");
}
} else {
console.log("User not found");
}
Output:
Login Successful
Conditional (Ternary) Operator
The ternary operator is a shorthand way of writing an ifβ¦else statement.
β Syntax
condition ? value_if_true : value_if_false;
β Example 1: Check age
let age = 20;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // Output: Adult
β Example 2: Even or Odd
let num = 7;
let type = (num % 2 === 0) ? "Even" : "Odd";
console.log(type); // Output: Odd
β Ternary operator with more than one condition
You can nest ternary operators (but not recommended if too long):
let marks = 85;
let grade = (marks >= 90) ? "A+" :
(marks >= 75) ? "A" :
(marks >= 50) ? "B" : "Fail";
console.log(grade);
// Output: A
β switch Statement
The switch statement checks one value against multiple possible cases.
β Syntax
switch(value) {
case option1:
// code
break;
case option2:
// code
break;
default:
// code if no case matches
}
β Example: Day of the Week
let day = 3;
switch(day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Invalid day");
}
Output:
Wednesday
β Example: Calculator Using Switch
let a = 10;
let b = 5;
let operator = "+";
switch(operator) {
case "+":
console.log(a + b);
break;
case "-":
console.log(a - b);
break;
case "*":
console.log(a * b);
break;
case "/":
console.log(a / b);
break;
default:
console.log("Invalid operator");
}
Output:
15
The break Keyword
The break statement stops the execution of a switch case.
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apple selected");
break; // stops here
case "banana":
console.log("Banana selected");
break;
case "orange":
console.log("Orange selected");
break;
}
Output:
Apple selected
The default Keyword
default runs when no cases match.
β Example:
let color = "purple";
switch(color) {
case "red":
console.log("Red Color");
break;
case "blue":
console.log("Blue Color");
break;
default:
console.log("No matching color found");
}
Output:
No matching color found
Strict Comparison (=== and !==)
Strict comparison checks both value AND data type.
β === β Strict Equal
β !== β Strict Not Equal
π Strict Comparison Examples
β Example 1: === Checks value + type
console.log(5 === 5); // true
console.log(5 === "5"); // false (number vs string)
β Example 2: !== Checks value + type
console.log(10 !== 10); // false
console.log(10 !== "10"); // true (type different)
π₯ Strict vs Loose Comparison
Loose comparison (==) only checks value, not type.
console.log(5 == "5"); // true (only value checked)
console.log(5 === "5"); // false (type different)
β Full Combined Example
let value = "10";
switch(value) {
case 10: // number
console.log("Number 10");
break;
case "10": // string
console.log("String 10");
break;
default:
console.log("No match");
}
// Strict comparison:
console.log(value === 10); // false
console.log(value === "10"); // true
console.log(value !== 10); // true
Output:
String 10
false
true
true
Boolean in JavaScript
A Boolean represents true or false.
β Example:
let isLoggedIn = true;
let isAdult = false;
console.log(isLoggedIn); // true
console.log(isAdult); // false
Booleans as Objects
You can create a Boolean object using new Boolean().
β οΈ Avoid using Boolean objects β they behave differently.
β Example:
let x = false; // boolean primitive
let y = new Boolean(false); // boolean object
console.log(typeof x); // "boolean"
console.log(typeof y); // "object"
for Loop
Used when you know how many times to run the loop.
β Example:
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}
Output:
1
2
3
4
5
while Loop
Used when you want to run the loop until a condition becomes false.
β Example:
let i = 1;
while (i <= 5) {
console.log("Count:", i);
i++;
}
forβ¦in Loop
Used to iterate over object properties (keys).
β Example:
let person = {
name: "Priya",
age: 21,
city: "Chennai"
};
for (let key in person) {
console.log(key, ":", person[key]);
}
Output:
name : Priya
age : 21
city : Chennai
forβ¦of Loop
Used to iterate over values of arrays, strings, etc.
β Example (Array):
let numbers = [10, 20, 30];
for (let value of numbers) {
console.log(value);
}
Output:
10
20
30
Logical AND (&&)
β Works when both conditions must be TRUE
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
console.log("You can enter.");
}
Logical OR (||)
β Works when at least one condition is TRUE
Example (conditions):
let isAdmin = false;
let isUser = true;
if (isAdmin || isUser) {
console.log("Access granted.");
}
. Logical NOT (!)
β Converts truthy β false
β Converts falsy β true
β Example:
console.log(!true); // false
console.log(!false); // true
console.log(!0); // true (0 is falsy)
console.log(!"Priya"); // false (string is truthy)
Nullish Coalescing Operator (??)
β Returns the right-side value only if left side is null or undefined
β Does NOT treat 0, "", false as null
β Examples:
let a = null;
console.log(a ?? "Default"); // "Default"
let b = undefined;
console.log(b ?? "Value Missing"); // "Value Missing"
let c = 0;
console.log(c ?? 100); // 0 (because 0 is NOT null/undefined)
let d = "";
console.log(d ?? "Empty"); // "" (string is not null/undefined)
JavaScript Loops
Loops allow you to repeat a block of code multiple times.
Common Loops in JS:
for
while
do...while
for...in
for...of
Loop Scope
A variable declared inside a loop (with let or const) is accessible only inside that loop block.
Example (var leaks outside):
for (var i = 1; i <= 3; i++) {
}
console.log(i); // β i is accessible (var is not block scoped)
The While Loop
Runs as long as the condition is TRUE.
β Example:
let n = 1;
while (n <= 5) {
console.log("While Loop:", n);
n++;
}
The Doβ¦While Loop
β Runs the code at least once, even if the condition is false.
β Condition is checked after the loop body.
β Example:
let x = 1;
do {
console.log("Do While Loop:", x);
x++;
} while (x <= 5);
The For Loop
Use a for loop when you know how many times you want to repeat something.
β Syntax:
for (initialization; condition; increment) {
// code block
}
β Example:
for (let i = 1; i <= 5; i++) {
console.log("For Loop:", i);
}
Output:
1
2
3
4
5
Comparing For and While Loops
Feature For Loop While Loop
Best Used When Number of iterations is known Number of iterations unknown
Structure All parts (init, condition, increment) in one line Parts written separately
Readability More compact More flexible
Risk Less chance of infinite loop More chance of forgetting increment (infinite loop)
Break in Loops
The break statement stops the loop immediately.
β Example β break inside a for loop
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // stops the loop when i = 3
}
console.log(i);
}
Output:
1
2
Break in a Switch Statement
break is used to stop execution of other cases.
β Example:
let color = "blue";
switch (color) {
case "red":
console.log("Red");
break;
case "blue":
console.log("Blue");
break; // stops here
case "green":
console.log("Green");
break;
default:
console.log("No match");
}
Output:
Blue
JavaScript Labels
A label is a name placed before a block of code.
It is used with break to exit from nested loops.
β Syntax:
labelName: {
// statements
}
β Best Use: Breaking out of nested loops
β Example β break with label
outerLoop: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
break outerLoop; // exits both loops
}
console.log(i, j);
}
}
Output:
1 1
1 2
1 3
2 1
JavaScript Continue
continue skips the current iteration and moves to the next iteration of the loop.
β Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skip 3
}
console.log(i);
}
Output:
1
2
4
5
The number 3 is skipped.
Continue to Label (Labeled Continue)
continue labelName jumps directly to the next iteration of the labeled loop, skipping everything below it.
β Example (Skip inner loop and continue outer loop)
outerLoop: for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (j === 2) {
continue outerLoop;
// skips inner loop and jumps to next 'i'
}
console.log(i, j);
}
}
Output:
1 1
2 1
3 1
JavaScript Strings
A string is text inside quotes:
" " (double quotes)
' ' (single quotes)
(backticks β template strings)
β Example:
let name = "Priya";
let city = 'Chennai';
console.log(name, city);
String Length
.length returns the number of characters.
β Example:
let text = "JavaScript";
console.log(text.length); // 10
Escape Characters
Used to insert special characters inside strings.
Escape Meaning
\" Double quote
\' Single quote
\ Backslash
\n New line
\t Tab
\r Carriage return
β Examples:
let str1 = "She said, \"Hello!\"";
let str2 = 'It\'s a nice day';
let str3 = "Line1\nLine2"; // new line
let str4 = "Tab:\tSpace";
output
console.log(str1);
console.log(str2);
console.log(str3);
console.log(str4);
JavaScript Strings as Objects
You can create a string object using new String().
β Example:
let str1 = "Hello"; // string primitive
let str2 = new String("Hello"); // string object
console.log(typeof str1); // "string"
console.log(typeof str2); // "object"
String Methods
Javascript strings are primitive and immutable: All string methods produce a new string without altering the original string.
Top comments (1)
You organized everything so clearly that it makes learning JavaScript much easier