DEV Community

PRIYA K
PRIYA K

Posted on • Edited on

javascript questions

1.

datatypes in Javascript

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.

Number
Represents both integers and decimals.
eg.

let age = 21;
let price = 99.5;
Enter fullscreen mode Exit fullscreen mode

String
Represents text.
eg.

let name = "Priya";

Enter fullscreen mode Exit fullscreen mode

Boolean
Represents true/false values.
eg

let isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Undefined
A variable declared but not assigned a value.
eg

let x;
console.log(x); // undefined
Enter fullscreen mode Exit fullscreen mode

Null
Represents an empty or unknown value.
eg

let data = null;
Enter fullscreen mode Exit fullscreen mode

BigInt
Used for very large numbers beyond Number limit.
eg

let big = 123456789012345678901234567890n;
Enter fullscreen mode Exit fullscreen mode

Symbol
Used for unique values (often in objects).
eg

let id = Symbol("id");
Enter fullscreen mode Exit fullscreen mode

🔹 2. Non-Primitive (Reference) Data Types
These store collections or complex data.

Object
Key–value pairs.
eg

let student = {
  name: "Priya",
  age: 21
};
Enter fullscreen mode Exit fullscreen mode

Array
Ordered list of items (objects but special type).
eg

let colors = ["red", "blue", "green"];
Enter fullscreen mode Exit fullscreen mode

Function
Functions are also objects in JavaScript.
eg

function greet() {
  console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

2.

Types Of Variables in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Bitwise Operators
Work on binary numbers.
Operator Meaning
& AND

^ XOR
~ NOT
<< Left shift( a * 2^ b)

Right shift( a / 2^ b)

Unsigned right shift



Example:
5 & 1;  // 1
5 | 1;  // 5
5 ^ 1;  // 4
~5;     // -6
5 << 1; // 10
5 >> 1; // 2
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

5.

IF Statement in JavaScript
The if statement is used to run a block of code only if a condition is true.
Syntax:

if (condition) {
    // code to run
}
Enter fullscreen mode Exit fullscreen mode

Example 1: Basic if

let age = 20;

if (age >= 18) {
    console.log("You are eligible to vote");
}
Enter fullscreen mode Exit fullscreen mode

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");
}

Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

Output:

✅ 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");
}
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

✔ 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");
}

Enter fullscreen mode Exit fullscreen mode

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");
}

Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

}

// 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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

}

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);
}
Enter fullscreen mode Exit fullscreen mode

}

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);
}
Enter fullscreen mode Exit fullscreen mode

}

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.

  1. String length

Returns the number of characters in a string.

let text = "Hello World";
console.log(text.length); // 11

  1. String charAt()

Returns the character at a specified index.

let text = "Hello";
console.log(text.charAt(1)); // e

  1. String charCodeAt()

Returns UTF-16 code (0–65535) of the character at an index.

let text = "A";
console.log(text.charCodeAt(0)); // 65

  1. String codePointAt()

Returns Unicode code point (works for emojis also).

let emoji = "😀";
console.log(emoji.codePointAt(0)); // 128512

  1. String concat()

Joins two or more strings.

let a = "Hello";
let b = "World";
console.log(a.concat(" ", b)); // Hello World

  1. String at()

Returns the character at a position (supports negative index).

let text = "Hello";
console.log(text.at(-1)); // o

  1. String

Access a character like an array.

let text = "Hello";
console.log(text[0]); // H

  1. String slice()

Extracts part of a string.

let text = "JavaScript";
console.log(text.slice(0, 4)); // Java
console.log(text.slice(-6)); // Script

  1. String substring()

Similar to slice(), but does NOT support negative values.

let text = "JavaScript";
console.log(text.substring(4, 10)); // Script

  1. String substr() (❌ Deprecated but still works)

Extracts a substring with start index and length.

let text = "JavaScript";
console.log(text.substr(4, 6)); // Script

  1. String toUpperCase()

Converts to uppercase.

let text = "hello";
console.log(text.toUpperCase()); // HELLO

  1. String toLowerCase()

Converts to lowercase.

let text = "HELLO";
console.log(text.toLowerCase()); // hello

  1. String isWellFormed()

Checks if string contains only valid Unicode characters.

console.log("hello".isWellFormed()); // true

  1. String toWellFormed()

Replaces invalid Unicode with valid ones.

console.log("\uD800".toWellFormed()); // �

  1. String trim()

