Skip to main content

Command Palette

Search for a command to run...

JavaScript: From beginner to Mastery

Updated
11 min readView as Markdown
JavaScript: From beginner to Mastery
O

Software Engineer. Nodejs👽 || Doing Web3 on the side. 🏌️‍♂️

What is javascript? JavaScript is a programming language used for building interactive and dynamic web applications, it can be used on the client side(what users can see) and the server side(users can't see). It allows functionality and behavior to web pages. It's the language of the web.

In this article, we'd be going through the basic and essential topics to become a proficient JavaScript developer.

Are you ready? Let's dive right into it.

Data types

There are two main data types in javascript which are;

  • Primitive and non-primitive data types:

    In this tutorial, we'd focus on primitive data types as it's beginner friendly.

    Number: Represents both integer and floating-point numbers.

// Integer Example
let intValue = 90;
console.log(intValue); // Output: 90

// Floating-Point Example
let floatValue = 20.4;
console.log(floatValue); // Output: 20.4

String: Represents sequences of characters (text) wrapped in a quote.

// String Example
let greeting = "Hello, World!";
console.log(greeting); // Output: Hello, World!
//Hello World is wrapped in a quote to identify it as a string

Boolean: Represents true or false values.

// Boolean Examples
let isRaining = true;
let isSunny = false;

console.log(isRaining); // Output: true
console.log(isSunny);   // Output: false

Undefined: Represents a variable that has been declared but not assigned a value.

// Undefined Example
let someVariable; // Declaring a variable without assigning a value
console.log(someVariable); // Output: undefined

Variables

In programming, variables are essential concepts. They are used to hold and store data values. Variables can hold different data types such as numbers(int and float), boolean, string e.t.c To create a variable in JavaScript, you use the let, const, or var keywords.

The let keyword allows you to create a variable that can be reassigned later.

let age = 30; // Declare a variable called "age" and assign the value 30 to it.

The const keyword creates a constant variable whose value cannot be reassigned.

const greet = "hello"; // Declare a constant variable called greet and assign the value "hello" to it.

The var (older way, discouraged to use in modern code): Similar to let, but has some differences in scoping rules.

var name = "John"; // Declare a variable called "name" and assign the value "John" to it.

Basic Operators

Operators in javascript allow one to perform various mathematical operations. Which are;

• Addition (+)

• Subtraction (-)

• Multiplication (*)

• Division (/)

• Modulo (returns the remainder of a division (%)

let num1 = 10;
let num2 = 5;

// Addition
let sum = num1 + num2;
console.log("Sum:", sum); // Output: 15

// Subtraction
let difference = num1 - num2;
console.log("Difference:", difference); // Output: 5

// Multiplication
let product = num1 * num2;
console.log("Product:", product); // Output: 50

// Division
let quotient = num1 / num2;
console.log("Quotient:", quotient); // Output: 2

// Modulo (Remainder)
let remainder = num1 % num2;
console.log("Remainder:", remainder); // Output: 0

// Exponentiation (ES6 and later)
let exponentiation = num1 ** num2;
console.log("Exponentiation:", exponentiation); // Output: 100000

Conditional Statement

Conditional statements in JavaScript are used to make decisions in your code based on specific conditions. They allow your program to execute different blocks of code depending on whether a given condition is true or false.

We have the if and else statements to make decisions.

if statement:

The if statement is used to execute a block of code if a specified condition evaluates to true.

let x = 12;
if (x > 6) {
  console.log("x is greater than 6.");
}
//This is said to be true because 12 is greater than 6

else statement:

The else statement executes the remaining part of the code is false.

if...else statement:

The if...else statement is used to execute one block of code if the condition is true and another block if the condition is false.

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

//The first line of code is said to be true because 18 is not greater than 18 but 18 is equal to 18
//While the else is false because 18 is not a minor

Type Conversion / Coercion

Type conversion is the process of converting a value from one data type to another using JavaScript built-in functions or methods. It allows you to change the representation of a value temporarily.

// String to Number
let numString = "42";
let number = Number(numString);

// Number to String
let num = 42;
let strNumber = String(num);

Type coercion, is the process of converting a value to another data type automatically, typically during operations between different data types. For example, the string "10" can be automatically coerced to the number 10.

Truthy & Falsy Value

Truthy and falsy values refer to the values that are treated as either "true" or "false" when evaluated in a boolean context, such as conditions in if statements

if ('true') {
    console.log("This will be printed.");
}

if ('false') {
    console.log("This will not be printed");
}

Equality Operator

Equality operators are used to compare values. It could be booleans, numbers, or strings. e.t.c There are two main equality operators in javascript which are: Loose equality ("==") and the strict equality operator("==="). They could be used interchangeably, but it's great to use the strict operator in most instances to avoid errors.

Loose Equality (==): It tries to convert the values to the same type before making the comparison. The loose equality operator compares values for equality after performing type coercion.

console.log(10 == '10'); 
// true (number 10 is coerced to string '10' before comparison)

console.log(true == 1)
// true (boolean true is coerced to Number 1) It convert before comparison.

Strict Equality (===): It checks both the values and their data types. The strict equality operator compares values for equality without performing type coercion.

console.log(2 === '2'); 
// false (number 2 is not coerced to string '2' before comparison). It's 
// strict on comaprison.

console.log(true === 1)
// false (boolean true is not coerced to Number 1) It does not convert before comparison.

Another thing to look at is the inequality operator. It's also very important when comparing two values.

Inequality (!=): It checks both the values and their data types. The strict equality operator compares values for equality without performing type coercion. It checks if one of the values is false without performing type coercion.

console.log(true != 2) 
// false (boolean true is not true to number 2)

Boolean Logic

Another very important concept in javascript is the boolean logic. It is the use of logical operators. AND, OR, and NOT to manipulate and combine boolean values (true or false) in order to make decisions.

AND Operator (&&):

The && operator returns true if both operands are true, otherwise, it returns false.

The tabular representation gives more explanation to the AND operator.

ANDTRUEFALSE
TRUETRUEFALSE
FALSEFALSEFALSE

OR Operator(||):

The || operator returns true if at least one of the operands is true. If both operands are false, it returns false.

The tabular representation gives more explanation to the OR operator.

ORTRUEFALSE
TRUETRUETRUE
FALSETRUEFALSE

NOT Operator(!): The ! operator can also be called the reverse operator. It returns the opposite of the boolean value. If the operand is true, ! returns false, and if the operand is false, ! returns true.

The Switch Statement

Writing the if statement (conditional statement is cool), until the codebase becomes large and it becomes very hard to maintain. That's where the switch statement comes in. It provides an alternative way to write multiple if and else statements when you need to write an expression against multiple cases.

Here's an example of a switch statement:

const day = 3;
const dayName;

switch (day) {
    case 1:
        dayName = "Sunday";
        break;
    case 2:
        dayName = "Monday";
        break;
    case 3:
        dayName = "Tuesday";
        break;
    case 4:
        dayName = "Wednesday";
        break;
    case 5:
        dayName = "Thursday";
        break;
    case 6:
        dayName = "Friday";
        break;
    case 7:
        dayName = "Saturday";
        break;
    default:
        dayName = "Invalid day";
}

console.log(`Today is ${dayName}`);

the switch statement evaluates the day variable and executes the code block corresponding to the matched case. If no case matches, the default block is executed. The break function is used to exit a switch block if the case is match, if omitted, other blocks continue to run till the last block. While the default function provides a code block to execute when no cases match the expression.

Ternary Operator

The ternary is also a conditional statement, it is used to execute one line of a condition in a program.

Here's an example of a ternary operator:

condition ? value_if_true : value_if_false;
const age = 20;
const message = age >= 18 ? "You are an adult" : "You are not an adult";
console.log(message);

if the age is greater than or equal to 18, the variable message will be assigned the string "You are an adult", otherwise, it will be assigned the string "You are not an adult". Ternary is used to express shorthand and simple conditions.

Functions

They are one of the most essential concepts in javascript. they are also fundamental building block of JavaScript programming, and they allow you to write reusable and modular code. They can be called, invoke or run in the program. There are three ways to write function:

Function Declaration:

It involves specifying the function's name, parameters (if any), and the code that will be executed when the function is called.

function functionName(parameters) {
    // Function body (code to be executed)
    // ...
    return result; // Optional: Return a value
}
  • function keyword: This keyword is used to declare a function.

  • functionName: This is the name you give to your function. It must be a valid identifier.

  • parameters: These are placeholders for values that you can pass into the function when you call it. They're like variables that the function can use inside its body.

  • Function body: This is the actual code that the function executes when it's called.

  • return: This keyword is used to specify the value that the function should return. Not all functions need to return a value, and if omitted, the function returns undefined.

Let's look at a very good example:

function greet(name) {
    return `Hello ${name}`;
}

const message = greet("Israel"); //Calling , invoking or running the function
console.log(message); // Output: Hello, Israel!

Function Expression

It involves assigning a function to a variable. It means you have to define the function before using it.

const functionName = function(parameters) {
    // Function body (code to be executed)
    // ...
    return result; // Optional: Return a value
};


//Example
const calcAge = function(birthYear) {
    return 2037 - birthYear
}
console.log(calcAge(1991));

// calcAge is the variable holding the function
// birthYear is the parameter
// return use to specify the value that should be return

It's similar to function declaration, but it has to be assigned to a variable.

Arrow Function

is a concise way to write function expressions in JavaScript. Arrow functions provide a more compact syntax for creating functions, especially when the function body is a single expression.

const functionName = (parameters) => {
    // Function body (code to be executed)
    return result; // Optional: Return a value
};

//Example
const yearsRetire = birthYear => {
    const age = 2037 - birthYear;
    const retirement = 65 - age;
    return retirement;

}
console.log(yearsRetire(1991));

// yearsRetire is the variable holding the function
// birthYear is the parameter
// return use to specify the value that should be return
// => is also called a fat arrow

Arrow functions are often used for short, concise functions where the context of this is important or when you want to keep your code clean and readable.

Arrays

Arrays are data structures. They are used to hold collections of data, such as a list of numbers, strings, objects, or even other arrays. Each element in an array has an index, starting from 0 for the first element.

const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange"];
const strings = ["Hello", "Welcome", "Good"];

Arrays in JavaScript can contain elements of different data types, and the elements can be accessed and manipulated using their index. There are many key concepts related to arrays:

  • Nested Arrays

  • Array Indexing

  • Array Length

  • Array Method

Loops

control structures that allow you to execute a block of code repeatedly as long as a certain condition is met. Loops are essential for automating repetitive tasks and iterating over collections of data, such as arrays or object properties. There ate two main loop in javascript, which is the for loop and while loops.

For Loop : The for loop is used to execute a block of code a specific number of times. It consists of an initialization, a condition, and an increment or decrement expression.

for (let i = 0; i < 3; i++) {
    console.log(i); // Outputs 0, 1, 2
}

`Whileloop: The while loop repeatedly executes a block of code as long as a given condition remains true.

let i = 0;
while (i < 5) {
    console.log(i); // Outputs 0, 1, 2, 3, 4
    i++;
}

Thank You

That will be all guys for this tutorial. I hope have been able to impact knowledge into you with this courses. Thank you for reading to the end. I hope this will help you become a proficient javascript engineer. Don't stop learning to keep getting better. I'm rooting for you💯

Made with ❤ by Israel