Coding Concept - Developing Procedures
Understanding Developing Procedures in Python and JavaScript
%%js
// Homework: Developing Procedures in JavaScript
// 1. Write a procedure that takes a number and returns its cube.
function cube(n) {
return n * n * n;
}
// 2. Write a procedure that takes an array of numbers and returns the sum.
function listSum(numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
// 3. Write a procedure that checks if a word is a palindrome.
function isPalindrome(word) {
const reversed = word.split('').reverse().join('');
return word === reversed;
}
// Test the functions
console.log(cube(3)); // 27
const nums = [1, 2, 3];
console.log(listSum(nums)); // 6
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("apple")); // false
<IPython.core.display.Javascript object>
1. cube(n) Function
- Purpose: This function takes a number n and returns its cube (i.e., n raised to the power of 3).
- How it works: The function multiplies the number n by itself three times.
2. ListSum(numbers) Function
- Purpose: This function takes an array of numbers and returns the sum of those numbers.
- How it works: The function initializes a total variable to 0, then loops through each number in the array numbers using a for…of loop. In each iteration, the current number is added to total.
3. isPalindrome(word) Function
- Purpose: This function checks if a given word is a palindrome, meaning it reads the same forwards and backwards.
- How it works: The function splits the word into an array of characters word.split(), reverses that array reverse(), then joins the characters back together into a string join(). Finally, it checks if the reversed word is the same as the original word.
Console Output:
The console.log statements test the functions:
- cube(3) prints 27, as it returns the cube of 3.
- listSum([1, 2, 3]) prints 6, as it returns the sum of 1, 2, and 3.
- isPalindrome(racecar) prints true, as racecar is a palindrome.
- isPalindrome(apple) prints false, as apple is not a palindrome.