Removes whitespace from both ends.

let text = " hi ";
console.log(text.trim()); // "hi"

  1. String trimStart() / trimLeft()

Removes whitespace from start.

let text = " Hi";
console.log(text.trimStart()); // "Hi"

  1. String trimEnd() / trimRight()

Removes whitespace from end.

let text = "Hi ";
console.log(text.trimEnd()); // "Hi"

  1. String padStart()

Pads a string at the beginning.

let num = "5";
console.log(num.padStart(4, "0")); // 0005

  1. String padEnd()

Pads a string at the end.

let num = "5";
console.log(num.padEnd(4, "")); // 5**

  1. String repeat()

Repeats the string.

console.log("ha".repeat(3)); // hahaha

  1. String replace()

Replaces first occurrence.

let text = "I love JavaScript";
console.log(text.replace("JavaScript", "Python"));
// I love Python

  1. String replaceAll()

Replaces all occurrences.

let text = "apple apple apple";
console.log(text.replaceAll("apple", "orange"));
// orange orange orange

  1. String split()

Splits a string into an array.

let text = "a,b,c";
console.log(text.split(",")); // ["a", "b", "c"]

JavaScript String Search Methods (with Examples)

These methods help you find text inside a string.

✅ 1. String indexOf()

Returns the first index of a substring.
Returns -1 if not found.

let text = "Hello JavaScript";

console.log(text.indexOf("Java")); // 6
console.log(text.indexOf("hello")); // -1 (case-sensitive)

✅ 2. String lastIndexOf()

Returns the last index of a substring.

let text = "Hello JavaScript Java";

console.log(text.lastIndexOf("Java")); // 17

✅ 3. String search()

Searches for a substring or regular expression.

let text = "I love JavaScript";

console.log(text.search("love")); // 2
console.log(text.search(/Java/i)); // 7 (regex, case-insensitive)

✅ 4. String match()

Returns matches of a regex as an array.

let text = "cat, bat, mat";

console.log(text.match(/at/g)); // ["at", "at", "at"]

✅ 5. String matchAll()

Returns all matches including details (iterator).

let text = "cat, bat, mat";

for (let m of text.matchAll(/at/g)) {
console.log(m);
}

Output will be:

["at", index: 1]
["at", index: 6]
["at", index: 11]

✅ 6. String includes()

Checks if a string contains another string.
Returns true/false.

let text = "Hello World";

console.log(text.includes("World")); // true
console.log(text.includes("world")); // false

✅ 7. String startsWith()

Checks if string begins with a substring.

let text = "JavaScript is fun";

console.log(text.startsWith("Java")); // true
console.log(text.startsWith("Script")); // false

✅ 8. String endsWith()

Checks if string ends with a substring.

let text = "Hello World";

console.log(text.endsWith("World")); // true
console.log(text.endsWith("Hello")); // false

JavaScript Number – Basic Methods

In JavaScript, numbers are usually primitive values, but JS automatically treats them as Number objects when you use methods.

let num = 123;

✅ 1. toString()
📌 Definition

Converts a number to a string.

✅ Example
let num = 100;
console.log(num.toString()); // "100"
console.log(typeof num.toString()); // string

👉 You can also convert to different bases:

let n = 15;
console.log(n.toString(2)); // "1111" (binary)
console.log(n.toString(8)); // "17" (octal)
console.log(n.toString(16)); // "f" (hex)

  1. toExponential() 📌 Definition

Returns a number written in exponential (scientific) notation.

✅ Example
let num = 12345;
console.log(num.toExponential()); // "1.2345e+4"

With decimal places:

let n = 9.656;
console.log(n.toExponential(2)); // "9.66e+0"

📌 Mostly used in scientific and large number calculations.

  1. toFixed() 📌 Definition

Formats a number with a fixed number of decimal places.
Returns a string.

✅ Example
let num = 4.56789;
console.log(num.toFixed(2)); // "4.57"
console.log(num.toFixed(0)); // "5"

✅ Very common in currency & billing apps.

  1. toPrecision() 📌 Definition

Formats a number to a specified total number of digits.

✅ Example
let num = 123.456;
console.log(num.toPrecision(4)); // "123.5"
console.log(num.toPrecision(2)); // "1.2e+2"

📌 Includes both integer + decimals.

  1. valueOf() 📌 Definition

Returns the primitive value of a Number object.

✅ Example
let num = new Number(100);

