Control flow refers to the order in which your code runs. Normally, JavaScript reads and runs code from top to bottom. But with control structures like conditionals, you can change that order based on certain conditions.
if (5 > 3) { console.log('5 is greater than 3'); } else { console.log('This won't run'); } // Output: 5 is greater than 3
The OR operator (||) is used in conditions to check if at least one of the conditions is true. If one or both conditions are true, the whole statement returns true.
let isWeekend = false; let isHoliday = true; if (isWeekend || isHoliday) { console.log('You can relax!'); } else { console.log('Time to work!'); } // Output: You can relax!
The ternary operator is a shorthand way to write an if-else statement. It takes a condition followed by a question mark (?), then the code for the true case, a colon (:), and finally the code for the false case.
let isMember = true; let discount = isMember ? '10%' : '0%'; console.log(discount); // Output: 10%
The AND operator (&&) checks if both conditions are true. If both are true, the whole statement returns true. If one or both are false, it returns false.
let hasTicket = true; let isSeatAvailable = true; if (hasTicket && isSeatAvailable) { console.log('You can enter the event.'); } else { console.log('Sorry, you cannot enter.'); } // Output: You can enter the event.
An if statement checks a condition and runs the code inside it if the condition is true. If it's false, the code inside the else block runs (if there's an else block).
let temperature = 30; if (temperature > 25) { console.log("It's hot outside!"); } else { console.log("It's cool outside."); } // Output: It's hot outside!
The switch statement is used to perform different actions based on different conditions. It's useful when you have many conditions to check.
let fruit = 'apple'; switch (fruit) { case 'banana': console.log('Bananas are great!'); break; case 'apple': console.log('An apple a day keeps the doctor away.'); break; default: console.log('Enjoy your fruit!'); } // Output: An apple a day keeps the doctor away.
The NOT operator (!) is used to reverse the value of a condition. If something is true, ! makes it false, and vice versa.
let isRaining = false; if (!isRaining) { console.log('It\'s not raining, enjoy your day!'); } // Output: It\'s not raining, enjoy your day!
Comparison operators like >, <, >=, <=, and === are used to compare values. These operators return true or false based on the comparison.
let age = 18; if (age >= 18) { console.log('You are an adult.'); } else { console.log('You are a minor.'); } // Output: You are an adult.
The else if statement allows you to check multiple conditions. If the first if condition is false, the next else if condition is checked, and so on.
let timeOfDay = 'afternoon'; if (timeOfDay === 'morning') { console.log('Good morning!'); } else if (timeOfDay === 'afternoon') { console.log('Good afternoon!'); } else { console.log('Good evening!'); } // Output: Good afternoon!
In JavaScript, values that are considered true in a Boolean context are called truthy, and those that are considered false are called falsy. Examples of falsy values include 0, '', null, undefined, NaN, and false.
let username = ''; if (username) { console.log('Welcome, ' + username); } else { console.log('No username provided'); } // Output: No username provided
A function is a block of code designed to perform a particular task. Functions help organize your code and make it reusable. You can define a function and call it whenever you need it.
function greet() { console.log('Hello, World!'); } greet(); // Output: Hello, World!
Arrow functions are a shorter way to write functions in JavaScript. They were introduced in ES6 and use a => symbol.
const add = (a, b) => a + b; console.log(add(2, 3)); // Output: 5
Parameters are placeholders in functions that allow you to pass values into the function. You can use these values inside the function to perform tasks.
function sayHello(name) { console.log('Hello, ' + name + '!'); } sayHello('Alice'); // Output: Hello, Alice!
The return keyword allows a function to send a value back to the place where it was called. This value can be stored in a variable or used directly.
function multiply(a, b) { return a * b; } let result = multiply(2, 4); console.log(result); // Output: 8
In addition to defining functions with the function keyword, you can also create them as expressions and assign them to variables.
const sayGoodbye = function() { console.log('Goodbye!'); }; sayGoodbye(); // Output: Goodbye!
Anonymous functions are functions that don’t have a name. They are often used in situations where you only need a function once, like passing it as an argument to another function.
setTimeout(function() { console.log('This will run after 2 seconds'); }, 2000); // Output: This will run after 2 seconds
Arrays are special variables that can hold more than one value at a time. They are like lists that you can store multiple items in, and you can access each item by its position in the list, called an index.
let fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // Output: apple console.log(fruits[1]); // Output: banana console.log(fruits[2]); // Output: cherry
The .length property tells you how many items are in an array.
let fruits = ['apple', 'banana', 'cherry']; console.log(fruits.length); // Output: 3
The .push() method adds one or more items to the end of an array.
let fruits = ['apple', 'banana']; fruits.push('cherry'); console.log(fruits); // Output: ['apple', 'banana', 'cherry']
The .pop() method removes the last item from an array and returns it.
let fruits = ['apple', 'banana', 'cherry']; let lastFruit = fruits.pop(); console.log(fruits); // Output: ['apple', 'banana'] console.log(lastFruit); // Output: cherry
You can access items in an array by using their index number, starting from 0.
let fruits = ['apple', 'banana', 'cherry']; console.log(fruits[1]); // Output: banana
The .map() method creates a new array by applying a function to each item in the original array.
let numbers = [1, 2, 3, 4]; let squares = numbers.map(function(number) { return number * number; }); console.log(squares); // Output: [1, 4, 9, 16]
The .concat() method joins two or more arrays and returns a new array.
let fruits = ['apple', 'banana']; let vegetables = ['carrot', 'lettuce']; let food = fruits.concat(vegetables); console.log(food); // Output: ['apple', 'banana', 'carrot', 'lettuce']
The .forEach() method executes a function once for each item in an array.
let fruits = ['apple', 'banana', 'cherry']; fruits.forEach(function(fruit) { console.log(fruit); }); // Output: apple // Output: banana // Output: cherry
Loops allow you to repeat a block of code multiple times. They are useful when you want to perform the same action for each item in a list, or until a certain condition is met.
for (let i = 0; i < 3; i++) { console.log('This is loop iteration ' + i); } // Output: This is loop iteration 0 // Output: This is loop iteration 1 // Output: This is loop iteration 2
The for loop repeats a block of code a specific number of times. You define the start, end, and step of the loop.
for (let i = 1; i <= 5; i++) { console.log(i); } // Output: 1 // Output: 2 // Output: 3 // Output: 4 // Output: 5
The while loop repeats a block of code as long as a certain condition is true. It's useful when you don't know in advance how many times you need to repeat something.
let count = 0; while (count < 3) { console.log('Counting: ' + count); count++; } // Output: Counting: 0 // Output: Counting: 1 // Output: Counting: 2
Sometimes you need to exit a loop before it has run through all its iterations. You can use the break statement to do this.
for (let i = 1; i <= 5; i++) { if (i === 3) { break; } console.log(i); } // Output: 1 // Output: 2
The continue statement allows you to skip the rest of the code inside a loop for the current iteration and move on to the next iteration.
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i); } // Output: 1 // Output: 2 // Output: 4 // Output: 5
The forEach loop is a method specifically designed for arrays. It runs a provided function once for each array element.
let fruits = ['apple', 'banana', 'cherry']; fruits.forEach(function(fruit) { console.log(fruit); }); // Output: apple // Output: banana // Output: cherry
The do...while loop is similar to the while loop, but it guarantees that the code inside the loop runs at least once, even if the condition is false.
let count = 0; do { console.log('Counting: ' + count); count++; } while (count < 3); // Output: Counting: 0 // Output: Counting: 1 // Output: Counting: 2
Loops are often used with arrays to iterate over each element and perform actions like printing, adding, or modifying elements.
let numbers = [1, 2, 3, 4, 5]; let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum); // Output: 15
A nested loop is a loop inside another loop. It's useful when you have to deal with multi-dimensional arrays or repeat actions multiple times for each iteration of the outer loop.
for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log('i=' + i + ', j=' + j); } } // Output: i=1, j=1 // Output: i=1, j=2 // Output: i=1, j=3 // Output: i=2, j=1 // Output: i=2, j=2 // Output: i=2, j=3 // Output: i=3, j=1 // Output: i=3, j=2 // Output: i=3, j=3
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!