Javascript Fundamentals

Omkar Bhavare
8 min readJan 1, 2024

--

JavaScript, as a versatile and dynamic programming language, is crucial for both beginners and experienced developers. In this article, we’ll delve into fundamental concepts that form the backbone of JavaScript development, making it accessible to developers at all levels.

📚var vs. let vs. const

var

var is the traditional way of declaring variables in JavaScript. It has function scope, which means the variable is accessible throughout the function where it is declared. However, it lacks block scope, which can lead to unintended consequences.

function example() {
if (true) {
var x = 10;
}
console.log(x); // Outputs 10
}

Advantages:

  • Hoisting: Variables declared with var are hoisted to the top of their scope.

Disadvantages:

  • Lack of block scope: May lead to unexpected behavior, especially in loops or conditional statements.

let

Introduced in ECMAScript 6 (ES6), let addresses the issues associated with var by introducing block scope. Variables declared with let are only accessible within the block or statement where they are defined.

function example() {
if (true) {
let y = 10;
}
// console.log(y); // Error: y is not defined
}

Advantages:

  • Block scope: Provides more predictable and less error-prone behavior.
  • Cannot be redeclared in the same scope.

Disadvantages:

  • Hoisting: Still subject to hoisting, but the variable is not initialized until the declaration statement is executed.

const

Similar to let in terms of block scope, const is used for constants whose values should not be reassigned. It must be initialized during declarations.

const PI = 3.14;
// PI = 22/7; // Error: Assignment to a constant variable

Advantages:

  • Immutability: Ensures that the variable’s value remains constant throughout its lifecycle.
  • Block scope: Provides a clear and confined scope for the variable.

Disadvantages:

  • Must be initialized during declaration.

📚 Understanding Data Types:

Primitive Types:

1. Number:

Numbers in JavaScript are used to represent numeric values, whether integers or floating-point decimals. They are fundamental for arithmetic operations and mathematical calculations.

let num = 42;
let floatNum = 3.4;
console.log(num); // Output: 42
console.log(typeof num); // Output: number

2. String:

Strings are sequences of characters and are essential for working with textual data. They can be declared using single or double quotes.

let greeting = 'Hello, World!';
console.log(greeting); // Output: Hello, World!
console.log(typeof greeting); // Output: string

3. Boolean:

Booleans have two possible values: true or false. They are crucial for conditional statements and logical operations.

let isTrue = true;
console.log(isTrue); // Output: true
console.log(typeof isTrue); // Output: boolean

4. Null:

The null primitive type represents the intentional absence of any object value. For example, if a database query returns no results, you might use null to represent this absence.

let nullValue = null;
console.log(nullValue); // Output: null
console.log(typeof nullValue); // Output: object

5. Undefined:

When a variable is declared but not assigned a value, it is of type undefined.For example, When you declare a variable but haven’t assigned it a value yet. It is the default value of uninitialized variables.

let undefinedValue;
console.log(undefinedValue); // Output: undefined
console.log(typeof undefinedValue); // Output: undefined

📚 Type Conversion:

JavaScript allows the conversion of one data type to another, often implicitly during operations or explicitly using conversion functions.

1. Implicit Type Conversion:

// Implicit Type Conversion Examples

// 1. Numeric and String Concatenation
let result1 = '42' + 2;
console.log(result1); // Output: '422'
console.log(typeof result1); // Output: string

// 2. Numeric and Boolean Operations
let result2 = true + 42;
console.log(result2); // Output: 43
console.log(typeof result2); // Output: number

// 3. String and Boolean Operations
let result3 = '42' + true;
console.log(result3); // Output: '42true'
console.log(typeof result3); // Output: string

// 4. Boolean and String Operations
let result4 = false + '42';
console.log(result4); // Output: 'false42'
console.log(typeof result4); // Output: string

// Edge Cases:

// Case 1: Concatenation with Undefined or Null
let undefinedConcat = '42' + undefined;
let nullConcat = '42' + null;
console.log(undefinedConcat); // Output: '42undefined'
console.log(nullConcat); // Output: '42null'
console.log(typeof undefinedConcat); // Output: string
console.log(typeof nullConcat); // Output: string

// Case 2: Concatenation with NaN
let nanConcat = '42' + NaN;
console.log(nanConcat); // Output: '42NaN'
console.log(typeof nanConcat); // Output: string

// Points to Remember:

// 1. Implicit type conversion occurs during operations between different data types.
// 2. JavaScript uses coercion rules to convert values to a common type before performing operations.
// 3. Be cautious with string concatenation, as it may lead to unexpected results, especially when combining with undefined, null, or NaN.
// 4. Understand the coercion rules and potential pitfalls to write predictable and bug-free code.

2. Explicit Type Conversion:

a. String to Number:

// String to Number Conversion Examples

// 1. Using parseInt()
let num1 = parseInt('42');
console.log(num1); // Output: 42
console.log(typeof num1); // Output: number

// 2. Using parseFloat()
let num2 = parseFloat('42.5');
console.log(num2); // Output: 42.5
console.log(typeof num2); // Output: number

// 3. Using the unary plus operator (+)
let num3 = +'42';
console.log(num3); // Output: 42
console.log(typeof num3); // Output: number

// 4. Using Number() constructor
let num4 = Number('42.75');
console.log(num4); // Output: 42.75
console.log(typeof num4); // Output: number

// Edge Cases:

// Case 1: Handling non-numeric strings
let nonNumericStr = 'Hello';
let result1 = parseInt(nonNumericStr);
console.log(result1); // Output: NaN (Not a Number)
console.log(typeof result1); // Output: number (special type NaN)

