avaScript is a widely-used programming language in web development. Whether you're a beginner or an experienced developer, it's essential to know some fundamental programs in JavaScript. The following programs are a must-know for every developer to get started with JavaScript programming.
As a language that is widely used in web development, JavaScript is essential for every developer to master. Here are 10 must-know JavaScript programs that every developer should know:
Hello, World! - This is a basic program same as the string palindrome program in Java that prints "Hello, World!" to the console. It's the traditional first program for learning any programming language.
console.log("Hello, World!");
2. FizzBuzz - This program prints numbers from 1 to 100, but replaces multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".
for (let i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log("FizzBuzz");
} else if (i % 3 == 0) {
console.log("Fizz");
} else if (i % 5 == 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
3. Factorial - This program calculates the factorial of a given number using recursion.
function factorial(num) {
if (num == 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
4. Fibonacci - This program generates the Fibonacci sequence up to a given number using recursion.
function fibonacci(num) {
if (num <= 1) {
return 1;
} else {
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
5. Reverse a String - This program reverses a given string.
function reverseString(str) {
return str.split("").reverse().join("");
}
6. Palindrome Checker - This program checks if a given string is a palindrome.
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return str == str.split("").reverse().join("");
}
7. Sorting an Array - This program sorts an array of numbers in ascending order using the bubble sort algorithm.
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
8. Finding the Largest Number in an Array - This program finds the largest number in an array.
function largestNumber(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
9. Calculating the Sum of an Array - This program calculates the sum of an array of numbers.
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
Comentarios