Fundamentals of Javascript

Photo by Growtika on Unsplash

Fundamentals of Javascript

·

10 min read

If else Conditionals

The "if" statement in JavaScript executes a block of code if a specific condition is met. The "else" clause is used to execute a block of code if the condition is not met.

Here is the basic syntax for an "if" statement:

if (condition) {
  // code to be executed if condition is true
}

Here is the syntax for an "if" statement with an "else" clause:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

The condition is a boolean expression that evaluates to either true or false. If the condition is true, the code in the "if" block is executed. If the condition is false, the code in the "else" block is executed (if present).

For example:

let x = 10;
if (x > 5) {
  console.log("x is greater than 5");
} else {
  console.log("x is not greater than 5");
}

In this example, the condition "x > 5" is true, so the code in the "if" block is executed and the message "x is greater than 5" is printed to the console.

If else ladder

The "if-else ladder" is a control structure in JavaScript that allows you to execute a different block of code depending on multiple conditions. It is called a ladder because it consists of multiple "if" and "else" statements arranged in a ladder-like fashion.

Here is the syntax for an "if-else ladder":

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
  // code to be executed if condition1 and condition2 are false and condition3 is true
} ...
else {
  // code to be executed if all conditions are false
}

In this structure, each "if" and optional "else" statement follows the statement. If the first "if" condition is true, the code in the corresponding block is executed and the rest of the ladder is skipped. If the first "if" condition is false, the second "if" condition is evaluated, and so on. If none of the conditions is true, the code in the "else" block is executed.

For example:

let x = 10;
if (x > 15) {
  console.log("x is greater than 15");
} else if (x > 10) {
  console.log("x is greater than 10 but less than or equal to 15");
} else if (x > 5) {
  console.log("x is greater than 5 but less than or equal to 10");
} else {
  console.log("x is less than or equal to 5");
}

In this example, the first "if" condition "x > 15" is false, so the second "if" condition "x > 10" is evaluated. This condition is also false, so the third "if" condition "x > 5" is evaluated. This condition is true, so the code in the corresponding block is executed and the message "x is greater than 5 but less than or equal to 10" is printed to the console.

The "if-else ladder" is a useful control structure for executing different blocks of code based on multiple conditions. It can help you write more concise and maintainable code in JavaScript.

Switch case

The "switch" statement in JavaScript is another control structure that allows you to execute a different block of code depending on a specific value. It is often used as an alternative to the "if-else ladder" when you have multiple conditions to check against a single value.

Here is the syntax for a "switch" statement:

switch (expression) {
  case value1:
    // code to be executed if expression == value1
    break;
  case value2:
    // code to be executed if expression == value2
    break;
  ...
  default:
    // code to be executed if expression does not match any of the values
}

In this structure, the "expression" is evaluated and compared to each of the "case" values. If the "expression" matches a "case" value, the corresponding block of code is executed. The "break" statement is used to exit the "switch" statement and prevent the code in the following cases from being executed. The "default" case is optional and is executed if the "expression" does not match any of the "case" values.

For example:

let x = "apple";
switch (x) {
  case "apple":
    console.log("x is an apple");
    break;
  case "banana":
    console.log("x is a banana");
    break;
  case "orange":
    console.log("x is an orange");
    break;
  default:
    console.log("x is something else");
}

In this example, the "expression" is the variable "x," which has the value "apple." The "expression" is compared to each of the "case" values, and when it matches the value "apple," the corresponding block of code is executed and the message "x is an apple" is printed to the console.

The "switch" statement is a useful control structure for executing different blocks of code based on a specific value. It can help you write more concise and maintainable code in JavaScript.

Ternary Operator

The ternary operator is a shorthand way to write an if-else statement in JavaScript. It takes the form of condition ? value1 : value2, where condition is a boolean expression, and value1 and value2 are expressions of any type. If condition is true, the ternary operator returns value1; if condition is false, it returns value2.

Here's an example of how you can use the ternary operator to assign a value to a variable based on a condition:

let x = 10;
let y = 20;
let max;

max = (x > y) ? x : y;

console.log(max); // Outputs: 20

In this example, the ternary operator checks whether x is greater than y. If it is, max is assigned the value of x; otherwise, it is assigned the value of y.

The ternary operator can be a useful and concise way to write simple if-else statements, but it can become difficult to read and understand when used for more complex statements or nested inside other expressions. In these cases, it may be better to use a regular if-else statement instead.

For Loops

Loops are a common control flow structure in programming that allows you to repeat a block of code a specific number of times. In JavaScript, there are three types of for loops: the standard for loop, the for-in loop, and the for-of loop.

Standard for loop

The standard for loop has the following syntax:

for (initialization; condition; increment/decrement) {
  // code to be executed
}