console.log(num.valueOf()); // 100
console.log(typeof num); // object
console.log(typeof num.valueOf()); // number

✅ JavaScript usually calls valueOf() automatically.

JavaScript Number – Static Methods

📌 Important:
Static methods can only be used on Number, not on number variables.

✅ Correct: Number.isInteger(10)

  1. Number.isFinite() 📖 Definition

Checks whether a value is a finite number.
Returns true only for real numbers (not Infinity, -Infinity, or NaN).

✅ Example
console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite("100")); // false

  1. Number.isInteger() 📖 Definition

Checks whether a value is an integer.

✅ Example
console.log(Number.isInteger(10)); // true
console.log(Number.isInteger(10.5)); // false
console.log(Number.isInteger("10")); // false

✅ 3. Number.isNaN()
📖 Definition

Checks whether a value is exactly NaN.
Better and safer than global isNaN().

✅ Example
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(10)); // false
console.log(Number.isNaN("Hello")); // false

  1. Number.isSafeInteger() 📖 Definition

Checks whether a number is a safe integer
(i.e., between −(2⁵³ − 1) and (2⁵³ − 1)).

✅ Example
console.log(Number.isSafeInteger(1000)); // true
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false

📌 Used in banking & large calculations.

  1. Number.parseInt() 📖 Definition

Parses a value and returns an integer.
Ignores decimals.

✅ Example
console.log(Number.parseInt("100")); // 100
console.log(Number.parseInt("100.75")); // 100
console.log(Number.parseInt("10 years")); // 10

  1. Number.parseFloat() 📖 Definition

Parses a value and returns a floating-point number.

✅ Example
console.log(Number.parseFloat("10.55")); // 10.55
console.log(Number.parseFloat("10.55px")); // 10.55
console.log(Number.parseFloat("10")); // 10

JavaScript Number Properties

📌 Important:
Number properties are static, so they are accessed using Number.
✅ Number.MAX_VALUE
❌ num.MAX_VALUE

✅ 1. Number.EPSILON
📖 Definition

The smallest difference between 1 and the next larger floating-point number.

Used to compare decimal numbers safely.

✅ Example
let a = 0.1 + 0.2;
let b = 0.3;

console.log(a === b); // false

console.log(Math.abs(a - b) < Number.EPSILON); // true

✅ 2. Number.MAX_VALUE
📖 Definition

The largest number JavaScript can safely represent.

✅ Example
console.log(Number.MAX_VALUE);
// 1.7976931348623157e+308

console.log(Number.MAX_VALUE * 2); // Infinity

✅ 3. Number.MIN_VALUE
📖 Definition

The smallest positive number greater than 0.

✅ Example
console.log(Number.MIN_VALUE);
// 5e-324

⚠️ Not the most negative number!

✅ 4. Number.MAX_SAFE_INTEGER
📖 Definition

The largest safe integer JavaScript can accurately represent.

✅ Example
console.log(Number.MAX_SAFE_INTEGER);
// 9007199254740991

console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)); // true

✅ 5. Number.MIN_SAFE_INTEGER
📖 Definition

The smallest safe integer JavaScript can represent.

✅ Example
console.log(Number.MIN_SAFE_INTEGER);
// -9007199254740991

✅ 6. Number.POSITIVE_INFINITY
📖 Definition

Represents positive infinity.

✅ Example
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(1 / 0); // Infinity

✅ 7. Number.NEGATIVE_INFINITY
📖 Definition

Represents negative infinity.

✅ Example
console.log(Number.NEGATIVE_INFINITY); // -Infinity
console.log(-1 / 0); // -Infinity

✅ 8. Number.NaN
📖 Definition

Represents Not-a-Number.

✅ Example
console.log(Number.NaN); // NaN
console.log(0 / 0); // NaN
console.log(Number("hello")); // NaN

✅ Check NaN correctly:

console.log(Number.isNaN(Number.NaN)); // true

What are Functions?
Functions are fundamental building blocks in all programming.
Functions are reusable block of code designed to perform a particular task.
Functions are executed when they are "called"

JavaScript Function Syntax
function name( p1, p2, ... ) {
// code to be executed
}

Functions are defined with the function keyword:
followed by the function name
followed by parentheses ( )
followed by brackets { }
The function name follows the naming rules for variables.
Optional parameters are listed inside parentheses: ( p1, p2, ... )
Code to be executed is listed inside curly brackets: { }
Functions can return an optional value back to the caller.

