NodeJS Articles

Defining a Javascript Function

0 👍
👎 0
 NodeJS
 Javascript

How To Define a JavaScript Function

There are a few different ways to declare a function in Javascript applications. I’ve laid out 4 ways below so choose the method that best fits your use case! Function declarations are great for named functions, whereas arrow functions are excellent for callbacks and shorter functions.  

Using Function Declaration

 

 /** Function Declaration */

 function functionName(parameters) {

    // code to be executed

    return value;

 }

 

 // Example

 function greet(name) {

    return "Hello, " + name + "!";

 }

 console.log(`My name is ${greet("Alice")}`); // "Hello, Alice!"

 

 

Using Function Expression

 

 /** Function Expression */

 const functionName = function(parameters) {

    // code to be executed

    return value;

 };

 

 // Example

 const multiply = function(a, b) {

    return a * b;

 };

 console.log(`5 * 3 = ${multiply(5, 3)}`); // 15

 

 

Using Arrow Functions (ES6)

 

 /** Arrow Function (ES6) */

 const functionName = (parameters) => {

    // code to be executed

    return value;

 };

 

 // Examples with different syntax

 const square = (x) => {

    return x * x;

 };

 console.log(`Square of 4: ${square(4)}`); // 16

 

 // Implicit return (for single expressions)

 const squareRoot = x => x ** 0.5;

 console.log(`Square Root of 8: ${squareRoot(8)}`);

 

 // Multiple parameters

 const add = (a, b) => a + b;

 console.log(`2 + 3 = ${add(2, 3)}`); // 5

 

 // No parameters

 const title = () => "Math";

 console.log(`The page title is "${pageTitle()}"`);

 

 

Using the Function Constructor

 

 /** 4. Function Constructor (less common) */

 const functionName = new Function("parameters", "function body");

 

 // Example

 const divide = new Function("a", "b", "return a / b;");

 console.log(divide(10, 2)); // 5

 



JavaScript Self-Invoked Functions (IIFEs)

0 👍
👎 0
 NodeJS
 Javascript

What is a self-invoked function? (IIFE)

A self-invoked function, also called an Immediately Invoked Function Expression (IIFE) is a Javascript function expression that is invoked immediately after its declaration.  A self-invoked function can be a valuable tool for creating isolated scopes and managing variable privacy in javascript applications.

 

Key aspects of IIFEs:

 

- IIFEs execute immediately when defined

- Allows creation of private scopes without polluting global namespace

- Return values can be assigned to variables

- Parameters can be passed to IIFEs



Basic syntax:

 

 (function() {

    // code here

 })();

 

 // OR arrow functions (ES6+)

 (() => {

       // code here

 })();

 

 

 

Why are IIFEs Necessary?

Immediate Execution with Parameters

 

 // Immediately logs provided data

 (function(date, location) {

    console.log(`Date: ${date.toDateString()}`);

    console.log(`Location: ${location}`);

 })(new Date(), 'Seattle');

 

 // Immediately logs:

 // Date: Thu Oct 16 2025

 // Location: Seattle

 

 

Avoiding Global Namespace Pollution

 

 // if multiple scripts use the same variable names

 // they won't conflict

 (function() {

    const restaurant = "Dairy Queen";

    console.log(user); // "Dairy Queen"

 })();

 

 (function() {

    const restaurant = "Burger King";

    console.log(user); // "Burger King"

 })();

 

 

Data Privacy/Encapsulation

 

 // Problem: counter value is vulnerable.

 var counter = 0;

 function increment() {

    return ++counter;

 }

 

 // FIX: keeps variables private. counterModule isn't directly accessible

 const counterModule = (function() {

    let count = 0;

   

    return {

        increment: function() {

            return ++count;

        },

        decrement: function() {

            return --count;

        },

        getCount: function() {

            return count;

        }

    };

 })();

 

 counterModule.count = 100; // WONT WORK!!

 // count is not accessible directly

 

 console.log(counterModule.getCount()); // 0

 counterModule.increment();

 console.log(counterModule.getCount()); // 1

 // OUPTUT: 0 1

 

 

Module Pattern Implementation

 

 const User = (function() {

    let memory = 0;

   

    function add(a, b) {

        return a + b;

    }

   

    function store(value) {

        memory = value;

    }

   

    function recall() {

        return memory;

    }

   

    // Only expose public methods

    return {

        add: add,

        store: store,

        recall: recall

    };

 })();

 

 console.log(Calculator.add(5, 3)); // 8

 Calculator.store(10);

 console.log(Calculator.recall()); // 10

 // memory is private and inaccessible

 

 

Using the Javascript Switch Statement

