DEV Community

fiaz jutt
fiaz jutt

Posted on

JavaScript Basics: Variables, Functions, and Loops Made Simple

Introduction:
JavaScript is the foundation of modern web development. Whether you're a beginner or brushing up on the basics, understanding variables, functions, and loops is essential for writing clean, efficient code.


1. Variables — Storing Data

Variables allow you to store and manipulate data. In JavaScript, you can declare variables using var, let, or const.

Example:

let name = "Alice";
const age = 25;
var isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Tip: Use let for variables that might change, const for values that shouldn't, and avoid var in modern code for better predictability.


2. Functions — Reusable Code Blocks

Functions help you organize and reuse code efficiently.

Example:

function greet(user) {
  console.log("Hello, " + user + "!");
}

greet("Alice");
Enter fullscreen mode Exit fullscreen mode

Arrow Functions:

const add = (a, b) => a + b;
console.log(add(5, 3)); // Outputs: 8
Enter fullscreen mode Exit fullscreen mode

3. Loops — Repeat Tasks Easily

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

For Loop Example:

for (let i = 0; i < 5; i++) {
  console.log("Number: " + i);
}
Enter fullscreen mode Exit fullscreen mode

While Loop Example:

let count = 0;
while (count < 3) {
  console.log("Count is " + count);
  count++;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)