Understanding Switch Case and Functions and What is Hoisting

Darshan Kumar - Jul 7 - - Dev Community

**

Switch Case Statement in JavaScript

**
The switch case statement in JavaScript is used to execute one block of code among many options based on evaluating an expression. It is an alternative to using multiple if…else if statements and can make your code more readable and organized.

switch (expression) { case value1: // Code to be executed if expression === value1 break; case value2: // Code to be executed if expression === value2 break; // Add more cases as needed default: // Code to be executed if the expression doesn’t match any case }

Regular Functions

Regular functions in JavaScript are the most common way to define a function. They are determined using the function keyword followed by a name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.

Syntax:

function function-name(parameters) {

// Code to be executed

}

**

Function Expressions

**
A function expression is a function that is stored in a variable. Function expressions can be named or anonymous and are not hoisted, meaning they cannot be used before they are defined.

Syntax:

let variableName = function(parameters) {

// Code to be executed

};
**

**

Arrow Functions

**
**
Arrow functions, introduced in ES6, provide a shorter syntax for writing function expressions. They do not have their own context and are often used for writing concise, anonymous functions.

Syntax:

let variableName = (parameters) => {

// Code to be executed

};

**

Hoisting in JavaScript

**
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means you can use functions and variables before they are declared in the code.

Function Hoisting: Function declarations are hoisted, so you can call a function before it is declared.

console.log(greet()); // Output: Hello, world!

function greet() {

return “Hello, world!”;

}

Variable Hoisting: Variable declarations (using var) are hoisted to the top of their scope but not their initializations. Variables declared with let and const are also hoisted but are not initialized until their definition is evaluated.

Example with var:

console.log(x); // Output: undefined

var x = 5;

console.log(x); // Output: 5

. . . . .