Your First Javascript Tutorial: Variables, Declarations, and Headaches

Sangy KSangy K
6 min read

Ever labelled a box only to forget what's inside? πŸ˜…

Think of Javascript variables like labelled boxes. You shove things in, label them, and maybe even move them later. That's exactly what variables do in your code.

In this tutorial, we'll tackle:

  • What are variables in Javascript?

  • The difference between var, let, and const (and why var is kind of retired πŸ‘΄)

  • Naming conventions

  • How to declare, reassign, and use variables

  • Why is undefined not an error (usually)

Let's unpack these boxes, shall we?

πŸ“¦ What Are Variables in Javascript or any programming language?

Imagine you're packing for a move.

You put books in a box labelled "Books" Clothes in "Winter Clothes" Then, months later, you're like, 'What's in this box again?'

That label? That's a variable.

Simple Definition - Variables are containers that hold data.

For example,

let myLunch = "πŸ•";

Here, myLunch is the label, and the value is... well, delicious.

Variables are used to store a user's name, track game scores, hold fetched data from APIs, and temporarily store things like button clicks, etc

Without them, everything would be hard-coded and inflexible. Boring πŸ₯±.

✍️ Javascript Syntax Basics

Before we start working with variables, let's review the basic Javascript syntax.

Let's take the previous example,

let myLunch = "πŸ•";

Javascript is case-sensitive. myLunch β‰  MyLunch β‰  mylunch

The statements usually end with ; (not always required, but recommended)

Comments may be single-line or multi-line // single-line or /* multi-line */

That's it! That's how Javascript looksβ€”no heavy lifting required πŸͺ¨.

🏷️ Declaring Variables: var, let, and const

πŸ”Ή var β€” The Old School Keyword

var myName = "Alice";
var myAge;
myAge = 35;

var is the grandpa of Javascript keywords πŸ‘΄. Back in the early days, it was the way to declare variables, long before let and const emerged, looking all modern and responsible.

It's function-scoped and gets hoisted β€” meaning Javascript lifts it to the top of its function, but sneakily initialises it with undefined πŸͺ„.

We'll dive deeper into scoping and hoisting soon, so hang tight! πŸš€

For now, remember this little quirk: with var, you can use a variable before you actually declare it 🀯. And yep, that sometimes leads to some classic Javascript weirdness.

console.log(myName); // Used before declaration statement
var myName = "Alice";
console.log(myName);
myName = 50000; // Value re-assigned
console.log(myName);
var myName = true; // Re-declared again and used
console.log(myName);

In this example, Javascript hoists the myName variable to the top and initialises it with undefined πŸͺ„. That's why you see undefined when you try to access it before the var myName = "Alice" line runs.

Also, with var, you can reassign it and redeclare it in the same scope πŸ”„β€”and Javascript's totally fine with that. A few of Javascript's quirks come straight from this weirdly flexible behaviour πŸ€·β€β™‚οΈ.

Legacy codebase still uses var, and it still works today, but let's be honest: using var feels a bit like coding on a floppy disk when you've got cloud storage β˜οΈπŸ’Ύ.

πŸ”Ή let β€” The Flexible Friend

let myName = "Alice";
let myAge;
myAge = 35;

let is your modern go-to buddy πŸ§‘β€πŸ’» for declaring Javascript variables. Unlike var, it plays by smarter rules: it's block-scoped πŸ”’ and doesn't pull the hoisting tricks that var does.

Unlike var, you can't use a let variable before declaring it β€” try it, and Javascript will throw an angry error: 🚨 "Uncaught ReferenceError: Cannot access 'myName' before initialisation"

console.log(myName); // Used before declaration statement
let myName = "Alice";
// Error: 
// "Uncaught SyntaxError: Identifier 'myName' has already been declared"

One more thing β€” once you declare a variable with let, you can't redeclare it in the same scope 🚫. Javascript will throw a fit if you try.

And if you try to redeclare the same variable in the same scope, Javascript shuts you down with: 🚨 "Uncaught SyntaxError: Identifier 'myName' has already been declared"

let myName = "Alice";
console.log(myName);
myName = 50000; // Value re-assigned
console.log(myName);
let myName = false; // Re-declared again and used
console.log(myName);
// Error: 
// "Uncaught SyntaxError: Identifier 'myName' has already been declared"

Basically, let keeps things a little stricter (and cleaner) 🧹.

πŸ”Ή const β€” The Locked Box

const PI = 3.14;
const api_key = "dekjhv876fsdo";

const is your "immutable", "no take-backs" option πŸ›‘οΈ. Once you declare a variable with const, you can't reassign it later β€” what's done is done.

const api_key = "dasdjkf876dfhgd";
api_key = "Someother value"; // Throws - "Uncaught TypeError: Assignment to constant variable."

Like let, it's block-scoped πŸ”’, but with one key rule:

πŸ‘‰ You must assign it a value right away, or Javascript will complain loudly.

const api_key;
api_key = "dasdjkf876dfhgd"; //Throws - "Uncaught SyntaxError: Missing initialiser in const declaration "

❗A Quick Note:

const doesn't mean "immutable" or "locked-up" for your arrays or objects 🧊.

It just means the variable reference is locked πŸ”’, but you can still change the contents inside an array or object.

const myLunchMenu = ["briyani"];
console.log(myLunchMenu); // Ouput - ["briyani"]
myLunchMenu.push("Raita");
console.log(myLunchMenu); // Ouput - ["briyani", "Raita"]
myLunchMenu = "Salad"; // Throws - "Uncaught TypeError: Assignment to constant variable.

In the example above, we assigned an array to the const variable, and we can still add items to that array 🧺.

But here's the catch: you can't reassign the variable to a different value or a whole new array 🚫. The reference stays the same, even if the contents change.

Well, here is my opinion,πŸ”¨

Avoid var like it's ancient history 🏺.

Use const by default πŸ”’, and only use let when the value truly needs to change πŸ”„.

Most modern frameworks and developers follow this approach β€” it keeps your code clean, predictable, and bug-free (well, mostly) πŸ§Ήβœ….

🏷️ Variable Naming Rules & Best Practices

  • Use camelCase: firstName, totalPoints - Recommended, but not in the rule book.

  • Pick meaningful names: userInput, not x - Recommended, but not in the rule book.

  • Avoid reserved keywords (such as return, break, etc.).

🧼 Variable Initialisation and Default Values

Declaring vs Initialising

When you just name a variable without giving it a value, you're declaring it πŸ“.

let myName; // Declaration only

When you finally give it a value, that's called initialising the variable β€” or more casually, you're assigning a value to it πŸ”§.

myName = "Alice"; // Now it's initialised

With var and let, you can declare a variable first and assign a value later πŸ› οΈ.

But with const, it's all or nothing β€” you must assign a value when you declare it 🚨. No empty declarations allowed!

πŸ«™What is undefined?

If you declare a variable without assigning a value, Javascript automatically sets it to undefined πŸ€·β€β™‚οΈ.

let myName;
console.log(myName);

So... is undefined good or bad? Well, it's not bad, but it's not exactly great either. It just means, "Hey, this thing exists, but I haven't decided what it is yet."

And there you have it β€” variables, some quirks, and all. πŸ› οΈ Now, go and write some code, break some stuff, and let Javascript surprise you (it always does). πŸš€

0
Subscribe to my newsletter

Read articles from Sangy K directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sangy K
Sangy K

An Introvert Coder | Trying to be a Full-stack Developer | A Wannabe Content Creator