DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on • Updated on

JavaScript Key fundamentals Part - 2

4.Control Flow: Used to make decisions in code using if/else statements, switch statements and loops (for, while, do-while).
if statement: executes a block of code if a condition is true.


let num = 42;
if (num > 40) {
  console.log("The number is greater than 40");
}

Enter fullscreen mode Exit fullscreen mode

if-else statement: executes a block of code if a condition is true, and another block of code if the condition is false.

let num = 42;
if (num > 50) {
  console.log("The number is greater than 50");
} else {
  console.log("The number is less than or equal to 50");
}
Enter fullscreen mode Exit fullscreen mode

switch statement: selects one of many blocks of code to be executed.

let day = "Monday";
switch (day) {
  case "Monday":
    console.log("Today is Monday");
    break;
  case "Tuesday":
    console.log("Today is Tuesday");
    break;
  default:
    console.log("Today is not Monday or Tuesday");
}

Enter fullscreen mode Exit fullscreen mode

for loop: executes a block of code a specified number of times.

for (let i = 0; i < 5; i++) {
  console.log("The value of i is:", i);
}

Enter fullscreen mode Exit fullscreen mode

while loop: executes a block of code while a condition is true.

let i = 0;
while (i < 5) {
  console.log("The value of i is:", i);
  i++;
}

Enter fullscreen mode Exit fullscreen mode

5.Functions: Reusable blocks of code that can accept parameters and return values.

function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Vamshi"));  // Output: Hello, Vamshi

Enter fullscreen mode Exit fullscreen mode

In this example, greet is a function that takes a parameter name and returns a string "Hello, " concatenated with the value of name. The function is called with the argument "Vamshi", and the returned value is logged to the console.

function add(a, b) {
  return a + b;
}

console.log(add(2, 3));  // Output: 5

Enter fullscreen mode Exit fullscreen mode

In this example, add is a function that takes two parameters a and b, and returns the sum of their values. The function is called with arguments 2 and 3, and the returned value 5 is logged to the console.

Top comments (0)