The initialization the statement is executed before the loop starts and is typically used to initialize a counter variable. The condition is checked at the beginning of each iteration and if it is true, the loop continues. If it is false, the loop exits. The increment/decrement statement is executed at the end of each iteration and is used to update the counter variable.

Here's an example of a standard for loop that counts from 1 to 10:

for (let i = 1; i <= 10; i++) {
  console.log(i);
}

This loop will print the numbers 1 through 10 to the console.

For-in loop

The for-in loop is used to iterate over the properties of an object. It has the following syntax:

for (variable in object) {
  // code to be executed
}

The variable is assigned the name of each property in the object as the loop iterates over them.

Here's an example of a for-in loop that iterates over the properties of an object:

let person = {
  name: "John",
  age: 30,
  job: "developer"
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}

This loop will print the following to the console:

name: John
age: 30
job: developer

For-of loop

The for-of loop is used to iterate over the values of an iterable object, such as an array or a string. It has the following syntax:

for (variable of object) {
  // code to be executed
}

The variable is assigned the value of each element in the object as the loop iterates over them.

Here's an example of a for-of loop that iterates over the elements of an array:

let numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
  console.log(number);
}

This loop will print the numbers 1 through 5 to the console.

For loops are a powerful tool in JavaScript and can be used to perform a variety of tasks, such as iterating over arrays and objects, repeating a block of code a specific number of times, and more. With the three types of for loops available in JavaScript, you can choose the one that best fits your needs and use it to write more efficient and effective code.

While Loop

While loops are a control flow structure in programming that allows you to repeat a block of code while a certain condition is true. In JavaScript, the syntax for a while loop is:

while (condition) {
  // code to be executed
}

The condition is checked at the beginning of each iteration and if it is true, the code block is executed. If it is false, the loop exits.

Here's an example of a while loop that counts from 1 to 10:

let i = 1;

while (i <= 10) {
  console.log(i);
  i++;
}

This loop will print the numbers 1 through 10 to the console.

It's important to include a way to update the condition within the loop, otherwise, it will become an infinite loop and will run forever. In the example above, the i++ statement increments the value of i by 1 at the end of each iteration, which eventually causes the condition to be false and the loop to exit.

While loops can be useful when you don't know exactly how many times you need to execute a block of code. For example, you might use a while loop to keep prompting a user for input until they provide a valid response.

let input = "";

while (input !== "yes" && input !== "no") {
  input = prompt("Please enter 'yes' or 'no':");
}

This loop will keep prompting the user for input until they enter either "yes" or "no".

While loops can be a useful tool in JavaScript, it's important to use them with caution. If the condition is never met, the loop will become an infinite loop and will run forever. Make sure to include a way to update the condition and eventually exit the loop to avoid this issue.

Functions

JavaScript functions are blocks of code that can be defined and executed whenever needed. They are a crucial part of JavaScript programming and are used to perform specific tasks or actions.

Functions are often referred to as "first-class citizens" in JavaScript because they can be treated like any other value. In other words, you can assign them to variables, pass them as arguments, and return them as values.

Here's the basic syntax for defining a function in JavaScript:

function functionName(parameters) {
  // code to be executed
}

The functionName is a unique identifier, while a parameters is a variable passed to a function upon its call. During execution, these parameters act as placeholders for the actual values passed to functions.

Here's an example of a simple function that takes a single parameter and returns the square of that number:

function square(x) {
  return x * x;
}

To call this function, you would simply use the function name followed by the arguments in parentheses:

let result = square(5);  // returns 25

Functions can also have multiple parameters, like this:

function add(x, y) {
  return x + y;
}

In this case, the add function takes two parameters, x and y, and returns their sum.

JavaScript also has a special type of function called an "arrow function," which uses a shorter syntax. Here's the same square a function defined using an arrow function:

const square = (x) => {
  return x * x;
};

Arrow functions are often used when you want to create a small, one-line function that doesn't require a separate function keyword.

Functions can be defined inside other functions, which is known as "nesting." This is useful for creating smaller, reusable blocks of code that can be called from within the larger function.

function outerFunction(x) {
  function innerFunction() {
    // code to be executed
  }
  // more code
}

In this example, the innerFunction is defined inside the outerFunction and can only be called from within that function.

In addition to these basic concepts, there are many other things you can do with functions in JavaScript, such as passing functions as arguments, creating anonymous functions, and using higher-order functions. These advanced techniques can make your code more efficient and flexible, and are essential tools for any JavaScript developer.

Thank you for reading about the Fundamentals of Javascript. I hope you found the information helpful. If you have any questions or comments, please don't hesitate to let me know. Thanks again for your time!

Did you find this article valuable?

Support Samridhi Vashisht by becoming a sponsor. Any amount is appreciated!