DEV Community

Cover image for Understanding JavaScript Variables: A Beginner's Guide
Rashidcodes
Rashidcodes

Posted on • Edited on

Understanding JavaScript Variables: A Beginner's Guide

Introduction

JavaScript variables play a crucial role in programming by allowing developers to store and manipulate data. In this blog post, we'll explore the fundamentals of variables in JavaScript and provide practical examples to enhance your understanding.

Declaring Variables

JavaScript provides three ways to declare variables:

var, let, and const.
Enter fullscreen mode Exit fullscreen mode

Using var:

// Using var (not recommended in modern JavaScript)
var age = 25;
var name = "John";

// Variables declared with var are function-scoped
function exampleFunction() {
  var localVar = "I am a local variable";
  console.log(localVar);
}

exampleFunction();
console.log(localVar); // This will throw an error

Enter fullscreen mode Exit fullscreen mode

Using let:

// Using let
let age = 30;
let name = "Jane";

// Variables declared with let are block-scoped
if (true) {
  let blockVar = "I am a block-scoped variable";
  console.log(blockVar);
}

// This will throw an error
// console.log(blockVar);

Enter fullscreen mode Exit fullscreen mode

Using const:

// Using const
const pi = 3.14;

// Variables declared with const are block-scoped and cannot be reassigned
// This will throw an error
// pi = 3.14159;

const person = {
  name: "Alice",
  age: 28
};

// Properties of a const object can be modified
person.age = 29;
console.log(person); // Outputs: { name: 'Alice', age: 29 }

Enter fullscreen mode Exit fullscreen mode

summary

summary of variables

Personal Note:

I hope you find this guide helpful! It's a journey I embarked on while learning JavaScript myself, and I believe these fundamentals will serve as a solid foundation for your coding endeavors. Happy coding!

Top comments (0)