Coding Challenges
01. Write a function called "addNumbers" that takes two numbers as arguments and returns their sum. Call the function before it is declared to demonstrate hoisting.
console.log(addNumbers(45, 67));
function addNumbers(num1, num2) {
return num1 + num2;
}
02. Write a function called "multiplyNumbers" that takes two numbers as arguments and returns their product. Use function expressions to define the function and call the function before it is declared to demonstrate hoisting.
multiplyNumbers(5, 10); // Error:
const multiplyNumbers = function(num1, num2) {
return num1 * num2;
};
const multiplyNumbers = function(num1, num2) {
return num1 * num2;
};
console.log(multiplyNumbers(60, 230));
03. Write a function that takes two numbers as arguments and returns their sum. Declare a variable inside the function using the var keyword and log its value to the console before it is assigned a value to demonstrate variable hoisting.
function calculateSum(num1, num2) {
console.log(myVariable); // Output: undefined
var myVariable;
console.log(myVariable); // Output: undefined
myVariable = num1 + num2;
console.log(myVariable); // Output: Sum of num1 and num2
}
calculateSum(5, 10);
04. Declare three variables, one using let, one using var, and one using const, all inside a block scope. Assign them values and log their values to the console before and after they are declared to demonstrate variable hoisting.
{
console.log(letVariable); // ReferenceError: Cannot access 'letVariable' before initialization
console.log(varVariable); // undefined
console.log(constVariable); // ReferenceError: Cannot access 'constVariable' before initialization
let letVariable = 'Let Variable';
var varVariable = 'Var Variable';
const constVariable = 'Const Variable';
console.log(letVariable); // Output: Let Variable
console.log(varVariable); // Output: Var Variable
console.log(constVariable); // Output: Const Variable
}
05. Declare a variable using let inside a block scope and attempt to log its value to the console before it is assigned a value to demonstrate the temporal dead zone.
{
console.log(variable); // ReferenceError: Cannot access 'variable' before initialization
let variable = 'Value';
}
{
let variable = 'Value';
console.log(variable); // Output: Value
}