DEV Community

A Ramesh
A Ramesh

Posted on

Exploring JavaScript Fundamentals and a Simple React Project

In my journey of learning JavaScript and React, I’ve recently explored some important concepts that build the foundation of front-end development. In this blog post, I’ll share what I’ve learned about function declaration vs function expression, hoisting, function composition, and a small React project that toggles a light bulb on and off using the ternary operator.


🔹 Function Declaration vs Function Expression

In JavaScript, functions can be written in different ways. The two most common forms are:

✅ Function Declaration

A function declaration is defined using the function keyword and is hoisted, which means it can be called even before it's defined in the code.

sayHello(); // ✅ This works!

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

✅ Function Expression

A function expression is when a function is assigned to a variable. Unlike declarations, function expressions are not hoisted.

greet(); // ❌ Error: Cannot access 'greet' before initialization

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

🔹 What is Hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

  • Function declarations are hoisted with their definitions.
  • Variables declared with var are hoisted without initialization.
  • Variables declared with let and const are hoisted but not initialized (they stay in a "temporal dead zone").
console.log(name); // undefined
var name = "Ramesh";

sayHi(); // Works!
function sayHi() {
  console.log("Hi!");
}
Enter fullscreen mode Exit fullscreen mode

🔹 Function Composition

Function composition is the process of combining two or more functions to produce a new function. It helps to write clean, reusable, and modular code.

Example:

const add = (x) => x + 2;
const multiply = (x) => x * 3;

const compose = (f, g) => (x) => f(g(x));

const result = compose(multiply, add)(5); // (5 + 2) * 3 = 21
console.log(result); // Output: 21
Enter fullscreen mode Exit fullscreen mode

🔹 Mini React Project: Light On / Off Using Ternary Operator

I also built a simple React project that toggles a bulb image (or a text state) from ON to OFF using a ternary operator and the useState hook.

Here’s a simplified version of the code:

import React, { useState } from 'react';

function LightToggle() {
  const [isOn, setIsOn] = useState(false);

  return (
    <div>
      <h2>The light is {isOn ? 'ON' : 'OFF'}</h2>
      <button onClick={() => setIsOn(!isOn)}>
        {isOn ? 'Turn OFF' : 'Turn ON'}
      </button>
    </div>
  );
}

export default LightToggle;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)