JavaScript Basics for Interviews

JavaScript Basics for Interviews

With 10 days of Diwali vacation ahead, I’m diving into JavaScript Mastery in 10 Days—a focused series designed to help JavaScript developers revisit core concepts and ace those must-know topics for interviews and beyond.

Data Types in JavaScript

JavaScript includes eight fundamental data types, categorized into two groups: Primitive and Non-Primitive types.

Primitive Data Types

1. String: Used for textual data, represented as a sequence of characters.

• Example: 'hello', "hello world!"

2. Number: Represents both integer and floating-point numbers.

• Example: 3, 3.234, 3e-2

3. BigInt: An integer with arbitrary precision, introduced in ES2020, used for very large integers.

• Example: 900719925124740999n, 1n

4. Boolean: Represents a logical value—either true or false.

5. Null: A special keyword representing an intentional “no value” or “unknown”.

6. Undefined: Indicates a variable that has been declared but not initialized or assigned a value.

7. Symbol: A unique and immutable data type, introduced in ES6, often used for unique property keys in objects.

• Example: let value = Symbol();

Non-Primitive Data Types

1. Object: A collection of key-value pairs, where keys are strings and values can be any data type.

• Example: let student = { name: "John" };

2. Array: A specialized type of object that stores an ordered collection of values, which can be of any data type.

• Example: let numbers = [1, 2, 3, 4, 5];

Additional Notes

• JavaScript is a dynamically typed language, allowing variables to hold different data types at different times.

• The typeof operator can be used to determine the data type of a variable.

• JavaScript differentiates between null and undefined values, with distinct meanings and uses.

JavaScript Variable Declarations: var, let , and const

In JavaScript, you can declare variables using var, let, or const, each serving a slightly different purpose:

1. var:

Scope: var is function-scoped, which means it’s only accessible within the function it’s declared in. However, if declared outside of a function, it becomes available globally.

Usage: While var has been used historically, it can lead to unexpected behavior in larger codebases, so it’s less common in modern JavaScript.

2. let:

Scope: let is block-scoped, meaning it’s only accessible within the block {} it’s declared in.

Usage: let is ideal when you plan to reassign the variable later in your code.

3. const:

Scope: Like let, const is also block-scoped.

Reassignment: Once assigned, a const variable cannot be reassigned. Use const when you don’t want the value to change, like with configuration settings or constants.

Mutable Objects: For objects and arrays, const prevents reassignment, but you can still modify properties or elements within.

Quick Tip: In modern JavaScript, use const by default, let when you need to reassign, and generally avoid var for cleaner, more predictable code.

JavaScript Operators

JavaScript provides a variety of operators to perform different types of operations on values. Here’s a concise summary:

1. Arithmetic Operators

Used for basic mathematical operations:

• + (Addition)

• - (Subtraction)

• * (Multiplication)

• / (Division)

• % (Modulus)

• ** (Exponentiation)

• ++ (Increment)

• -- (Decrement)

2. Assignment Operators

Used to assign values to variables:

• = (Assign)

• += (Add and assign)

• -= (Subtract and assign)

• *= (Multiply and assign)

• /= (Divide and assign)

• %= (Modulus and assign)

3. Comparison Operators

Used to compare two values:

• == (Equal)

• === (Strict equal)

• != (Not equal)

• !== (Strict not equal)

• > (Greater than)

• < (Less than)

• >= (Greater than or equal to)

• <= (Less than or equal to)

4. Logical Operators

Used with boolean values:

• && (AND)

• || (OR)

• ! (NOT)

5. Bitwise Operators

Operate on the binary representation of numbers:

• & (AND)

• | (OR)

• ^ (XOR)

• ~ (NOT)

• << (Left shift)

• >> (Right shift)

6. String Operators

Primarily used for concatenating strings:

• + (Concatenation)

• += (Concatenation assignment)

7. Conditional (Ternary) Operator

A shorthand for if-else:

• condition ? valueIfTrue : valueIfFalse

8. Type Operators

• typeof (Returns the type of a variable)

• instanceof (Checks if an object is an instance of a specific class)

9. Nullish Coalescing Operator

Provides a default value for null or undefined:

• ??

10. Optional Chaining Operator

Allows safe access to deeply nested object properties:

• ?.

Control Structures in JavaScript

Control structures are essential for directing the flow of execution in a program. In JavaScript, they allow you to execute different blocks of code based on certain conditions or iterate through data. Here’s a summary of the main control structures:

