Mastering JavaScript Basics: Your Essential Day 1 Guide

Mastering JavaScript Basics: Your Essential Day 1 Guide

Learn JavaScript Fundamentals, Variables, Data Types, and Control Structures for a Strong Foundation in Web Development

I remember being super confused about how to start learning Javascript to embark on my journey of web development. There were countless guides, sources, and tutorials, but a layout that could help me master the fundamentals and advanced concepts wasn't the one I could find out there; it ended up being something that I curated myself and went on a mission to unravel the intricacies of this dynamic programming language. Whether you're a seasoned developer seeking to deepen your skills or a curious newcomer eager to dive into the realms of web development, this series of "JavaScript Mastery in 15 Days" is designed to empower you with the knowledge and confidence to master JavaScript.

This can be your passport to the world of web interactivity and creativity. JavaScript is the driving force behind the magic you see on your favorite websites, from dynamic user interfaces to engaging animations. So, whether you're driven by the desire to excel in interviews, build your projects, or simply satisfy your curiosity, this series has got your back.


Let's start this with the outline of today's mission:

  • Introduction to Javascript

  • Understanding Variables and their importance

  • Different Data Types in Javascript

  • Navigating Operators

  • Building a strong foundation with Control Structures

    (Conditional Statements and Looping Constructs)

  • Real-world examples to solidify concepts

  • Teaser for our next mission


Introduction to Javascript

Every time a web page does more than just sit there and display static information for you to look at—displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, or more—you can bet that JavaScript is probably involved.

-MDN web docs__

JavaScript is a cross-platform, OOP language that brings life to websites and makes them interactive. Imagine a static website—it just sits there looking pretty. But when you add JavaScript to the mix, suddenly buttons can be clicked, images can change, forms can validate, and all sorts of cool things can happen in response to user actions.

Javascript can be extended for various purposes according to how you want to implement it on a website. Mainly, we extend it to:

  • Client-Side Javascript handles user interactions, like when you click a button and a pop-up appears.

  • Server-Side Javascript performs calculations, manipulates data, and even makes your webpage talk to a server to fetch information.

Now, imagine your webpage or website as a hamburger. HTML is the bread—it structures the content and elements of your webpage. CSS is like the sauce and toppings—it makes things look nice and pretty. And guess what? JavaScript is like the ham that gives your burger flavor and makes it exciting.

💡
Javascript and Java are two different languages. To learn more about the difference between them, click here.

We can place our Javascript code in an HTML file in three ways:

  1. Inside the Body Tag:
<body>
This is our script!
<script type="text/javascript">
document.write("This is  the script content.")
</script>
</body>
  1. Inside the Head Tag:

     <html>
     <head>
     <script type="text/javascript">
     document.write("This generates an alert msg.");
     funtion alertmsg(){
         alert("Go and study Javascript!");
     }
     </script>
     </head>
     <body>
     <form><input type="button" value="click" onclick="msg()"/></form>
     </body>
     </html>
    
  2. Embedding the external .js file:

<!--index.html-->
<body>
this page uses an external javascript file.
<script src="script.js"></script>
</body>
//script.js
function msg(){  
 alert("This is an external file.");  
}

Understanding Variables and their importance

Variables serve as foundational components that play a crucial role in storing and managing data. For example, if you are designing a platform that offers personalized greetings, the user's name must be captured and stored for later use. Variables facilitate this process by allowing developers to store the user's name in a designated variable, which can then be employed to generate tailored greetings and messages.

They can be declared using the var, let, and const keywords.

//declaring a variable
let yourname;
//assigning value to the variable
yourname = "Elsa";
//assigning value while declaring the variable
let yourname = "Dave";
//const example
const pi = 3.14159;
💡
Historically, var was widely used to declare variables. However, it has some scoping quirks that can lead to unexpected behavior. Variables declared with var are function-scoped or globally-scoped, regardless of where they are declared in a function. This can sometimes result in unintended variable hoisting.

Different Data Types in JS

  1. Primitive Data Types (allows you to store only single data type values):

The 7 data types in Javascript are as follows-

  • String

      var str = "Javascript"; //double quotes
      var str2 = "Brendan Eich";
      var str3 = '1995'; //single quotes
    
  • Number

var x = 3; //without decimal
var y = 9.536; //with decimal
  • BigInt (*for a number greater than the limitation of the number of data types)*
var bigint_example = 3576493096730572333;
  • Boolean (logical entity; gives True or False)
var a = 2;
var b = 4;
var c = 2;
(a == b)      //returns false
(a == c)      //returns true
  • Undefined (variable declared but not assigned a value)
var x;                  //value of x is not defined
var y = undefined;      //value can be set as undefined too
  • Null (non-existent or invalid value)
var z = null;
  • Symbol (new data type introduced in the ES6 version, can be used to store an anonymous and unique value)
var symb1 = Symbol('symbol');
  1. Non-Primitive Data Types (stores multiple and complex values):
  • Object (used to store collection of data)
//collection of data as an ordered list
var array1 = [1995, 'Brendan Eich', True, 6.3];

