Your First Steps in JavaScript


Are you ready to deep dive into the world of web development, or I would say full-stack software engineering. You are in the right place, JavaScript is the language that adds life to the webpage.
Making websites interactive and dynamic, from animated menus to complex web applications running complex business logic behind the scenes.
This article is your friend if you want to start walking on the path of web development using JavaScript. We’ll explore the fundamental building blocks that every beginner needs to master. You’ll learn what variables are and how to use them, the different types of data you can work with, how operators help you change or compare data, and how to control what your program does using control flow statements like if-else and switch. By the end, you’ll have a strong foundation to start writing your own JavaScript code!
Understanding Variables and Data Types in JavaScript
Imagine you have lots of ingredients and spices in your kitchen, each stored in its own labeled container. In programming, variables are just like those labeled containers — they hold different pieces of information so you can use them whenever you need.
What are Variables? The "Boxes" for Your Data
A variable in JavaScript is a named storage that holds a value or some data. This value can change during the program execution - that’s why they are called variables.
In JavaScript, you declare (create) variables using keywords: var, let, and const.
Declaring and Assigning Values to Variables:
let message; // Declaring variable message = "Hello" // Assigning a value to variable // Declaring a variable named 'userName' and assigning it a string value let userName = "Hardik"; // Declaring a variable named 'userAge' and assigning it a number value const userAge = 24;
You might have noticed we used
let
andconst
in the examples above. These are the modern ways to create variables in JavaScript. Since the ES6 update, it is preferred to avoid usingvar
becauselet
andconst
. They are safer and easier due to how they handle the scope.
What is Scope?
Scope refers to where a variable is accessible within your code. Think of it like the jurisdiction of a law – a local ordinance applies only within a specific city, not the entire country.
Var (Function Scope) - Variables declared with var keyword are function scoped. This means they are accessible only within the function they are declared in. Regardless of block statements like (If and Loop). They also have a behaviour called hoisting, where variables and function declarations are moved to the top of their scope before code execution.which can sometimes lead to unexpected results for beginners.
function exampleVarScope() { if (true) { var x = 10; console.log("Inside if block (var):", x); // Output: Inside if block (var): 10 } console.log("Outside if block (var):", x); // Output: Outside if block (var): 10 (Accessible!) } exampleVarScope();
console.log(myVar); // Outputs: undefined (due to hoisting of 'var myVar') var myVar = 10; console.log(myVar); // Outputs:10
Let (Block Scope) - Let is the flexible choice of variable we know and expect the values can be changes in further execution. It's block-scoped, meaning it's only accessible within the block of code (defined by curly braces {}) where it's declared.This helps prevent accidental overwriting of variables and makes your code more predictable. Let variables cannot be accessed before initialization and this is scope before declaration is known temporal dead zone of that variable.
function exampleLetScope() { if (true) { let y = 20; console.log("Inside if block (let):", y); // Output: Inside if block (let): 20 } console.log("Outside if block (let):", y); // the line above would cause a ReferenceError,because 'y' is not accessible here. } exampleLetScope();
console.log(myLet); // Throws ReferenceError: Cannot access 'myLet' before initialization. let myLet = 20; console.log(myLet); // Outputs: 20
Const (Block Scope) - Variables declared using const are also block scoped, we use it for values that should not be reassigned once they are set.This makes your code more robust and readable, indicating that a particular value is meant to stay the same.
const PI = 3.14159; console.log(PI); // Output: 3.14159 PI = 3.0; // This would cause a TypeError: Assignment to constant variable.
Data Types: The Kinds of Information Variables Hold
Just like we took an example above for variable in which we talked about name containers to store spices and ingredients in your kitchen. In same way just think we are categorizing the containers that can store specific type of spices or ingredients (For example - different container to store oil, milk and any other liquid. And name them to identify what liquid is stored), Javascript has data types to categorize what kind of information a variable can hold.
Understanding data types is crucial because it dictates what operations you can perform on a value. Data Types are often divided into two types →
Primitive Data Types
Data Types which are predefined by the language, Javascript has 7 primitive Data Types -
String - Strings represents the textual data, we enclose strings into
single quotes(‘ ‘), double quotes(“ “) or backticks(` `).let firstName = "Hardik"; let message = "Welcome to JavaScript!"; let multiLine = `This is a multi-line string.`;
Number - Represents both integer and floating-point (decimal) numbers. For ex - Your age, the price of an item.
let age = 30; let productPrice = 29.99; let temperature = -5;
Boolean - Boolean is a logical data type that only have two values either True or False.
let isLoggedIn = true; let hasPermission = false;
Undefined - A variable that is declared but has to yet assigned a value automatically holds the value undefiend.
let myVariable; console.log(myVariable); // Output: undefined
Null - Represents the intentional absence of any object value. In simple terms it means empty.
let selectedProduct = null; // No product selected yet
BigInt - Used to create unique identifiers.
Symbol - For very large integer numbers that the standard Number type cannot represent accurately.
Non Primitive Data Types
User-defined data types such as Objects and Arrays are known a non-primitive data types.
Objects - Complex data types that store multiple values or a collection of data under the same variable name. Objects have key-value pairs where each key is a string and values can be any other data types
let person = { name: "John Doe", age: 45, Country: "New York", }; // Objects can have properties and methods let Car = { name: "BMW", // Properties TopSpeed: 200, Color: "Black", Accelerate: Accelerate = () => { // Methods console.log("Car is accelerating") } };
Array - Arrays are objects in JavaScript that store multiple data of the same type under the same variable name.
let arr1 = [1, 2, 4, 7] // array of numbers let fruits = ["Apple", "Orange", "Banana"] // array of strings
JavaScript Operators: The Basics You Need to Know
Once you have your data stored in variables, you'll want to do things with it: perform calculations, compare values, or combine expressions. This is where operators come in handy! Operators are special symbols that perform operations on one or more values (called operands). Think of them as the verbs of your programming sentences.
Assignment Operators: Used to assign values to variables.
let score = 100; // Assigns 100 to score score += 50; // score is now 150 (score = score + 50) score -= 20; // score is now 130 (score = score - 20)
Arithmetic Operators: Perform mathematical calculations.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (returns the remainder of a division)
** Exponential
let result = 10 + 5; // 15 let remainder = 17 % 5; // 2 (17 divided by 5 is 3 with a remainder of 2) let power = 4 ** 2; // 16 (4 squared)
Comparison Operators: Used to compare two values and return a Boolean (true or false) result. These are crucial for control flow.
\== Loose equality (checks if values are equal).
\=== Strict equality (checks if values are equal AND have the same type.
!= To check inequality.
< and > Greater than and Less than
>= Greater than or equal to.
<= Less than or equal to.
console.log(10 == '10'); // Output: true (loose equality, type coercion) console.log(10 === '10'); // Output: false (strict equality, different types) console.log(20 > 15); // Output: true console.log(7 <= 7); // Output: true
Logical Operators: Used to combine or modify Boolean expressions.
&& (AND): Returns true if both operands are true.
|| (OR): Returns true if at least one operand is true.
! (NOT): Reverses the boolean value of an operand (true becomes false, false becomes true).
let hasLicense = true; let isAdult = false; console.log(hasLicense && isAdult); // Output: false (Both must be true) console.log(hasLicense || isAdult); // Output: true (At least one is true) console.log(!hasLicense); // Output: false (Reverses true to false)
Control Flow in JavaScript: If, Else, and Switch Explained
In JavaScript, by default, the program executes from top to bottom. However, in the real world, applications need to make some decisions, this is when control flow statements kick in. These statements allow you to make decisions, repeat tasks and choose different paths to execute based on certain conditions.
If statement
If Statement executes a block of code when a certain condition is true.let isSunny = true; if (isSunny) { console.log("Don't forget your sunglasses!"); } // Output: Don't forget your sunglasses!
If … Else Statement
The if-else block provides us with an alternative block to execute if the condition is false.let temperature = 15; // Celsius if (temperature < 0) { console.log("It's freezing outside! Bundle up."); } else { console.log("It's not freezing, but still chilly."); } // Output: It's not freezing, but still chilly.
if...else if...else statement:
When you have multiple conditions to check in sequence, you chain the conditions with else if to be evaluated. The program will execute the first block, which is true, and skip the rest. If none is true, then it will execute the Else block.let score = 85; let grade; if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else if (score >= 60) { grade = "D"; } else { grade = "F"; } console.log("Your grade is:", grade); // Output: Your grade is: B
Switch Statement: Handling Multiple Fixed Choices
If you have multiple cases to evaluate for a single condition, and chaining multiple If Else statements doesn’t look clean. We use switch case statements.Switch → In this block, we write the condition to evaluate.
Case → Specific value to match against the expression.
Break → This statement terminates the switch case once the match is found. If we don’t use break, it will move ahead to the next condition to evaluate.
Default → Default case to execute when no match is found.
let dayOfWeek = "Wednesday";
let message;
switch (dayOfWeek) {
case "Monday":
message = "Ugh, start of the week.";
break;
case "Wednesday":
message = "Hump day! You're halfway there.";
break;
case "Friday":
message = "TGIF! Weekend is near!";
break;
default:
message = "It's just another day.";
}
console.log(message); // Output: Hump day! You're halfway there.
When to use switch vs. if/else if:
Use a switch case when you have a single expression that you want to compare against many discrete, constant values. It often makes the code more readable than a long if/else if chain in such scenarios.
Use if/else if for more complex conditional logic involving ranges, multiple conditions, or non-strict comparisons.
Conclusion
You've just completed a significant first step into the world of JavaScript! We've unpacked the core concepts that form the bedrock of almost every program.
Subscribe to my newsletter
Read articles from Hardik Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Hardik Kumar
Hardik Kumar
👨💻 Full Stack Developer | MERN & Beyond | Generative AI Enthusiast As a Full Stack Developer, I specialize in building modern, scalable web applications using the MERN stack and beyond. During my previous internship roles, I contributed to both frontend and backend development on real-world projects, working with technologies like React, Node.js, and microservices-based architectures. With a BTech in Computer Science, I’ve built a strong foundation in programming and software development. I'm passionate about continuous learning and personal growth — and I document my journey as I explore new technologies, sharpen my skills, and strive to become a better engineer every day.