'Function Expression (JavaScript)

Convert the function named functionDeclaration to an anonymous function expression and assign it to a variable called myFunc.

function functionDeclaration() {
  let myFunc = str
   return "Hi there!";

}

console.log(myFunc())

I'm new to coding. What am I doing wrong? It's supposed to print 'Hi there!' but keeps giving me a reference error message.

Thank you for your help!



Solution 1:[1]

Your function expression could be like,

const func = function functionDeclaration() {
    return "Hi there!";
 }
 
 let myFunc = func()
 console.log(myFunc);

Solution 2:[2]

I am not sure what is the purpose of let myFunc = str, but give this a try -

function functionDeclaration() {
  // let myFunc = str
  return "Hi there!";
}

const myFunc = () => {
  return functionDeclaration.call(this);
}

console.log(myFunc());

Solution 3:[3]

Your answer:

let myFunc = function() {
    return "Hi there!";
}

Please read Constructor vs. declaration vs. expression

Solution 4:[4]

It same as :

const func = function() {
  return `Hi there!`
}
console.log(func())

let myfunc = func
console.log(myfunc())

const func1 = function(name) {
  return `Hi my name is ${name}!`
}
console.log(func1('abc'))

let myfunc1 = func1
console.log(myfunc1('xyz'))

myfunc = func1

console.log(myfunc('123'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sujith Sandeep
Solution 2 sunil vishwakarma
Solution 3 Phalgun
Solution 4 Xupitan