//collection of data in key-value pairs
var obj_example = {
    x : 43,
    y : "Brendan Eich",
    z : function(){
            return this.x;
        }
}
💡
Any data type that is not primitive, is of non-primitive (object) type in JS.

Navigating Operators

I am assuming that you have a basic idea about operators and their types, and I don't need to write anything extensive about it. However, if you want to have a quick read, click here.

Look at this table for a grasp of operators in JS:


Control Structures

Control structures serve as indispensable tools for managing the flow of code execution. Within JavaScript, the control structures – specifically conditional statements and looping constructs – are pivotal for crafting dynamic and responsive applications.

Conditional Statements

if, else if, else :

Conditional statements provide the means to execute different code blocks based on specified conditions. The cornerstone of conditional statements is the if statement, which evaluates a condition and, if true, executes a particular code block.

The else if statement allows for the evaluation of additional conditions if the preceding conditions are false. Finally, the else statement executes a code block when none of the preceding conditions are met.

let year = 2024;

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
  console.log(year + " is a leap year.");
} else {
  console.log(year + " is not a leap year.");
}

Looping Constructs

for, while, do...while:

Looping constructs enable the repeated execution of code blocks, allowing for efficient automation of tasks. JavaScript offers three primary types of loops: for, while, and do...while.

The for loop iterates over a specific range of values based on defined initialization, condition, and increment components.

The while loop executes a code block as long as a given condition holds true. The condition is evaluated before each iteration.

The do...while loop is similar to the while loop, but it ensures that the code block is executed at least once, even if the condition is initially false.

// Using a for loop to print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// Using a while loop to print even numbers from 2 to 10
let num = 2;
while (num <= 10) {
  console.log(num);
  num += 2;
}

// Using a do...while loop to get user input until a valid age is entered
let userAge;
do {
  userAge = parseInt(prompt("Enter your age:"));
} while (isNaN(userAge) || userAge <= 0);

Here is a program that generates a Fibonacci series by using for loop.

let fibonacciSeries = [0, 1];
let seriesLength = 10;
for (let i = 2; i < seriesLength; i++) {
  let nextNumber = fibonacciSeries[i - 1] + fibonacciSeries[i - 2];
  fibonacciSeries.push(nextNumber);
}
console.log("Fibonacci series:", fibonacciSeries);
💡
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

As we continue our voyage towards JavaScript proficiency, mastering these control structures will undoubtedly enrich your coding skills.


Real-world examples to solidify concepts

  • Understanding Variables and Their Importance:

    Real-World Example: Online Shopping Cart

Imagine you're developing an e-commerce website. Each user has a shopping cart where they can add items. Here, variables come into play. You'd use variables to store the user's name, selected items, their quantities, and the total cost. This enables seamless interaction as users add, remove, and purchase items.

  • Exploring Different Data Types in JavaScript:

    Real-World Example: Social Media Profile

Think of a scenario where you're building a social media platform. User profiles contain a mix of data types – names (strings), ages (numbers), account statuses (booleans), and even profile pictures (objects). Each data type serves a specific purpose, contributing to a rich and diverse user experience.

  • Navigating Operators:

    Real-World Example: Calculator App

How about this? You're designing a calculator app where users input numbers and perform operations like addition, subtraction, multiplication, and division. Here, arithmetic operators (+, -, *, /) come into play to perform the calculations. Additionally, you might use comparison operators to validate user inputs and ensure accurate calculations.

  • Control Structures:

    1. if, else if, else

      Real-World Example: Weather App

Suppose you're creating a weather app that provides recommendations based on the forecast. If the temperature is high, the app might suggest wearing light clothing. If it's raining, it could advise taking an umbrella. Here, conditional statements (if, else if, else) help tailor the app's responses based on varying weather conditions.

  1. for, while, do...while

    Real-World Example: Task Scheduler

Consider a task scheduler application. You want to display tasks due for the day. Instead of manually printing each task, a loop (for, while, or do...while) helps you iterate through the tasks and display them systematically. This ensures that your application handles multiple tasks efficiently.

You can try building these above-mentioned examples as your extra-curricular mini-projects as you advance through!

These real-world examples demonstrate how the concepts of variables, data types, operators, and control structures are applied to create practical and functional JavaScript applications.


You've just taken your first steps into the coding cosmos, and guess what? Day 2 is going to be a wild ride. We're diving headfirst into the enchanting world of functions – those super-smart, do-it-all code wizards!

Get ready to witness the awesomeness of functions – the ultimate tools for keeping your code tidy and your life as a coder so much easier. We'll be cooking up functions like a masterchef, exploring how to create them, make them work their magic, and understand their hidden powers.

So, Stay tuned for Day 2 to take your JavaScript skills to the next level and buckle up for a day of discovery, where we're unraveling the mysteries of functions. These bad boys are all about making your code snazzy, reusable, and slick as a whistle. You're in for a treat!

Stay curious and keep that coding fire burning!

Catch you on the flip side,

Aparna


Connect with me on LinkedIn and Hashnode for more upcoming insights and coding intricacies.