1 👍
👎 0
 NodeJS
 ReactJS
 Javascript

Overview of the Switch Statement


  The switch statement is a control structure available in almost every programming and scripting language.  It allows the developer to execute different blocks of code based on the value of an expression.  It is often used as a cleaner alternative to multiple if-else statements.  You may be asking yourself why use the switch statement since we already have if-else.  


   There are differences though.  And depending on the task-at-hand, the switch statement can be a better alternative than
if-else.  

Structure:

 

 switch (expression) {

    case value1:

        // execute this code block only

        break;

    case value2:

        // execute this code block only

        break;

    default:

        // execute if no cases match

 }


   A
switch statement evaluates an expression and executes the code block for the first case that matches its value.

   The break keyword is crucial. When encountered, it exits the entire switch statement immediately. Without it, execution will "fall through" and run the code in the subsequent case, even if the value doesn't match.  If no matching case is found, the optional default block is executed.

Example:

 

 let day = 'Monday';

 let output = '';

 switch (day) {

    case 'Monday':

        output = `Day is Monday`;

    case 'Tuesday':

        output = `Day is Tuesday`;

        break;

    case 'Wednesday':

        output = `Day is Wednesday`;

        break;

    case 'Thursday':

        output = `Day is Thursday`;

        break;

    case 'Friday':

        output = `Day is Friday`;

        break;

    case 'Saturday':

        output = `Day is Saturday`;

        break;

    case 'Sunday':

        output = `Day is Sunday`;

        break;

    default:

        output = `No day specified`;

 }

 

 // Output if day == 'Monday' OR day == 'Tuesday':

 // Day is Tuesday

 

 // Output if day == 'Saturday':

 // Day is Saturday

 

 // Output if day == 'Nothing'

 // No day specified

 


   This example demonstrates a crucial concept in JavaScript's
switch statement: fallthrough.  When day is 'Monday', the output will indeed be "Day is Tuesday".  Here’s why: The switch statement finds a match on case 'Monday' and begins executing the code on the next line, setting output = 'Day is Monday'.

  Because there is no break keyword at the end of the 'Monday' case, the logic "falls through" and continues to execute the very next line of code, which is the start of the 'Tuesday' case.  It then executes output = 'Day is Tuesday', overwriting the previous value.  Finally, the break keyword at the end of the 'Tuesday' case is encountered, which halts the execution of the switch block entirely.

   The break statement is not optional for most use cases. It is essential for exiting the switch block once a specific case's code has finished running. Without it, execution will continue into the next case, whether it matches or not.


   The
default case is only executed if no other case values match the expression. It will not be executed simply because of a fallthrough from a matched case (unless that fallthrough leads all the way to it).

Using Slots in Vue 2 (Options API)

0 👍
👎 0
 Laravel
 VueJS
 NodeJS
 Javascript

Slots in Vue let you create reusable components where the parent controls part of the content. 

 

1. Create a reusable component (Card.vue)

 

 <template>

   <div class="card">

     <div class="card-header">

       <!-- Named slot for header -->

       <slot name="header">Default Header</slot>

     </div>

 

     <div class="card-body">

       <!-- Default slot -->

       <slot>Default content goes here...</slot>

     </div>

 

     <div class="card-footer">

       <!-- Named slot for footer -->

       <slot name="footer">Default Footer</slot>

     </div>

   </div>

 </template>

 

 <script>

 export default {

   name: "Card"

 }

 </script>

 

 

2. Use the component in a parent (App.vue or a Blade-Vue view)

 

 <template>

   <div>

     <h1>Vue 2 Slots Example</h1>

 

     <Card>

       <template v-slot:header>

         Custom Header: Article Info

       </template>

 

       This is the article body content coming from the parent.

 

       <template v-slot:footer>

         <button @click="sayHello">Click Me</button>

       </template>

     </Card>

 

     <!-- Another card with defaults -->

     <Card />

   </div>

 </template>

 <script>

 import Card from "./Card.vue";

 export default {

   name: "App",

   components: { Card },

   methods: {

     sayHello() {

       alert("Hello from slot footer button!");

     }

   }

 }

 </script>

 

 

Javascript Variable Declaration

0 👍
👎 0
 NodeJS
 Javascript

JavaScript has three ways to declare variables, each with different scoping rules and use cases.

When to Use Each

const: Default choice for most variables

let: When you need to reassign values (counters, flags, accumulators)

var: Rarely needed in modern code; mainly for legacy support or specific patterns

The introduction of let and const in ES6 significantly improved JavaScript's variable scoping and made code more predictable and maintainable.

1. var (Function-Scoped)