Function Invocation ()
The code inside the function will execute when "something" invokes (calls) the function:
When it is invoked (called) from JavaScript code
When an event occurs (a user clicks a button)
Automatically (self invoked)
The () operator invokes a the function.

Normal (Named) Function
Definition
A normal function is declared using the function keyword and has a name.
Example 1

function greet() {
    console.log("Hello World");
}
greet(); // function call

output
Hello World
Enter fullscreen mode Exit fullscreen mode

Example 2
console.log('outside');
function makeBiryani(){
console.log("biryani");
}
output:
outside

Example 3
console.log('outside');
function makeBiryani(){
console.log("biryani");
}
makeBiryani();
output:
outside
biryani

Function with Parameters
Definition
Parameters allow you to pass values into a function.

Example 1
function add(a, b) {
    console.log(a + b);
}
add(10, 20);
output
30

Example 2
console.log('outside');
        function makeBiryani(rice_container , masala_box){
            console.log("biryani");
            console.log(rice_container);
            console.log(masala_box);
        }
        makeBiryani("SeeragaSamba")
        makeBiryani("Aachi")

output 
outside
biryani
seeragasamba
undefined
outside
biryani
Aachi
undefined

Example 3
console.log('outside');
        function makeBiryani(rice_container , masala_box){
            console.log("biryani");
            console.log(rice_container);
            console.log(masala_box);
        }
        makeBiryani("SeeragaSamba")

output
outside
biryani
seeragasamba
undefined

Example 4
console.log("outside")
        function makeBiryani(rice_container , masala_box){
            console.log("biryani")
            console.log(rice_container)
            console.log(masala_box)
        }
        makeBiryani("SeeragaSamba","Aachi")

output
outside
biryani
seeragasamba
Aachi

Example 5
console.log("outside")
        function makeBiryani(rice_container , masala_box){
            console.log("biryani")           
        }
        makeBiryani("SeeragaSamba","Aachi")
output
outside
biryani

Example 6
Enter fullscreen mode Exit fullscreen mode

Function with Return Value
Definition
A function can return a value using the return keyword.

Example
function multiply(x, y) {
    return x * y;
}
let result = multiply(5, 4);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

What is Scope in JavaScript?
Scope defines where a variable can be accessed in a program.
There are mainly two important scopes:
Global Scope
Local Scope
first priority is given to local scope.

Global Scope
Definition
A variable declared outside any function or block is in the global scope.
It can be accessed from anywhere in the program.
Lifetime: Entire program
Memory: Occupies memory longer

Example
let message = "Hello World"; // Global variable
function showMessage() {
console.log(message);
}
showMessage();
console.log(message);

Output
Hello World
Hello World
//Accessible inside and outside functions

Local Scope
Definition
A variable declared inside a function or block is in the local scope.
It can be accessed only inside that function or block.
Lifetime: Until function/block ends
Memory: Freed after execution
Function Scope (Local Scope)
function cooking() {
let food = "Biryani"; // local variable
console.log(food);
}

cooking();
console.log(food); // ❌ Error

Error
ReferenceError: food is not defined

example 1
let product = "biscuit"
console.log(product)
buymilk()
function buymilk(){
let product = "milk"
console.log("inside function",product)
}

output
biscuit
inside function milk

example 2
let product = "biscuit"
console.log(product)
buymilk()
function buymilk(){
console.log("inside function",product)
}

output
biscuit
inside function biscuit

Parameters vs. Arguments
Parameters are the names listed in the function definition.
Arguments are the values received by the function.
Examples
"name" and "age" are parameters:
function greet(name, age) {
return Hello ${name}! You are ${age} years old.;
}

"John" and 21 are arguments:
greet("John", 21);

Function Parameters and Arguments
syntax:
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.

Default parameter
Rest parameter
Return
One function using return statement for giving input for another function

example 1
function buyMilk(){
return "milk";
}
let container = buyMilk();
console.log(container)

output
milk

example 2
function buyMilk(){
return "milk";
console.log("milk");
}
let container = buyMilk();
console.log(container);

output
unreachable code after return statement
milk

example 3
function buyMilk(){
console.log("milk");
return "milk";
}
let container = buyMilk();
console.log(container);

output
milk
milk

example 4
function buymilk(){
let product = "milk";
return product;
}
let product = buymilk();
console.log(product);

