DEV Community

PRIYA K
PRIYA K

Posted on

javascript questions

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

βœ… 2. String

Represents text.

let name = "Priya";

Enter fullscreen mode Exit fullscreen mode

βœ… 3. Boolean

Represents true/false values.

let isStudent = true;
Enter fullscreen mode Exit fullscreen mode

βœ… 4. Undefined

A variable declared but not assigned a value.

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

βœ… 5. Null

Represents an empty or unknown value.


let data = null;
Enter fullscreen mode Exit fullscreen mode

βœ… 6. BigInt

Used for very large numbers beyond Number limit.

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

βœ… 7. Symbol

Used for unique values (often in objects).

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

πŸ”Ή 2. Non-Primitive (Reference) Data Types

These store collections or complex data.

βœ… 1. Object

Key–value pairs.

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

βœ… 2. Array

Ordered list of items (objects but special type).

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

βœ… 3. Function

Functions are also objects in JavaScript.


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

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

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
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

Right shift

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

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

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

Top comments (1)

Collapse
 
art_light profile image
Art light

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