Why function deceleration overrides

twitter logo github logo ・1 min read


var myName = "Richard"; 

function myName () {
console.log ("Rich");
}

console.log(typeof myName)

////output is string

but when i code function in other way like in above code, giving different output

var myName = "Richard"; 

myName = function() {
console.log ("Rich");
}

console.log(typeof myName)

////output is  function


twitter logo DISCUSS (4)
markdown guide
 

What's happening here is that you've hit the difference between a function expression and function declaration.

function myName () {
console.log ("Rich");
}

This is a function declaration, and it is subject to a javascript feature called hoisting, which moves it to the top of the scope it's declared in. This means that when you set var myName = "Richard", it actually comes afterwards in the order of execution and overwrites the function.

By contrast, myName = function() { ... } is a function expression, and it is evaluated in place, and behaves as you'd expect with your code laid out as it is.

I actually just wrote a post on this exact thing -- carlanderson.xyz/function-declarat...

 
 
 

It's already explained but you are re-assigning your name variable (the string) to the function.

I'd do this:

// Good :D

const myName = 'Richard'; 

const logMyName = () => {
  console.log(myName);
}

/* 
This example below will throw an 
error because you can't re-assign 
a constant variable so use the 
one I wrote above :)
*/

// Bad :(

myName = () => {
  console.log(myName);
}
Classic DEV Post from Jun 20

Do you use time-tracking for work or for your personal time?

kambala yashwanth profile image
I ❤️ JavaScript > any other ☕ logo languages