output
milk

example 5
function buymilk(){
let product = "milk";
return product;
}
let product = buymilk();
console.log(product);
output
milk

example 6
let product = "biscuit"
console.log(product)
buymilk()
function buymilk(){
let product = "milk"
console.log("inside function",product)
}

output
biscuit
inside function milk

example 7
buymilk();
buybiscuit();
function buymilk(){
let product = "biscuit"
console.log("inside milk",product)
}
function biscuit(){
console.log("inside",product)
}
output
inside milk biscuit

example 8
buymilk();
buybiscuit();
function buymilk(){
let product = "biscuit"
console.log("inside",product)
}
function buybiscuit(){
console.log("inside",product)
}
output
inside biscuit
error(product is not defined)

Return
example 1
function add(){
let i = 10;
let j = 20;
return i,j;
}
output
error

example 2
function add(){
let i = 10;
let j = 20;
return 10,20;
}
output
error

example 3
function add(){
let i = 10;
let j = 20;
return i + j;
}
output
30

convert function into function expression by
not using function names

What is a Function Expression?
A function expression is a function assigned to a variable.
A function expression is a way of defining a function within an expression, rather than as a standalone declaration.
A function expression can be assigned to a variable, passed as an argument to another function, or returned from a function.
Example
const x = function (a, b) {return a * b};

example
const x = function (a, b) {return a * b};
let z = x(4, 3);
output
12
The function above is actually an anonymous function (a function without a name).

Functions stored in variables do not need function names. They are always invoked (called) using the variable name

Function Declarations
A function declaration (or simply a function) is defined using the function keyword followed by a function name, parameters, and a code block:
function add(a, b) {return a + b;}

Function Expressions
A function expression is defined by assigning an anonymous function to a variable:
const add = function(a, b) {return a + b;};
Note
Function expressions are commonly used to create anonymous functions.
Anonymous functions are functions without a name.
Function declarations are "hoisted" to the top of their scope. This means you can call a function before it is defined in the code:
let sum = add(2, 3);
function add(a, b) {return a + b;}

Semicolons are used to separate executable JavaScript statements.
Since a function declaration is not an executable statement, it is not common to end it with a semicolon.

let sum = add(2, 3); // ⛔ Will generate error.
const add = function (a, b) {return a + b;};

Arrow Functions allow a shorter syntax for function expressions.

You ca skip the function keyword, the return keyword, and the curly brackets:
let myFunction = (a, b) => a * b;
Before Arrow:

Function to compute the product of a and b
let myFunction = function(a, b) {return a * b}

With Arrow
let myFunction = (a, b) => a * b;

Before Arrow:
let hello = function() {
return "Hello World!";
}

With Arrow Function:
let hello = () => {
return "Hello World!";
}

If the function has only one statement that returns a value, you can remove the brackets and the return keyword:
Arrow Functions Return Value by Default:
let hello = () => "Hello World!";

Arrow functions must be defined before they are used.

You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
Example
// This will not work
let myFunction = (x, y) => { x * y } ;

// This will not work
let myFunction = (x, y) => return x * y ;

// Only this will work
let myFunction = (x, y) => { return x * y };

object

An Object is a variable that can hold many variables.
object inside functions are methods.
object is the combination of states and behaviour.
object contains information and methods.
information(Attributes,properties,states)
new object() is not neccessary

eg
const person ={}; (object)

JavaScript Objects
What is a JavaScript Object?
A JavaScript object is a collection of key–value pairs.
Keys are called properties, and values can be data or functions (methods).

🔹 Definition:

An object stores related data and functionality together.

🔹 Example:
let student = {
name: "Priya",
age: 21,
course: "AI & DS"
};

Note:

You should declare objects with the const keyword.
When an object is declared with const, you cannot later reassign it to point to a different variable.
It does not make the object unchangeable. You can still modify its properties and values.

🛠 How to Create a JavaScript Object

inside curly braces { }:
1️⃣ Using Object Literal (Most Common Method)
Syntax:
let objectName = {
property1: value1,
property2: value2
};

Example:
let car = {
brand: "Toyota",
model: "Innova",
year: 2023
};

console.log(car.brand); //
output
Toyota

2️⃣ Using the new Object() Method
Syntax:
let objectName = new Object();

new keyword calls the constructor
Example:
let person = new Object();
person.name = "Rahul";
person.age = 25;
person.city = "Chennai";

console.log(person);