var is the original way to declare variables in JavaScript. It has function scope and is hoisted to the top of its scope.

Characteristics:

1. Function-scoped (not block-scoped)

2. Hoisted to the top of its scope

3. Can be redeclared and updated

4. Creates a property on the global object (when declared globally)

 

// Function-scoped example

 function doSomething() {

    if (true) {

       var x = 10; // Available throughout the function

    }

    console.log(x); // 10 - accessible outside the block

 }

 

 // Hoisting example

 console.log(y); // undefined (hoisted but not initialized)

 var y = 5;

 

 // Redeclaration

 var z = 1;

 var z = 2; // No error

 console.log(z); // 2

 

2. let (Block-Scoped)

let was introduced in ES6 and provides block-level scoping, which is generally more predictable.

Characteristics:

1. Block-scoped ({ } boundaries)

2. Not hoisted in the same way as var (temporal dead zone)

3. Can be updated but not redeclared in the same scope

4. Doesn't create properties on the global object

Example Use Cases:

 

 // Block-scoped example

 function exampleLet() {

    if (true) {

        let x = 10; // Only available in this block

        console.log(x); // 10

    }

    // console.log(x); // ReferenceError: x is not defined

 }

 

 // Loop variables (ideal use case)

 for (let i = 0; i < 5; i++) {

    setTimeout(() => {

       console.log(i); // Logs 0, 1, 2, 3, 4 (not 5,5,5,5,5 like with var)

    }, 100);

    console.log(i);

 }

 

 // Can be updated but not redeclared

 let count = 0;

 count = 1; // Allowed

 // let count = 2; // SyntaxError: Identifier 'count' has already been declared

 

3. const (Block-Scoped Constants)

const is also ES6 feature for declaring constants - variables that cannot be reassigned.

Characteristics:

1. Block-scoped like let

2. Must be initialized during declaration

3. Cannot be reassigned after declaration

4. For objects/arrays, the reference is constant but properties/elements can be modified

Example Use Cases:

 

 // Constants that shouldn't change

 const PI = 3.14159;

 const API_URL = "https://api.example.com";

 

 // Object with const - properties can be modified

 const person = {

    name: "John",

    age: 30

 };

 person.age = 31; // Allowed - modifying property

 // person = {name: "Jane"}; // Error - cannot reassign

 

 // Array with const - elements can be modified

 const colors = ["red", "green"];

 colors.push("blue"); // Allowed

 // colors = ["purple"]; // Error - cannot reassign

 

 // Configuration objects

 const CONFIG = {

    timeout: 5000,

    retries: 3,

    baseURL: "https://api.example.com"

 };

 

What Happens When You Don't Declare Variable Types in JavaScript

When you don't use var, let, or const to declare a variable, JavaScript automatically creates a global variable (in non-strict mode). This is generally considered bad practice and can lead to bugs.

Problem Scenario:

 

// In file1.js

 function initApp() {

    config = { theme: "dark" }; // Accidentally global

 }

 

 // In file2.js (loaded later)

 function updateConfig() {

    config = { theme: "light" }; // Modifies the same global variable!

 }

 

Solution:

 

 // Always declare variables properly

 function initApp() {

    const config = { theme: "dark" }; // Properly scoped

    return config;

 }

 

 function updateConfig(currentConfig) {

    return { ...currentConfig, theme: "light" }; // No side effects

 }

 


Best Practices

1. Always declare variables with const, let, or var

2. Use 'use strict' to catch undeclared variables

3. Lint your code - tools like ESLint will flag this error

4. Prefer const/let over var for better scoping

 

 // Good

 const calculateTotal = (items) => {

   let total = 0;

   for (let item of items) {

       total += item.price;

   }

   return total;

 };

 

 // Bad (creates global variable)

 const calculateTotalBad = (items) => {

    total = 0; // Missing declaration!

    for (item of items) { // Also missing declaration!

       total += item.price;

    }

    return total;

 };

 

 

Javascript Null Coalescing Operator ??

0 👍
👎 0
 NodeJS

The double question mark ?? in javascript is referred to as the null coalescing operator.  It was introduced in JavaScript ES2020.  It allows you to check for null or undefined variable.   In most cases the order of operation for this operator follows the math and comparison operators.  Below are a few examples: 


Example 1:
let myval = null;
console.log(myval ?? 20); // output is 20 because myval is null

Example 2:
console.log(myval ?? 20); // output is 20 because myval is undefined

Example 3:
let myval = [];
console.log(myval ?? [1,2,3]);  // output is [] because it isn't null and it's not undefined

If the myval is anything other than null or undefined, the output will be the value of the right-hand side of the equation.