1. Conditional Statements

Conditional statements execute different code blocks based on specific conditions.

• if Statement:

if (condition) {
    // Code to execute if condition is true
}

• if...else Statement:

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

• else if Statement:

if (condition1) {
    // Code for condition1
} else if (condition2) {
    // Code for condition2
} else {
    // Code if none of the above conditions are true
}

• switch Statement:

A cleaner way to execute different code blocks based on the value of a variable.

switch (expression) {
    case value1:
        // Code to execute if expression === value1
        break;
    case value2:
        // Code to execute if expression === value2
        break;
    default:
        // Code to execute if no cases match
}

2. Loops

Loops allow you to execute a block of code multiple times.

• for Loop:

Used for iterating over a range of values.

for (let i = 0; i < 5; i++) {
    // Code to execute on each iteration
}

• while Loop:

while (condition) {
    // Code to execute while condition is true
}

• do...while Loop:

Similar to while, but the code block is executed at least once before the condition is tested.

do {
    // Code to execute at least once
} while (condition);

• for...of Loop:

Iterates over iterable objects (like arrays or strings).

for (const key in object) {
    // Code to execute for each property
}

• for...in Loop:

Iterates over the enumerable properties of an object.

for (const key in object) {
    // Code to execute for each property
}

3. Exception Handling

To manage errors gracefully, JavaScript provides a way to handle exceptions.

• try...catch Statement:

Executes code that might throw an error and catches any errors that occur.

try {
    // Code that may throw an error
} catch (error) {
    // Code to execute if an error occurs
} finally {
    // Code that runs regardless of an error
}

Type Coercion in JavaScript

Type coercion is the process by which JavaScript automatically converts values from one type to another. This can happen in various situations, especially when performing operations involving different data types.

1. Implicit Coercion

JavaScript automatically converts types when necessary.

String and Number:

console.log(5 + "5"); // "55" (Number is coerced to String)
console.log("5" - 2); // 3 (String is coerced to Number)

Boolean and Number:

console.log(1 + true);  // 2 (true is coerced to 1)
console.log(0 + false);  // 0 (false is coerced to 0)

Boolean and String:

console.log("The answer is " + true); // "The answer is true" (true is coerced to String)
console.log("5" + false); // "5false" (false is coerced to String)

2. Explicit Coercion

You can manually convert types using functions.

Number to String:

let num = 10;
let str = String(num);
console.log(str); // "10"

String to Number:

let strNum = "20";
let numFromStr = Number(strNum);
console.log(numFromStr); // 20

Boolean to String:

let boolValue = true;
let strBool = String(boolValue);
console.log(strBool); // "true"

String to Boolean (using double negation):

let nonEmptyString = "Hello";
let isTrue = !!nonEmptyString;
console.log(isTrue); // true (non-empty string is truthy)

3. Coercion in Comparisons

Different types are compared through coercion.

Using \== (Equality):

console.log(0 == "0"); // true (String is coerced to Number)
console.log(false == ""); // true (Both are coerced to Number)

Using \=== (Strict Equality):

console.log(0 === "0"); // false (No coercion, different types)
console.log(false === ""); // false (No coercion, different types)

\== (Equality Operator)

The == operator, known as the equality operator, compares two values for equality after performing type coercion if they are of different types. This means JavaScript will convert the values to a common type before making the comparison.

Examples of ==:

1. Different Types:

console.log(5 == '5');    // true (String '5' is coerced to Number 5)
console.log(false == 0);   // true (false is coerced to 0)
console.log(null == undefined); // true (both are treated as equal)

2. Same Types:

console.log(10 == 10);     // true
console.log('hello' == 'hello'); // true

\=== (Strict Equality Operator)

The === operator, known as the strict equality operator, compares two values for equality without performing type coercion. If the types are different, the comparison will return false.

Examples of ===:

1. Different Types:

console.log(5 === '5');    // false (different types, no coercion)
console.log(false === 0);   // false (different types)
console.log(null === undefined); // false (different types)

2. Same Types:

console.log(10 === 10);     // true
console.log('hello' === 'hello'); // true

That’s a wrap for Day 1! These basic concepts are essential for anyone looking to delve deeper into more advanced topics in JavaScript. Understanding these fundamentals will provide you with a solid foundation to build upon as we explore more complex topics in the coming days.

Stay tuned for Day 2, where we’ll dive into variable declarations and scope! Happy coding!