output
Object { name: "Rahul", age: 25, city: "Chennai" }
There is no need to use new Object()
Object Properties

You can access object properties in two ways:
objectName.propertyName
objectName["propertyName"]

JavaScript Object Methods
Object methods are actions that can be performed on objects.
Object methods are function definitions stored as property values:
Sometimes we need to create many objects of the same type.
To create an object type we use an object constructor function.

object Constructor Function
Definition:
A constructor function is used to create multiple objects of the same type.
Syntax:
function Person(name, age) {
this.name = name;
this.age = age;
}
Example:
function Student(name, rollNo, department) {
this.name = name;
this.rollNo = rollNo;
this.department = department;
}

let s1 = new Student("Priya", 101, "AI & DS");
let s2 = new Student("Arun", 102, "CSE");

console.log(s1.name); // Priya

Note:
In the constructor function, this has no value.
this = refers to current object.
this = works only inside function
The value of this will become the new object when a new object is created.
Constructor function starts with the capital letters.
constructor is called automatically when the object is created
constructor = assigning object specific values into variables

Objects are containers for Properties and Methods.
Properties are named Values.
Methods are Functions stored as Properties.
Properties can be primitive values, functions, or even other objects.
Constructors are Object Prototypes.

example
constructor function
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
const mySelf = new Person("Johnny", "Rally", 22, "green");

    function Person(first,last,age,eyecolor){
        this.firstname = first,
        this.lastname = last,
        this.age = age,
        this.eyecolor = eyecolor;
    }
    console.log(myFather.eyecolor);
Enter fullscreen mode Exit fullscreen mode

output
blue

constructor function
const myFather = new Person("John", "Doe", 50);
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
const mySelf = new Person("Johnny", "Rally", 22, "green");

    function Person(first,last,age,eyecolor){
        this.firstname = first,
        this.lastname = last,
        this.age = age,
        this.eyecolor = eyecolor;
    }
    console.log(myFather.eyecolor);
Enter fullscreen mode Exit fullscreen mode

output
undefined

Object Properties in JavaScript
🔹 Accessing Object Properties
1️⃣ Dot Notation
console.log(student.name);

2️⃣ Bracket Notation
console.log(student["age"]);

📌 Use bracket notation when:

Property name has spaces

Property name is stored in a variable

Example:
let key = "course";
console.log(student[key]);

🔹 Adding New Properties
student.grade = "A";

🔹 Updating Properties
student.age = 22;

🔹 Deleting Properties
delete student.course;

🔹 Object with Methods
Example:
let user = {
name: "Priya",
login: function () {
console.log("User logged in");
}
};

user.login();

🔍 Check Property Exists
Using in operator:
console.log("name" in user); // true

🔁 Loop Through Object Properties
Using for...in loop:
for (let key in student) {
console.log(key + ": " + student[key]);
}

What are Object Methods?
When a function is stored inside an object, it is called a method.

🔸 Example:
let user = {
name: "Priya",
age: 21,
greet: function () {
console.log("Hello, " + this.name);
}
};
user.greet();

📌 Output:
Hello, Priya
✔ this refers to the current object

JavaScript Object Properties
An Object is an Unordered Collection of Properties
Properties are the most important part of JavaScript objects.
Properties can be changed, added, deleted, and some are read only.
Accessing JavaScript Properties

The syntax for accessing the property of an object is:
// objectName.property
let age = person.age;

or
//objectName["property"]
let age = person["age"];

or
//objectName[expression]
let age = person[x];
Examples
person.firstname + " is " + person.age + " years old.";
person["firstname"] + " is " + person["age"] + " years old.";
let x = "firstname";
let y = "age";
person[x] + " is " + person[y] + " years old.";

Adding new attributes:
eg
const person = {
name: "Priya",
age: 23
};
person.city = "Chennai";
console.log(person);
output
Object { name: "Priya", age: 23, city: "Chennai" }

update:
just assign a new value to the same key
eg
const person = {
name: "Priya",
age: 23,
city : "Chennai"
};
person.city = "london";
console.log(person.city);
output
london

delete:
the delete keyword deletes a property from an object
eg
const person = {
name: "Priya",
age: 23,
city : "Chennai"
};
delete person.city;
console.log(person);
output
Object { name: "Priya", age: 23 }

The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.