// Case 2: Handling strings with leading/trailing whitespaces
let stringWithSpaces = ' 42.5 ';
let result2 = parseFloat(stringWithSpaces);
console.log(result2); // Output: 42.5
console.log(typeof result2); // Output: number

// Case 3: Using parseInt() with radix/base
let hexString = '1a';
let result3 = parseInt(hexString, 16);
console.log(result3); // Output: 26
console.log(typeof result3); // Output: number

// Points to Remember:

// 1. Be cautious with parseFloat() for whole numbers, as it may introduce floating-point precision.
// 2. NaN (Not a Number) is a special numeric value representing an undefined or unrepresentable value.
// 3. parseInt() can handle different numeric bases when the string starts with '0x' for hexadecimal, '0o' for octal, or '0b' for binary.
// 4. Always validate input strings to avoid unexpected results, especially when converting user input.

b. Number to String:

// Number to String Conversion Examples

// 1. Using String() conversion function
let str1 = String(42);
console.log(str1); // Output: '42'
console.log(typeof str1); // Output: string

// 2. Using concatenation with an empty string
let str2 = 42 + '';
console.log(str2); // Output: '42'
console.log(typeof str2); // Output: string

// 3. Using the toString() method
let num = 42.5;
let str3 = num.toString();
console.log(str3); // Output: '42.5'
console.log(typeof str3); // Output: string

// Edge Cases:

// Case 1: Handling NaN (Not a Number)
let notANumber = NaN;
let result1 = String(notANumber);
console.log(result1); // Output: 'NaN'
console.log(typeof result1); // Output: string

// Case 2: Handling Infinity and -Infinity
let positiveInfinity = Infinity;
let negativeInfinity = -Infinity;
let result2 = String(positiveInfinity);
let result3 = String(negativeInfinity);
console.log(result2); // Output: 'Infinity'
console.log(result3); // Output: '-Infinity'
console.log(typeof result2); // Output: string
console.log(typeof result3); // Output: string

// Case 3: Using toPrecision() for control over decimal places
let num2 = 42.123456;
let result4 = num2.toPrecision(4);
console.log(result4); // Output: '42.12'
console.log(typeof result4); // Output: string

// Points to Remember:

// 1. Be cautious with toString() when dealing with null or undefined values, as it will result in a TypeError.
// 2. String() and concatenation methods are simple and convenient but may have performance implications for large-scale operations.
// 3. Converting special numeric values like NaN, Infinity, and -Infinity results in corresponding string representations.
// 4. Use toPrecision(), toFixed(), or toExponential() for control over the precision of the converted string when dealing with floating-point numbers.

c. Boolean to Number:

// Boolean to Number Conversion Examples

// 1. Using the unary plus operator (+)
let num1 = +true;
console.log(num1); // Output: 1
console.log(typeof num1); // Output: number

// 2. Using Number() conversion function
let num2 = Number(false);
console.log(num2); // Output: 0
console.log(typeof num2); // Output: number

// Edge Cases:

// Case 1: Handling true as 1 and false as 0
let trueBool = true;
let falseBool = false;
let result1 = +trueBool;
let result2 = +falseBool;
console.log(result1); // Output: 1
console.log(result2); // Output: 0
console.log(typeof result1); // Output: number
console.log(typeof result2); // Output: number

// Case 2: Handling other truthy and falsy values
let truthyValue = 'Hello';
let falsyValue = '';
let result3 = +truthyValue;
let result4 = +falsyValue;
console.log(result3); // Output: NaN (Not a Number)
console.log(result4); // Output: 0
console.log(typeof result3); // Output: number
console.log(typeof result4); // Output: number

// Points to Remember:

// 1. Converting true to a number results in 1, and converting false results in 0.
// 2. Using the unary plus operator or the Number() function achieves the same result.
// 3. Be cautious when converting non-boolean values, as unexpected results (such as NaN) may occur.
// 4. Ensure that the boolean values you are converting make sense in a numeric context.

🔥 FAQ

⭐️ What does the typeof operator return for null and undefined?

typeof null returns ‘object’ whereas typeof undefined returns undefined.

let num1=null;
let num2;

console.log(typeof num1); // object
console.log(typeof num2); // undefined

⭐️ Explain the concept of “hoisting” in relation to null and undefined.
How does it affect the values of variables?

  • Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation.
  • For variables, only the declaration is hoisted, not the assignment. So, if a variable is not assigned a value, it’s undefined by default.

⭐️ Write a function that removes null and undefined values from an array.

function removeNullUndefined(arr) {
return arr.filter(item => item !== null && item !== undefined);
}

⭐️ Explain the concept of a “nullish coalescing operator” (??)

The nullish coalescing operator (??) returns the right operand when the left operand is null or undefined.

let variable = null;
let result = variable ?? "default";
console.log(result); // Outputs "default"

⭐️ Discuss a practical example where using let for a constant value is more appropriate than using const.

If you want a value that might change based on certain conditions, it’s better to use let as const requires an immediate assignment during declaration.

⭐️ Explain the role of hoisting in the context of let and const. How do they differ from the hoisting behavior of var?

Unlike var, let and const are hoisted but not initialized, leading to a Temporal Dead Zone (TDZ). Trying to access them before declaration results in a ReferenceError. In contrast, var is hoisted and initialized with undefined.

📚Earlier Post:

👉 React Js Fundamentals

🔍 Coming up next:

👉 JavaScript Execution and Call Stack
👉 Memory Management , Memory Leak and Garbage Collection
👉 Operators and Control Flow

Stay tuned for more insights into the world of Javascript Fundamentals🚀📦

🤝 Let’s connect on LinkedIn: https://www.linkedin.com/in/omkarbhavare/

--

--

Omkar Bhavare

Passionate developer, blogger, and problem solver. Crafting code, sharing insights, and building innovative projects. 🚀