JavaScript Object Methods:
Object methods are actions that can be performed on objects.
A method is a function definition stored as a property value.
What are Object Methods?
When a function is stored inside an object, it is called an object method.
Accessing Object Methods:
You access an object method with the following syntax:
objectName.methodName()
If you invoke the fullName property with (), it will execute as a function:
Example
name = person.fullName();
If you access the fullName property without (), it will return the function definition:
Example
name = person.fullName;

eg 1
const Person = {
firstname:"Priya",
lastname:"saraswathi",
id: 5566,
fullname: function(){
return this.firstname + " " + this.lastname;
}
}
let fullname = Person.fullname();
console.log(fullname);
output
Priya saraswathi

eg 2
const Person = {
firstname:"Priya",
lastname:"saraswathi",
id: 5566,
fullname: function(){
return this.firstname + " " + this.lastname;
}
}
let fullname = Person.fullname();
console.log(Person.firstname);
output
Priya

Adding a Method to an Object
Adding a new method to an object is easy:
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};

Using JavaScript Methods
This example uses the JavaScript toUpperCase() method to convert a text to uppercase:
Example
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};

Built-in Numbers
Number Properties (Static)

  1. Number.MAX_VALUE

Definition:
Largest possible number in JavaScript.

console.log(Number.MAX_VALUE);
// 1.7976931348623157e+308

  1. Number.MIN_VALUE

Definition:
Smallest positive number greater than 0.

console.log(Number.MIN_VALUE);
// 5e-324

  1. Number.POSITIVE_INFINITY

Definition:
Represents positive infinity.

console.log(Number.POSITIVE_INFINITY);
// Infinity

  1. Number.NEGATIVE_INFINITY

Definition:
Represents negative infinity.

console.log(Number.NEGATIVE_INFINITY);
// -Infinity

  1. Number.NaN

Definition:
Represents “Not a Number”.

console.log(Number.NaN);
// NaN

  1. Number.EPSILON

Definition:
Smallest difference between two representable numbers.

console.log(Number.EPSILON);
// 2.220446049250313e-16

  1. Number.MAX_SAFE_INTEGER

Definition:
Largest safe integer in JavaScript.

console.log(Number.MAX_SAFE_INTEGER);
// 9007199254740991

  1. Number.MIN_SAFE_INTEGER

Definition:
Smallest safe integer in JavaScript.

console.log(Number.MIN_SAFE_INTEGER);
// -9007199254740991

📌 Number Methods (Static)

  1. Number.isNaN(value)

Definition:
Checks if value is NaN.

console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("10")); // false

  1. Number.isFinite(value)

Definition:
Checks if value is a finite number.

console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(Infinity)); // false

  1. Number.isInteger(value)

Definition:
Checks if value is an integer.

console.log(Number.isInteger(10)); // true
console.log(Number.isInteger(10.5)); // false

  1. Number.isSafeInteger(value)

Definition:
Checks if value is a safe integer.

console.log(Number.isSafeInteger(100));
// true

  1. Number.parseInt(value)

Definition:
Converts string to integer.

console.log(Number.parseInt("123.45"));
// 123

  1. Number.parseFloat(value)

Definition:
Converts string to floating-point number.

console.log(Number.parseFloat("123.45"));
// 123.45

📌 Number Methods (Instance)

  1. toString()

Definition:
Converts number to string.

let n = 10;
console.log(n.toString());
// "10"

  1. toFixed(n)

Definition:
Formats number with n decimal places.

let x = 5.6789;
console.log(x.toFixed(2));
// "5.68"

  1. toExponential(n)

Definition:
Converts number to exponential notation.

let x = 1234;
console.log(x.toExponential(2));
// "1.23e+3"

  1. toPrecision(n)

Definition:
Formats number to n total digits.

let x = 123.456;
console.log(x.toPrecision(4));
// "123.5"

  1. valueOf()

Definition:
Returns primitive value of number.

let x = new Number(10);
console.log(x.valueOf());
// 10

  1. toLocaleString()

Definition:
Formats number based on locale.

let num = 1000000;
console.log(num.toLocaleString("en-IN"));
// "10,00,000"

Built-in BigInt

Top comments (3)

Collapse
 
art_light profile image
Art light

You organized everything so clearly that it makes learning JavaScript much easier

Collapse
 
frntx profile image
frontend developer

remove emojis while copy and pasting from chatgpt

Collapse
 
priya_k_9427a2e692abd3ddb profile image
PRIYA K • Edited

okay i will